CBSE CS

cbse cs logo

Home

Elementary Concepts of Python

Python Character Set

 

Python uses the character set to declare identifier as given below:

  • Letters A-Z , a-z
  • Digits 0-9
  • Special Symbols Space + – * / ^ \ ( ) [ ] { } = != < > . „ “ $ , ; : % ! & ? _ # <= >= @
  • White Spaces Blank spaces, horizontal tab, carriage return

Tokens in Python

 

The smallest individual unit of the program is known as Token.

There are five types of Tokens in Python:

  • Keywords
  • Identifiers (variables and others )
  • Literals
  • Delimiters or Punctuators
  • Operators

Keywords in Python

 

Here are some examples of keywords in Python:

if – used to start an if statement.
else – used to define the block of code to be executed if the if condition is false.
elif – used to add more conditions to the if statement.
while – used to start a while loop.
for – used to start a for loop.
def – used to define a function.
return – used to return a value from a function.
try – used to start a block of code to be tested for errors.
except – used to define the block of code to be executed if an error occurs.
finally – used to define the block of code to be executed regardless of whether an error occurs or not.
These are just a few examples of keywords in Python. There are many more, and you can find a full list of Python keywords by typing help(“keywords”) in the Python shell.

Identifiers (Variable names )

Identifiers are the name given by the programmer to objects/parts of a program.

1. Can be of any size

2. It should have allowed characters, which are a-z, A-Z, 0-9 and underscore (_)

3. It must begin with an alphabet or underscore

4. It should not be a keyword

It is a good practice to follow these identifier naming conventions:

1. Variable name should be meaningful and short

2. Generally, they are written in lower case letters

 

Variables

 

  • A variable in a program is uniquely identified by a name .
  • Variable is an object / an item or element that is stored in the memory.
  • Variables must always be assigned values before they are used in expressions.

For example –
Num=10
City=”Bikaner”
A variable has three main components: Identity , Type and a Value .

 

Every Variable (object) has:

A. Identity, – can be known using id (object)

  • Identity of the object: It is the object’s address in memory and does not change once it has been created.

B. type – can be checked using type (object) and

  • It is a set of values, and the allowable operations on those values.

C. value

  • – to bind value to a variable, we use assignment operator (=). This is also known as building of a variable. Example

>>> pi = 31415

Literals 

  • The values which are assigned to variable or are use in expression or in print statement in a program are called Literals. Literals can be defined as a data that is given in a variable or constant.

    Python support the following literals:

    I. String literals

    II. Numeric literals

    III. Boolean literals

    IV. Special literals

    V. Literal Collections

 

Punctuators

 

Punctuators are symbols that are used in programming languages to organize sentence structure, and indicate the rhythm and emphasis of expressions, statements, and program structure.
Common punctuators are: „ “ # $ @ []{}=:;(),.

Operators

 

Operators are special symbols which represents computation. They are applied on operand(s), which can be values or variables.

Same operator can behave differently on different data types. Operators when applied on operands form an expression.

Operators are categorized as 

  • Arithmetic
  • Relational
  • Logical
  • Assignment

Value and variables when used with operator are known as operands.
In Python, an operator is a symbol or a sequence of symbols used to perform a specific operation on one or more operands. Here are some examples of operators in Python:

  • Arithmetic operators: used to perform mathematical operations on numeric operands. Examples include + (addition), – (subtraction), * (multiplication), / (division), % (modulus), and ** (exponentiation).
  • Assignment operators: used to assign a value to a variable. Examples include = (simple assignment), += (increment assignment), -= (decrement assignment), *= (multiplication assignment), /= (division assignment), and %= (modulus assignment).
  • Comparison operators: used to compare two values and return a Boolean value (True or False). Examples include == (equality), != (inequality), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).
  • Logical operators: used to combine Boolean values and return a Boolean result. Examples include and (logical and), or (logical or), and not (logical not).
  • Bitwise operators: used to perform operations on binary numbers. Examples include & (bitwise and), | (bitwise or), ^ (bitwise exclusive or), ~ (bitwise complement), << (left shift), and >> (right shift).
  • Identity operators: used to compare the identity of two objects. Examples include is (object identity) and is not (negated object identity).
  • Membership operators: used to test if a value is a member of a sequence. Examples include in (membership) and not in (negated membership).

These are just a few examples of operators in Python. There are many more, and you can find a complete list in the Python documentation.

Arithmetic operators

 

Arithmetic operators in Python are used to perform mathematical operations on numeric operands. Here are the different arithmetic operators in Python and their meanings:

  1. Addition (+): Adds two operands together.

    Example: 3 + 4 returns 7.

  2. Subtraction (-): Subtracts the second operand from the first.

    Example: 6 – 2 returns 4.

  3. Multiplication (*): Multiplies two operands together.

    Example: 5 * 2 returns 10.

  4. Division (/): Divides the first operand by the second.

    Example: 10 / 2 returns 5.0.

    Note that the result of division is always a float, even if the operands are integers.

  5. Modulus (%): Returns the remainder of dividing the first operand by the second.

    Example: 9 % 2 returns 1.

  6. Exponentiation (**): Raises the first operand to the power of the second.

    Example: 2 ** 3 returns 8.

