0% found this document useful (0 votes)
3 views

Class XI -Python Basics

Python is a high-level, interpreted programming language known for its readability, extensive libraries, and portability across platforms. It supports both interactive and script modes for executing code, and utilizes variables, data types, and comments to structure programs. Key features include dynamic memory management, extensibility with other languages, and a simple syntax that enhances ease of learning and use.

Uploaded by

Soham Mukherjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Class XI -Python Basics

Python is a high-level, interpreted programming language known for its readability, extensive libraries, and portability across platforms. It supports both interactive and script modes for executing code, and utilizes variables, data types, and comments to structure programs. Key features include dynamic memory management, extensibility with other languages, and a simple syntax that enhances ease of learning and use.

Uploaded by

Soham Mukherjee
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Python is a high-level (human-readable) programing language that is

processed by the Python “interpreter” to produce results.

Interpreter is a language processor which translates high level language


(Source program) statement line by line into a sequence of machine
instructions and them executes these machine instructions before translating
the next source language statement.

1
• Python is free – is open source distributable software.
• Python is easy to read and learn – has a simple English language syntax and is uncluttered by punctuation.
• Python has extensive libraries – provides a large standard libraries for easy integration into your own
programs. The presence of libraries also makes sure that you don’t need to write all the code yourself and
can import the same from those that already exist in the libraries.
• Python is interactive – has a terminal for debugging and testing snippets of code (You can actually sit at a
Python prompt and interact with the interpreter directly to write your programs).
• Python is portable – runs on a wide variety of hardware platforms (Mac/Linux/Windows)and has the
same interface on all platforms.
• Python is interpreted – If you’re familiar with any languages like C++ or Java, you must first compile it, and
then run it. But in Python, there is no need to compile it. Internally, its source code is converted into an
immediate form called bytecode. So, all you need to do is to run your Python code without worrying about
linking to libraries, and a few other things.

• Python is high-level – has automatic memory management.


• Python is extensible – Extensible feature in python refers that you can write some of your Python code
in other languages like C or C++. It means that it can be extended to other languages which makes python
an extensible language. It's not extending the language itself (syntax, constructs, etc), but it lets you
interface python with libraries written in other languages. Simply means you can write code in other
languages in your python source code. 2
Bytecode is program code
that has been compiled
from source code into
low-level code designed
for a software interpreter.
It may be executed by a
virtual machine (such as a
PVM) or further compiled
into machine code, which
is recognized by the
processor.

3
If Python is installed in your system, then you can start at command line or
IDLE (It is a graphical integrated development environment for Python).

Click Start.
Click All Programs >> Python 3.7 >> Python 3.7 (64-bit)

You will see that the Python (command line) window appears with the Python >>> primary prompt
as shown below:

Python interactive prompt waitingfor


Python command

4
To start Python at shell prompt:
• Click Start >> All Programs >> Python 3.7 >> IDLE (Python 3.7 32-bit)
• Double click on the desktop

When you start the Python GUI program, you will see the Python Shell window containing
the Python >>> primary prompt.

Python prompt in Python Shell and


active cursor waiting for Python
command

5
There are two modes to use the python interpreter:
i. Interactive Mode
ii. Script Mode

i. Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
output: 9

Note: >>> is a prompt , which python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.

6
Script Mode: In this mode source code is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter, you
have to tell the interpreter the name of the file.

Example:
To run the script you have to follow the steps given below:
Step-1: In Python Shell window, click File >> New File or click Ctrl+N.
Note. If you already have a program file with .py extension, click File >> Open Or click
Ctrl+O to open .py file.
Notice that an Untitled window appears as shown below:
Click here to create a program in new window

Enter Python code overhere

7
Step-2: Click File >> Save or Press Ctrl + S. Like other windows applications, in Save As
window, select a folder, type the name of the file (Hello) and click Save button. You
will notice that the named file is saves as .py extension.
To run Python program:
Step-3: Click Run >> Run Module command or Click F5 key.
If the code is written correctly, you will see the output in the Python Shell window with
following output:

