0% found this document useful (0 votes)
84 views8 pages

Python Unit 2: Operators & Loops

Uploaded by

Samyak Hirap
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views8 pages

Python Unit 2: Operators & Loops

Uploaded by

Samyak Hirap
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Chapter 2

Notes

Operators:

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators ( not useful for MSBTE )
 Relational operators
 Logical operators
 Identity operators
 Membership operators ( will discuss in list and tuples topic )
 Bitwise operators ( not for MSBTE )

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND


Arithmetic Operators:

Relational Operators:

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND


Logical Operators:

Identity Operators:

Program For Arithmetic Operation


# Store input numbers:
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)
# Subtract two numbers
min = float(num1) - float(num2)
# Multiply two numbers

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND


mul = float(num1) * float(num2)
#Divide two numbers
div = float(num1) / float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
# Display the subtraction
print('The subtraction of {0} and {1} is {2}'.format(num1, num2, min))
# Display the multiplication
print('The multiplication of {0} and {1} is {2}'.format(num1, num2, mul))
# Display the division
print('The division of {0} and {1} is {2}'.format(num1, num2, div))

Conditional Statement

Conditional Statement in Python perform different computations or actions


depending on whether a specific Boolean constraint evaluates to true or false.
Conditional statements are handled by IF statements in Python.

Major Types of Conditional Statement in Python

1. IF
2. IF...ELSE
3. Nested IF

IF Statement :

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND


IF statement is used to execute or check only one statement. If that block is true
then it execute the ode otherwise terminated from the block .

If ( condition ) :

Statements...

......................

IF Else :

It contains a body of code which runs only when the condition given in the if
statement is true. If the condition is false, then the optional else statement runs
which contains some code for the else condition.

if expression
Statement
else
Statement

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND


Nested IF :

We can have a if...elif...else statement inside another


if...elif...else statement. This is called nesting in computer
programming.

Any number of these statements can be nested inside one another. Indentation is
the only way to figure out the level of nesting. They can get confusing, so they
must be avoided unless necessary.

If ( condition ):

If ( condition ):

Statement

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND


Looping in Python

Python programming language provides following types of loops to handle


looping requirements. Python provides three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax
and condition checking time.

1. While Loop:
2. In python, while loop is used to execute a block of statements repeatedly
until a given a condition is satisfied. And when the condition becomes
false, the line immediately after the loop in program is executed.

Syntax :

while expression:
statement(s)

3. All the statements indented by the same number of character spaces after
a programming construct are considered to be part of a single block of
code. Python uses indentation as its method of grouping statements.

For Loop

The for loop in Python is used to iterate over a sequence or other iterable
objects. Iterating over a sequence is called traversal.

Syntax of for Loop

for val in sequence:


Body of for

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND


Here, val is the variable that takes the value of the item inside the sequence on
each iteration.

Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.

Main differences between “for” and “while” loop

 Initialization, conditional checking, and increment or decrement is done


while iteration in “for” loop executed. while on the other hand, only
initialization and condition checking in the syntax can be done.
 For loop is used when we are aware of the number iterations at the time
of execution. on the other hand, in “while” loop, we can execute it even if
we are not aware of the number of iterations.
 If you forgot to put the conditional statement in for loop, it will reiterate
the loop infinite times but if you forgot to put the conditional statement in
while loop, it will show an error to you.
 The syntax in the for loop will be executed only when the initialization
statement is on the top of the syntax but in case of while loop, it doesn’t
matter whether initialization statement finds anywhere in the syntax.
 The iteration will be executed on if the body of the loop executes. on the
contrary, the iteration statement in while loop can be written anywhere in
the syntax.

MSBTE NEXT ICON COURSE YOUTUBE – UR ENGINEERING FRIEND

Common questions

Powered by AI

The syntax for a 'while' loop in Python involves a conditional expression followed by a block of indented statements. It repeats executing the block of statements as long as the condition evaluates to true. Once the condition changes to false, the loop exits, and execution moves to the line immediately after the loop. This is useful for situations where the number of iterations is not predetermined, allowing the loop to run until a certain state is achieved .