Arithmetic operators can be used with numeric values of different types (e.g., integers, floats, etc.). Additionally, arithmetic operators can be combined with assignment operators to modify the value of a variable. For example, x += 5 is equivalent to x = x + 5. 

Relational operators

Relational operators in Python are used to compare two values and return a Boolean value ( True or False ) based on the comparison. Here are the different relational operators in Python and their meanings:

  1. Equal to ( == ): Returns True if the first operand is equal to the second operand.

    Example: 2 == 2 returns True . 

  2. Not equal to ( != ): Returns True if the first operand is not equal to the second operand.

    Example: 3 != 4 returns True .

  3. Greater than ( > ): Returns True if the first operand is greater than the second operand.

    Example: 5 > 3 returns True .

  4. Less than ( < ): Returns True if the first operand is less than the second operand.

    Example: 2 < 4 returns True .

  5. Greater than or equal to ( >= ): Returns True if the first operand is greater than or equal to the second operand.

    Example: 5 >= 5 returns True .

  6. Less than or equal to ( <= ): Returns True if the first operand is less than or equal to the second operand.

    Example: 3 <= 4 returns True .

Relational operators can be used with values of different types, including numeric types, string types, and others. When comparing values of different types, Python automatically performs type conversion if possible to make the comparison. It’s important to note that relational operators have lower precedence than arithmetic operators, so expressions with both types of operators may need parentheses to enforce the desired order of operations

Logical operators

Logical operators in Python are used to combine Boolean values and return a Boolean result. Here are the different logical operators in Python and their meanings:

  1. Logical AND ( and ): Returns True if both operands are True , and False otherwise.

    Example: True and False returns False .

  2. Logical OR ( or ): Returns True if either operand is True , and False otherwise.

    Example: True or False returns True .

  3. Logical NOT ( not ): Returns the opposite Boolean value of the operand.

    Example: not True returns False .

Logical operators can be used with Boolean values or expressions that evaluate to Boolean values. They can also be combined with parentheses to enforce the desired order of operations. Logical operators follow short-circuit evaluation, meaning that if the result of the expression can be determined by evaluating only one operand, the other operand is not evaluated. For example, if the first operand of a logical AND expression is False , the second operand is not evaluated because the result will be False regardless. Similarly, if the first operand of a logical OR expression is True , the second operand is not evaluated because the result will be True regardless.

Assignment operators

 

Assignment operators in Python are used to assign a value to a variable. Here are the different assignment operators in Python and their meanings:

  1. Simple assignment ( = ): Assigns the value on the right-hand side to the variable on the left-hand side.

    Example: x = 3 assigns the value 3 to the variable x .

  2. Addition assignment ( += ): Adds the value on the right-hand side to the variable on the left-hand side and assigns the result to the variable on the left-hand side.

    Example: x += 5 is equivalent to x = x + 5 .

  3. Subtraction assignment ( -= ): Subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result to the variable on the left-hand side.

    Example: x -= 2 is equivalent to x = x – 2 .

  4. Multiplication assignment ( *= ): Multiplies the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable on the left-hand side.

    Example: x *= 4 is equivalent to x = x * 4 .

  5. Division assignment ( /= ): Divides the variable on the left-hand side by the value on the right-hand side and assigns the result to the variable on the left-hand side.

    Example: x /= 2 is equivalent to x = x / 2 .

  6. Modulus assignment ( %= ): Computes the modulus of the variable on the left-hand side and the value on the right-hand side, and assigns the result to the variable on the left-hand side.

    Example: x %= 3 is equivalent to x = x % 3 .

  7. Exponentiation assignment ( **= ): Raises the variable on the left-hand side to the power of the value on the right-hand side and assigns the result to the variable on the left-hand side.

    Example: x **= 2 is equivalent to x = x ** 2 .

Assignment operators are commonly used in Python to update the value of a variable based on its current value.

Identity operators in Python

 

The identity operators in Python are used to compare the memory locations of two objects to check if they are the same object or not. There are two identity operators in Python:

  1. is : Returns True if both operands refer to the same object, and False otherwise.

    Example: x = [1, 2, 3] and y = [1, 2, 3] . Although x and y have the same values, they are not the same object, so x is y returns False .

  2. is not : Returns True if both operands do not refer to the same object, and False otherwise.

    Example: x = [1, 2, 3] and y = [4, 5, 6] . Since x and y are not the same object, x is not y returns True .

Identity operators are useful when you want to check if two variables are referring to the same object in memory, rather than just having the same value. However, it’s important to note that the use of is and is not should be used carefully, especially when dealing with mutable objects like lists or dictionaries, as they can be modified in place and may result in unexpected behavior.

Membership operators

The membership operators in Python are used to test if a value is a member of a sequence, such as a string, list, or tuple. There are two membership operators in Python:
  1. in : Returns True if the value on the left-hand side is found in the sequence on the right-hand side, and False otherwise. Example: x = ‘hello’ and ‘e’ in x returns True , while ‘z’ in x returns False .
  2. not in : Returns True if the value on the left-hand side is not found in the sequence on the right-hand side, and False otherwise. Example: x = [1, 2, 3] and 4 not in x returns True , while 1 not in x returns False .