8
Python Character Sets & Tokens

Letters: Both lowercase (a, b, c, d, ...., etc.) and uppercase (A, B, C, D, ...., etc..) letters

Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special symbols: _, (, ), [, ], {, }, +, -, *, /, %, !, &, |, ~, ^, <, =, >, $, #, ?, Comma (,), Dot (.),


Colon (:), Semi-colon (;), Single quote ('), Double quote ("), Back slash (\)

White space: Space, Tab (¦), New line (8)

9
Python Tokens

Python Tokens

Keywords Identifiers Operators Literals

Delimiters

Keywords: Reserved words in the library of a language. All the keywords are in lowercase
except 03 keywords (True, False, None).
Ex: and, as, break, class, continue, def, elif etc
Identifiers: The name given by the user to the entities like variable name, class-name,
function-name etc.
Ex: roll_no, salary, name, sep98_score

10
Literals: Literals are the constant value. Literals can be defined as a data that is given in
a variable or constant.

• Numeric literals - 3,4+5


• String literals – ‘XYZ’
• Boolean literals - True or False
• Special literals – None
None is used to specify to that field that is not created. It is also used for end of
lists in Python
• Literal Collections: Collections such as tuples, lists and Dictionary.

11
Operators: An operator performs the operation on operands. Basically there are two
types of operators in python according to number of operands.
• Unary Operator: Performs the operation on one operand.
Example:
x=+2
y=-x

• Binary Operator: Performs operation on two operands.


Example:
x=a+b
y=a-b

Delimiters: A delimiter is a sequence of one or more characters used to specify the


boundary between separate, independent regions in plain text or other data streams.
Example : , ; , ( ), { }, [ ]

12
Variables
Variable is a container in which a data value can be stored within the computer’s memory.
The stored value can then be referenced using the variable’s name. The programmer can
choose any name for a variable, except the python keywords.

Data to be stored in a variable is assigned in a python program declaration statement with


the assignment operator (=). The assignment statement assigns a value to a variable.

Variable = Value/Expression
L-Value Assignment R-Value
Operator
• Variable is an identifier.
• Value/Expression is an expression with a value or some calculation, function, etc.
• Variable refers to an L-value because it resides in memory and it is addressable
and Value/Expression is an R-value i.e., a value that is not L-value.
In concept, R-value correspond to temporary objects returned from functions, while L-values
correspond to objects you can refer to, either by name or by following a L-value reference.
Python first evaluates the RHS expression and then assigns to LHS.
13
Examples:
>>> Num1 = 10 # Assigns an integer value
>>> Num2 = 20 # Assigns an integer value
>>> sumN = Num1 + Num2 # An expression
>>> PiValue = 3.14 # A floating-point value
>>> MyName = "XYZ" # A string

Python is Dynamic – Python variables adjust the memory allocation to suit the various
data values assigned to their variables (dynamic).

Initialize variables with integer values. Assign a string value to the variable.
A, B = 10, 20 Message = 'Python in middle schools.'
C=A+B

Assign a float value to the variable. Assign a Boolean value to the variable.
PiValue = 4.13 Flag = True

14
Variable Declaration Rules
Some basic rules to declare variables in Python:
• Variable names can be as short as a single letter either in uppercase or
lowercase.
• Variable names must begin with a letter or an underscore ('_').
• After the first letter or underscore, they can contain letters, numbers, and additional
underscores. For example totalCost, y2014, _sysVal, _my_name, _my_name, etc.
• Variable names are case-sensitive. For example, myname and myName are not the same
names, they are two different variables.
• Variable names should not be reserved words or keywords. That is, variables cannot have the
same name as a Python command or a library function. For example, while, if, etc. cannot be
declared as variable name.
• No blank spaces are allowed between variable name. Also, it cannot use any special
characters (such as @, $, %, etc. ) other than underscore ('_').
• Variables or identifiers can be of unlimited length. 15
Valid Variable Names
roll_no, Salary ,sep98_score, index_age, percentageamount, dob, Cust_no, D_o_j, _my_name

Invalid variable names with reason


>>> Your Age
SyntaxError: invalid syntax because variable contains space

>>> while
SyntaxError: invalid syntax because variable is a reserve word

>>> myname@
SyntaxError: invalid syntax because variable contains a special character

>>> 98Sep_score
SyntaxError: invalid syntax because variable start with a digit

16
Way to Assign Value to Variable
There are different ways to assign value to a variable.

Assigning an expression. An expression can be assigned into a variable.


Example:
>>> x = 10 x 10

>>> x = 3.9 * x * (1 – x) # An expression


>>> print (x) # Returns: –351.0

x –351.0

>>> Fahrenheit = 9.0 / 5.0 * Celsius + 32 # An expression


>>> print (Celsius, Fahrenheit) # Returns: 40, 104.0

17
A variable can be assigned many times. It always retains the value of the most
recent assignment.

Var1 = 7 Var1 = 0 Var1 = Var1 + 10

7 0 10

Example:
>>> Var1 = 7
>>> Var1 # Returns: 7
>>> Var1 = 0 # Returns: 0
>>> Var1
>>> Var1 = Var1 + 10
>>> Var1 # Returns: 10

18
Assigning a value to multiple variables: In Python, we can assign a value to multiple variables.
Example:
>>> a = b = c = d = 5
>>> print (a, b, c, d) # Returns: 5, 5, 5, 5
Here, all the variables a, b, c and d are assigned a single value called 5.

Multiple assignments in a single line. You can even assign values to multiple variables in a single line.
While assigning, the left and the right side must have the same number of elements. The general
format is:
<var1>, <var2>, <var3>, …. <varN> = <expr1>, <expr2>, <expr3>, ….<exprN>
This is called simultaneous assignment. Semantically, this tells Python to evaluate all the
expressions on the right-hand side and then assign these values to the corresponding
variables named on the left-hand side. If the variables in left-
hand side differs with
Example: the values with right-
hand side and vice-
versa, then an exception
will raised and the
program will stop.

19
Example:

p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p,q,r)