Indentation in Python is crucial as it defines the block of code associated with loops and conditional statements. Proper indentation ensures that statements are grouped correctly and executed in the desired order and context. This is particularly important in loops and 'if' statements where incorrect indentation can lead to logic errors, unexpected behavior, or syntax errors. Unlike many other programming languages that use braces or keywords to define code blocks, Python relies purely on indentation, which promotes code clarity but demands careful attention to consistent spacing .

Python uses indentation as a method for grouping statements. In loops, all statements that are indented by the same number of character spaces after a programming construct are considered part of a single block. This indentation signifies that they should be executed as part of the loop .

In Python, conditional statements are used to perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. The main types of conditional statements include 'IF', 'IF...ELSE', and 'Nested IF'. An 'IF' statement is used to execute a block of code if the condition evaluates to true. 'IF...ELSE' includes an additional block of code that executes when the condition is false. 'Nested IF' statements allow embedding multiple conditions by nesting them within each other, which can be useful but also complex .

Arithmetic operations in Python include basic mathematical operations such as addition, subtraction, multiplication, and division. A basic example of implementing these involves the program that stores input numbers and performs these operations: e.g., addition (sum = float(num1) + float(num2)), subtraction (min = float(num1) - float(num2)), multiplication (mul = float(num1) * float(num2)), and division (div = float(num1) / float(num2)). The results are displayed using formatted strings .

The main differences between 'for' and 'while' loops in Python include the following: In a 'for' loop, initialization, conditional checking, and increment or decrement are done in the loop declaration, whereas, in a 'while' loop, only initialization and condition checking are done externally; 'for' loops are used when the number of iterations is known beforehand, while 'while' loops are suited for situations where the number of iterations is not known in advance; omitting a conditional statement in a 'for' loop can lead to an infinite loop, whereas omitting it in a 'while' loop will result in an error; in 'for' loops, iteration occurs at the top of the syntax, while in 'while' loops it can occur anytime in the syntax; finally, the 'for' loop continues iterating as long as the body executes, whereas 'while' can handle iteration at any time during execution .

Membership operators in Python ('in' and 'not in') are used to test whether a value is present in a sequence, such as lists and tuples. These operators allow checking for the presence or absence of elements efficiently. For instance, when using 'in', the syntax 'element in sequence' returns True if the element exists within the sequence. Conversely, 'not in' returns True if the element is absent. Considering Python's dynamic typing and sequence processing capabilities, effectively using membership operators can enhance performance for checks within loops or conditions and contribute to cleaner, more expressive code .

Excessive nesting of loops and conditional statements in Python is discouraged because it increases code complexity and reduces readability. Deep nesting makes understanding and maintaining the code challenging, elevating the risk of logical errors and bugs. These issues not only make debugging difficult but also hinder collaborative development, as new developers may struggle to grasp the flow. Utilizing functions or breaking conditions into simpler, flat structures can enhance readability and maintainability .

'Nested IF' statements in Python allow placing an 'if' or 'else if' statement inside another 'if' or 'else if'. This enables checking for multiple conditions where each 'if' statement can contain a block of code executed based on its condition. They are necessary when decision-making requires evaluating multiple, interconnected conditions. However, nested IF statements can become cumbersome and difficult to follow, leading to increased complexity and potential errors, especially with deeply nested conditions. Using them excessively is discouraged unless necessary to avoid these downsides .

In Python, operators are classified into various categories such as arithmetic, relational, logical, identity, membership, and bitwise operators. This classification helps in organizing and employing appropriate operations based on the context, aiding in cleaner, more efficient programming. For example, arithmetic operators facilitate numeric calculations, relational operators enable comparison of values, logical operators combine conditions, and membership operators check for elements within sequences. Proper use of each type enhances code readability, maintainability, and reduces errors .

You might also like