Membership operators are commonly used in Python to test if a value is present in a list, tuple, or string, among other sequence types. They are also useful when working with conditional statements, such as if-else statements or loops, to determine if a value is included in a sequence.

Precedence of Operators in Python

 

The precedence of operators in Python determines the order in which different operators are evaluated in an expression. When multiple operators are used in an expression, Python evaluates them in a specific order, based on their precedence level. Here’s a summary of the precedence of operators in Python, from highest to lowest: 

  1. Parentheses () : Used to group expressions and force evaluation order.
  2. Exponentiation ** : Used to raise a value to a power.
  3. Positive and negative sign +x , -x : Used to indicate the sign of a value.
  4. Multiplication, division, and remainder * , / , % : Used to perform arithmetic operations.
  5. Addition and subtraction + , – : Used to perform arithmetic operations.
  6. Bitwise shift << , >> : Used to shift the bits of a value.
  7. Bitwise AND & : Used to perform bitwise logical operations.
  8. Bitwise XOR ^ : Used to perform bitwise logical operations.
  9. Bitwise OR | : Used to perform bitwise logical operations.
  10. Comparison == , != , > , < , >= , <= , is , is not , in , not in : Used to compare values.
  11. Logical NOT not : Used to invert a boolean value.
  12. Logical AND and : Used to perform logical operations.
  13. Logical OR or : Used to perform logical operations.

 

Associative of Operators in Python

 

An operator may be Left-associative or Right –associative.

In left associative, the operator falling on left side will be evaluated first.

Examples: +,-,*,/ are left associate

In right associative operator falling on right will be evaluated first.

Example “=” and “**” are Right Associative.

 

When multiple operators with the same precedence level are used in an expression, Python evaluates them from left to right. Parentheses can be used to change the order of evaluation and force specific operations to be performed before others.

 

Data types in Python

 
In Python, a data type is a classification of data items that indicate the type of value that they represent. Different data types in Python are used to represent different kinds of data such as numbers, text, and boolean values. Here are some of the commonly used data types in Python:
  1. Numeric Types: Numeric types are used to represent numbers in Python. There are three numeric types in Python:
    • Integer (int): Used to represent whole numbers.
    • Floating-point number (float): Used to represent decimal numbers.
    • Complex (complex): Used to represent numbers with a real and imaginary part.
  2. String (str): A string is a sequence of characters enclosed in quotation marks. Strings are used to represent text data in Python.
  3. Boolean (bool): A boolean data type can have two possible values: True or False . Booleans are used to represent logical values.
  4. List (list): A list is a collection of items, where each item can be of any data type. Lists are mutable, meaning that their elements can be changed.
  5. Tuple (tuple): A tuple is similar to a list, but it is immutable, meaning that its elements cannot be changed.
  6. Set (set): A set is an unordered collection of unique elements. Sets are used to perform mathematical operations like union and intersection.
  7. Dictionary (dict): A dictionary is a collection of key-value pairs. Each key is associated with a value, and the keys must be unique.
In Python, data types are dynamically assigned, meaning that the data type of a variable can change depending on the value it holds. To determine the data type of a variable, you can use the built-in type() function.

Mutable and Immutable Types

 
  • Mutable data types: Data types where the value can be changed in place.    :
    Example :  dictionary, sets, lists etc.
  • Immutable data types: Data types where the values cannot be changed in place.
    Example: integer, float, string, tuples etc.

Expression

 

An expression is defined as a combination of constants, variables, and operators. An expression always evaluates to a value. A value or a standalone variable is also considered as an expression but a standalone operator is not an expression. 

Some examples of valid expressions are given below.
(i) 750 (iv) 5.0 + 9.54 (ii) avg (v) 23/3 -5 * 7 +(14 -2*a) (iii) num – 20 (iv) “India” + “Russia

 

Statement

Statement- In Python, a statement is a unit of code that the Python interpreter can execute.

For example
a=50
x=sum(4,5)

While writing Python statements, keep the following points in mind:

 

  1. Write one python statement per line (Physical Line). Although it is possible to write two statements in a line separated by semicolon.
  2. Comment starts with “#” outside a quoted string and ends at the end of a line. Comments are not part of statement. They may occur on the line by themselves or at the end of the statement. They are not executed by
    interpreter.
  3. For a long statement, spanning multiple physical lines, we can use “/” at the end of physical line to logically join it with next physical line. Use of the “/” for joining lines is not required with expression consists of ( ), [ ], { }
  4. When entering statement(s) in interactive mode, an extra blank line is treated as the end of the indented block.
  5. Indentation is used to represent the embedded statement(s) in a compound/ Grouped statement. All statement(s) of a compound statement must be indented by a consistent no. of spaces (usually 4)
  6. White space in the beginning of line is part of indentation, elsewhere it is not significant.
error: Content is protected !!