Now the result will be:


6 6 12

Note: Expressions separated with commas are evaluated from left to right and assigned in
same order.

>>> a,b,a=1,2,3
>>> print(a,b)
?
>>> a,b,c=b+1,a+1,b+1
>>> print(a,b,c)
?

20
Basic terms of a Python Programs

Blocks and Indentation: Python provides no braces to indicate blocks of code for class and
function definition or flow control.
Maximum line length should be maximum 79 characters. Blocks of code are denoted by
line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.
for example – if True:
print(“True”)
else:
print(“False”)
Statements : A line which has the instructions or expressions.

Expressions: A legal combination of symbols and values that produce a result. Generally it
produces a value.

Comments: Comments are not executed. Comments explain a program and make a
program understandable and readable. All characters after the # and up to the end of the
line are part of the comment and the Python interpreter ignores them.
# This is a new line comment.
21
Comments in Python
Comments in Python
Writing a comment as a new line:
Example:
>>> # This is a new line comment.
Here, Python ignores everything after the hash mark and up to the end of
the line.

Writing a comment with statement or expression line:


Example:
>>> a = 12 + 34 # Comment with expression line (in-line comment)
>>> print (a) # Comment with statement line (in-line comment)
When you run the above code, you will only see the output 46. Everything else is
ignored.

22
There are two types of comments in python:

• Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values

• Multiline Comment: While Python doesn’t have native multiline commenting


functionality, you can create multiline comments in Python. There are two simple
ways to do so.

The first way is simply by pressing the return key after each line, adding a new hash
mark and continuing your comment from there:
# This is a pretty good example
# of how you can spread comments
# over multiple lines in Python
Each line that starts with a hash mark will be ignored by the program.

Second way is use multiline strings by wrapping your comment inside a set of triple
quotes:
23
Second way is use multiline strings by wrapping your comment inside a set of triple
quotes:
"""
If I really hate pressing `enter` and
typing all those hash marks, I could
just do this instead
"""
While this gives you the multiline functionality, this isn’t technically a comment. It’s a
string that’s not assigned to any variable, so it’s not called or referenced by your
program. Still, since it’ll be ignored at runtime and won’t appear in the bytecode, it can
effectively act as a comment.

