0% found this document useful (0 votes)
75 views50 pages

Python Operators and Control Statements

This document covers key concepts in Python programming, including assignment statements, arithmetic, relational, logical, and bitwise operators. It also discusses conditional statements, loops, and control flow statements like break, continue, and pass. Additionally, it introduces the assert statement for debugging purposes.

Uploaded by

Rahul Sharma
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)
75 views50 pages

Python Operators and Control Statements

This document covers key concepts in Python programming, including assignment statements, arithmetic, relational, logical, and bitwise operators. It also discusses conditional statements, loops, and control flow statements like break, continue, and pass. Additionally, it introduces the assert statement for debugging purposes.

Uploaded by

Rahul Sharma
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

Operators, Expressions and

Python Statements
Chapter-4
Assignment statement
• An assignment statement in Python is used to
store a value into a variable.
• Syntax :
variable_name = value
• Here, the = is called the assignment operator.
Assignment statement
# Simple Example :
x = 10 # Assigns 10 to variable x
name = "John"
# Assigns string "John" to variable name
pi = 3.14 # Assigns 3.14 to variable pi
Assignment statement
Multiple Assignments:
• Python allows assigning multiple variables at
the same time.
a = b = c = 5 # All variables get the value 5
x, y = 2, 3 # x = 2 and y = 3
Assignment statement
Variable Reassignment:
• You can change the value of a variable by
assigning it a new value.
x = 10
x = 20 # Now x is 20
Arithmetic Operator
• Arithmetic operators are used to perform
mathematical operations like addition,
subtraction, multiplication, etc.
Arithmetic Operator
Operator Name Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 5/2 2.5
// Floor Division 5 // 2 2 (no decimal part)
Modulus
% 5%2 1
(Remainder)
** Exponentiation 2 ** 3 8 (2³)
Difference between / and //
/ (Normal Division):
• Always returns a decimal (float) value.
• Even if the result is a whole number, it still
shows as x.0
• Example :
print(10 / 2) # Output: 5.0
print(7 / 3) # Output: 2.333...
Difference between / and //
// (Floor Division):
• Removes the decimal part and rounds down
to the nearest whole number.
• Always returns an integer if both operands
are integers, else float.
• Example :
print(10 // 2) # Output: 5
print(7 // 3) # Output: 2
print(-7 // 3) # Output: -3 (rounds down)
Example Program for Arithmetic
Operator
a = 10
b=3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Power:", a ** b)
Relational operator(or Comparison
Operator)
• Relational operators are used to compare two
values. The result is either True or False.
Relational operator(or Comparison
Operator)
Operator Meaning Example Output

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 7>5 True

< Less than 3<2 False

>= Greater than or equal to 4 >= 4 True

<= Less than or equal to 2 <= 3 True


Relational operator(or Comparison
Operator)
# Example Program of Relational operator
a = 10
b=5
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
print(a >= b) # True
print(a <= b) # False
Logical Operator
• Logical operators are used to combine
multiple conditions and return True or False.

Operator Meaning Example Result


True if both are
and 5 > 2 and 3 < 4 True
True
True if any one is
or 5 > 10 or 4 == 4 True
True
Reverses the
not not (5 > 2) False
result
Example Program of Logical Operator
a = 10
b=5
print(a > 5 and b < 10) # True and True → True
print(a < 5 or b < 10) # False or True → True
print(not(a > b)) # not(True) → False
Bitwise operators
• Bitwise operators work on binary (bit level)
— they perform operations bit by bit.
Bitwise operators
Operator Name Example Explanation Result

& AND 5&3 0101 & 0011 → 0001 1

| OR 5|3 0101 & 0011 → 0111 7


0101 ^ 0011 → 0110
XOR
^ 5^3 (When only one 1 is 6
(Exclusive OR)
present, then output is 1)
~ NOT ~5 ~0101 → 1010 -6

<< Left Shift 5 << 1 0101 → 1010 (shift left) 10

>> Right Shift 5 >> 1 0101 → 0010 (shift right) 2


Program of Bitwise operators
a=5
b=3
print("a & b =", a & b) # AND → 1
print("a | b =", a | b) # OR → 7
print("a ^ b =", a ^ b) # XOR → 6
print("~a =", ~a) # NOT → -6
print("a << 1 =", a << 1) # Left Shift → 10
print("a >> 1 =", a >> 1) # Right Shift → 2
Conditional Statements
• Conditional statements let your program
make decisions — like saying:
“If this is true, do something. Otherwise, do
something else.”
• if
• if-else
• if-elif-else
if Statement
• Runs a block of code only if the condition is
true.
• Example :
age = 18
if age >= 18:
print("You can vote")
2. if...else Statement
• Runs one block if condition is true, another
block if false.
• Example :
age = 16
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
3. if...elif...else Statement
• Use elif when you have multiple conditions.
• Example :
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")
Nested
• In Python, a nested function (also called
an inner function) is a function that is defined
inside the body of another
function(the enclosing or outer function).
Nested conditionals
• A nested if-else statement is
an if or else statement that is
placed inside another if or else block. This
allows you to check for multiple conditions in
a structured, hierarchical way.

Key Idea: You can only get to the inner


condition if the outer condition is true.
Why Use Nested Conditions?
To make complex decisions where a secondary
condition depends on the first condition being
true.
Real-life Example:
First, check if it is the weekend.
If it is, then check if the weather is good.
If weather is good, go to the park.
Else, watch a movie at home.
If it's not the weekend, then go to work.
Syntax & Structure

if outer_condition:
# Outer condition is True
if inner_condition_1:
# Do something if inner_condition_1 is True
elif inner_condition_2:
# Do something if inner_condition_2 is True
else:
# Do something if all inner conditions are False
else:
# Outer condition is False
# Do something else
Example
if x < y:
STATEMENTS_A
else:
if x > y:
STATEMENTS_B
else:
STATEMENTS_C
• The outer conditional contains two branches.
The second branch contains another if
statement, which has two branches of its own.
Those two branches could contain conditional
statements as well.
• Although the indentation of the statements
makes the structure apparent, nested
conditionals very quickly become difficult to
read. In general, it is a good idea to avoid them
when you can.
Range Function
• The range() function is used to generate a
sequence of numbers.
• Syntax of range() :
range(start, stop, step)
Parameter Description
(Optional) The number to start from. Default is
start
0.
stop (Required) The number to stop before.
(Optional) Difference between each number.
step
Default is 1.
Examples of range()
1. Basic range(stop)
for i in range(5):
print(i)
OUTPUT :
0
1
2
3
4
Examples of range()
2. range(start, stop)
for i in range(2, 6):
print(i)
OUTPUT :
2
3
4
5
Examples of range()
3. range(start, stop, step)
for i in range(1, 10, 2):
print(i)
OUTPUT
1
3
5
7
9
While Statement
• The while statement in Python is used to execute
a block of code repeatedly as long as a given
condition is True.
• Syntax :
while condition:
# block of code
• The condition is checked before each iteration.
• If the condition is True, the block is executed.
• It keeps repeating until the condition becomes
False.
For loop
• The for loop in Python is used to repeat a
block of code a fixed number of times —
especially useful for going through items in a
sequence (like a list, string, or range).
• Syntax:
for variable in sequence:
# code to repeat
Nested Loops
Definition:
A nested loop is a loop that is placed inside the
body of another loop. This allows you to
perform iterative tasks (like repeating actions)
within another iterative task.

Key Idea: For each iteration of the outer loop,


the entire inner loop runs completely.
Why Use Nested Loops?
• To work with multi-dimensional data or perform
repetitive tasks that have their own smaller
repetitive tasks.
Syntax & Structure:
for outer_item in outer_sequence:
# Outer loop code
for inner_item in inner_sequence:
# Inner loop code
# More outer loop code
Example: Pattern Printing
Print a rectangle of stars with 3 rows and 5 columns.

rows = 3
cols = 5

for i in range(rows): # Outer loop for rows


for j in range(cols): # Inner loop for columns
print('*', end=‘’) # Print 5 stars in one row
print() # Move to the next line after each row
break statement
• The break statement is used to exit/stop a
loop immediately, even if the condition hasn't
become False.
Where it's used?
• In for loops and while loops
• Typically with conditions (like if) to stop the
loop early
Example 1: Using break in for loop
for i in range(1, 10):
if i == 5:
break
print(i)
OUTPUT :
1
2
3
4
Example 2: Using break in while loop
i=1
while i <= 10:
if i == 4:
break
print(i)
i += 1
OUTPUT :
1
2
3
Continue Statement
• The continue statement is used to skip the
current iteration of a loop and go to the next
one, without exiting the loop.
Example 1: continue in for Loop
for i in range(1, 6):
if i == 3:
continue
print(i)
OUTPUT :
1
2
4
5
NOTE : Skips 3 and continues the loop.
Example 2: continue in while Loop
i=0
while i < 5:
i += 1
if i == 2:
continue
print(i)
OUTPUT :
1
3
4
5
NOTE : Skips printing 2
Pass Statement
• The pass statement is a null (do-nothing)
statement used when a statement is required
syntactically, but you don’t want any code to
run.
Why use pass?
• To create empty code blocks that you’ll
complete later.
• To avoid getting an error when a block cannot
be left empty.
Pass Statement
• Syntax :
if condition:
pass
#Empty if block
x=5
if x > 0:
pass # Do nothing for now
print("Program runs fine")
OUTPUT :
Program runs fine
Assert Statement
• The assert statement in Python is used to
check if a condition is True, and if it’s not, the
program will raise an AssertionError.
• It’s mainly used for debugging purposes — to
catch bugs early in the development phase.
• Syntax :
assert condition
How It Works
• If the condition is True, nothing happens and
the program continues.
• If the condition is False, an AssertionError is
raised.
• If a message is provided, it will be displayed
with the error.
Example 1: Assertion Passes
x = 10
assert x > 5 # Condition is True, nothing happens
print("Assertion passed!")
Example 2: Assertion Fails
x=3
assert x > 5 # This will raise AssertionError

• OUTPUT :
AssertionError
Example 3: Assertion with Message
x=3
assert x > 5, "x is not greater than 5"

• OUTPUT :
AssertionError: x is not greater than 5

You might also like