Comments

Expression Statements

Indentation
24
Multiple Statements on a Single Line: The semicolon ( ; ) allows multiple statements
on the single line given that neither statement starts a new code block.
Example:
x=5; print(“Value =” x)

25
Data Types in Python
Every value in Python has a data type and everything in Python is an object.
Python provides various standard data types that define the storage method on each of
them.

26
Number Data Type: Number data type stores Numerical Values. This data type is immutable
i.e. value of its object cannot be changed.
1. int: A Python object of type int an integer, that is, a signed whole number (i.e., signed
integer, 32 bits long). The range is at least –2,147,483,648 to 2,147,483,647 (approximately
±2 billion).
Example:
>>> Num1, Num2 = 1, 10
>>> type(Num1)
<class 'int'>

Notice that the object name of Num1 is defined as <class ‘int’>, i.e., the class type is int.
The type() function tells the data type of the object Num1.

• Boolean: Boolean Type which is a unique data type, consisting of two constants, True
& False. A Boolean True value is Non-Zero, Non-Null and Non-empty.
Example:
>>> flag = True
>>> type(flag)
<class 'bool'>
27
2. Float: A float is a format for representing numbers with fractional parts is called
floating point or real numbers . In a floating point number, the decimal point must
preceded or followed by one or more digits.
Example:
>>> pi = 3.14
>>> type(pi)
<class 'float'>
Notice that the object name of pi is defined as <class ‘float’>, i.e., the class type is float.
If the exponent present consists of either "e" or "E" indicating the power of 10.
Example:
>>> aFloatValue = 3.5e2 It is just equal to 3.5 x 10 x 10
>>> print(aFloatValue) 350.0
3. Complex: Complex number in python is made up of two floating point values, one each
for real and imaginary part. For accessing different parts of variable x; we will use
x.real and x.imag. Imaginary part of the number is represented by “j” instead of “i”,
so 1+0j denotes zero imaginary part.
Example:
>>> x = 1+0j >>> y = 9-5j
>>> print(x.real,x.imag) >>> print(y.real, y.imag)
1.0 0.0 9.0 -5.0 28
None :
This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None.
Example:
>>> a=None
>>> print(a)
Sequence Data Type: A sequence is an ordered collection of items, indexed by positive
integers. It is combination of mutable and non mutable data types. Three types of
sequence data type available in Python are Strings, Lists & Tuples.

1. String: is an ordered sequence of letters/characters. They are enclosed in single


quotes (‘ ’) or double (‟ “). The quotes are not part of string. They only tell the
computer where the string constant begins and ends. They can have any character or
sign, including space in them. These are immutable data types.
Example
>>> a = 'Ram’
A string with length 1 represents a character in Python.

29
2. Lists: List is also a sequence of values of any type. Values in the list are called
elements / items. These are mutable and indexed/ordered. List is enclosed in square
brackets.
Example
l = [“sam”, 20.5,5]

3. Tuples: Tuples are a sequence of values of any type, and are indexed by integers.
They are immutable. Tuples are enclosed in ().
Example
t= (4, 2)

Sets: Set is an unordered collection of values, of any type, with no duplicate entry. Sets
are immutable.
Example
s = set ([1,2,34])

30
Dictionaries: Can store any number of python objects. What they store is a key – value
pairs, which are accessed using key. Dictionary is enclosed in curly brackets.
Example :
d = {1:'a',2:'b',3:'c'}

Mutable and Immutable Variables


A mutable variable is one whose value may change in place, whereas an immutable variable
change of value will not happen in place. Modifying an immutable variable will rebuild the
same variable.
Example :
>>>x=5
Will create a value 5 referenced by x
x 5
>>>y=x
This statement will make y refer to 5 of x
x
5
y

31
>>> x=x+y
In the statement, expression on RHS will result into value 10 and when this is assigned
to LHS (x), x will rebuild to 10. So now

x 10 and y 5
Identity of the object: It is the object's address in memory and does not change once it
has been created. Id() function is used to display the memory address.
(We would be referring to objects as variable for now)

32
Printing Data:
print() function is the standard function used to print the output to the console. The general
form of print is
print()
print (value/expr)
print(value, ...., sep=' ', end='\n’)

1. print(): Output displayed by the print() function will, by default, add an invisible \n newline
character at the end of the line to automatically move the print head to the next line.
Example:
>>> print () # Print a blank line

2. print(value/expression): This print() function prints the value of variable or expression.


Example:
>>> N1, N2 = 20, 30
>>> Sum = N1 + N2
>>> print (Sum) # Prints: 50
Or
>>> print (N1 + N2) # Prints: 50
33
3. print(value, ...., sep=' ', end='\n')
This print() function prints message, value, variable, expression, etc. You can print all at once.

The sep parameter is a separator used in between the values. It defaults into a space
character.
Example:
>>> print(10,20,30,40, sep=' * ‘) # Prints a space and separator *

o/p:
10 * 20 * 30 * 40

The end parameter is used to print the last printed character(s). It defaults into a new line.
Example:
>>> # A new end is assigned @
>>> print(10,20,30,40, sep=' * ', end='@’)

o/p:
10 * 20 * 30 * 40@

34
Escape Characters (Non-printing characters):
In Python the backslash "\" is a special character, also called the "escape" character. It is
used in representing certain whitespace characters:
"\t" is a tab
"\n" is a newline
An escape character gets interpreted in a single quoted as well as double quoted strings.

Example:

35
User Input: Just as we assign value to a variable in Python, a user can assign value
to a variable using input() function.
The main purpose of this function is:
• Read input from the standard input (the keyboard, by default).
• By default you can input only the string values not numbers.
The general format is:
input([prompt])
• The prompt is an optional parameter which is a string you wish to display on the
screen.
• The prompt is an expression that serves to prompt the user for input. This is
almost always a string literal which is enclosed within quotes (single or double)
with parentheses.
Example:
# input() function
rollno = input("Enter your roll no. ")
perc = input("Enter your percentage: ")
print ("My roll no. is:", rollno)
print ("My percentage is:", perc)
36
Python Type Conversion and Type Casting
Type Conversion
The process of converting a value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data
type. This process does not need any user involvement.
Example1:

37
Note:
• We add two variables Num1 and Num2, storing the value in Result.
• In the output, we can see the data type of Num1 is an integer while the data type of
Num2 is a float.
• Also, we can see the Result has a float data type because Python always converts smaller
data types to larger data types to avoid the loss of data.

Example2:

38
Note:
• We add two variables Num1 and Num2, storing the value in Result.
• In the output, we can see the data type of Num1 is an integer while the data type of
Num2 is a string.
• As we can see from the output, we got TypeError. Python is not able to use Implicit
Conversion in such conditions.

In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.

This type of conversion is also called typecasting because the user casts (changes) the data
type of the objects.

Syntax :

<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to the expression.
39
Note:
• We add two variables Num1 and Num2.
• We converted Num2 from string(higher) to integer(lower) type using int() function to
perform the addition.
• After converting Num2 to an integer value, Python is able to add these two variables
Points to Remember:
• Type Conversion is the conversion of object from one data type to another data type.
• Implicit Type Conversion is automatically performed by the Python interpreter.
• Python avoids the loss of data in Implicit Type Conversion.
• Explicit Type Conversion is also called Type Casting, the data types of objects are converted
using predefined functions by the user.
• In Type Casting, loss of data may occur as we enforce the object to a specific data type. 40
• int() - constructs an integer number from an integer literal, a float literal (by rounding
down to the previous whole number), or a string literal (providing the string represents a
whole number)
Example: x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
Example: x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0

• str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
Example: x = str("s1") # x will be 's1’
y = str(2) # y will be '2’
z = str(3.0) # z will be '3.0'

41
Python Operators
In Python, operators are the special symbols which carry out arithmetic and logical operations.
The value that the operator operates on is called operand.

Various operators in Python are:


1. Arithmetic Operators
2. Relational Operators
3. Assignment Operators
4. Logical Operators
5. Special Operators

42
Arithmetic operators - Used to perform mathematical operations like addition, subtraction,
multiplication, etc.

Operator Operation Result (When x, y, s = 20, 10, 0)


+ Addition s=x+y # returns: 30

– Subtraction s=x–y # returns: 10

* Multiplication s=x*y # returns: 200

/ Division s=x/y # returns: 2.0

% Modulo s=x%y # returns: 0

** Exponent s = x ** y # returns: 10240000000000

// Floor division s = x // y # returns: 2


Remember, if the numerator is a floating-point number, it
only add a decimal zero with the result.
E.g., 11.0//4 or float(11)//4 will produce 2.0.

43
Relational Operators – They are also known as Comparison operators which are used to
compare values. It returns either True or False according to the condition.

Operator Name Result (When x, y, s = 20, 10, 0)


== Equality s=x==y # returns: False

!= Inequality s = x != y # returns: True

> Greater than s=x>y # returns: True

< Less than s=x<y # returns: False

>= Greater than or equal s = x >= y # returns: True


to

<= Less than or equal s = x <= y # returns: False

44
Assignment operators - Used in Python to assign values to variables.

Operator Shorthand Expression Result (When s, x = 20, 10)


+= s+=x s=s+x s+=x # returns: 30
–= s–= x s=s–x s–=x # returns: 10
*= s*= x s = s*x s*=x # returns: 200
/= s/=x s = s/x s/=x # returns: 2.0
%= s%= x s = s%x s%=x # returns: 0
**= s**=x s = s**x s**=x # returns: 10240000000000
//= s//=x s = s//x s //= x # returns: 2

45
Logical operators

Operator Operation Result (When x, y = True, False)


and Logical AND Returns: True, if both x and y are True.
Returns: False, if both x and y are False.
Returns: False, if any one is False.
Here,
print (x and y) # Returns: False
or Logical OR Returns: True, if either x or y is True.
Returns: False, if both x and y are False.
Returns: True, if both are True.
Here,
print (x or y) # Returns: True
not Logical NOT If a condition is true then Logical not operator will make
false.
Here,
print (not (x and y)) # returns: True

46
Special operators -

Identity operators :
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does
not imply that they are identical.

Operator Description Example


is Evaluates to true if the variables
on either side of the operator x is y, here is results in 1 if id(x) equals
point to the same object and false id(y).
otherwise.
is not Evaluates to false if the variables
on either side of the operator x is not y, here is not results in 1 if id(x) is
point to the same object and true not equal to id(y).
otherwise.

47
Operator Description Example
in Evaluates to true if it finds a variable
x in y, here in results in a 1 if x is a
in the specified sequence and false
member of sequence y.
otherwise.
not in Evaluates to true if it does not finds x not in y, here not in results in a 1 if x is
a variable in the specified sequence not a member of sequence y.
and false otherwise.

48
Operator precedence rule in Python
Operators Meaning
() Parenthesis
** Exponent

+x, -x Unary plus, Unary minus

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators

not Logical NOT


and Logical AND
or Logical OR

49
Associativity of Python Operators
From the above table we notice that more than one operator exists in the same group.
These operators have the same precedence.

Associativity is the order in which an expression is evaluated that has multiple operator of
the same precedence. Almost all the operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence. Hence, if both of
them are present in an expression, left one is evaluates first.
Example 1: Example 2:

50
Non associative operators
Some operators like assignment operators and comparison operators do not have
associativity in Python. There are separate rules for sequences of this kind of operator
and cannot be expressed as associativity.

For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
< y and y < z, and is evaluates from left-to-right.

Furthermore, while chaining of assignments like x = y = z is perfectly valid, x = y += z will


result into error.
Example:

51

You might also like