0% found this document useful (0 votes)
1 views48 pages

SSH-PP-UNIT-II

This document covers Python programming concepts, focusing on operators and expressions, including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It also discusses control flow structures such as if statements, loops, and their variations like nested and for loops. Each section includes examples and outputs to illustrate the usage of these operators and control structures.
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)
1 views48 pages

SSH-PP-UNIT-II

This document covers Python programming concepts, focusing on operators and expressions, including arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It also discusses control flow structures such as if statements, loops, and their variations like nested and for loops. Each section includes examples and outputs to illustrate the usage of these operators and control structures.
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
You are on page 1/ 48

PYTHON PROGRAMMING

UNIT-II
Operators and Expressions
➢Operators- Arithmetic Operators

➢Comparison (Relational) Operators

➢Assignment Operators

➢Logical Operators

➢Bitwise Operators

➢Membership Operators
➢Identity Operators

➢Expressions and order of evaluations

➢Control Flow- if, if-elif-else, for, while, break, continue, pass


In Python, operators are special symbols that perform operations on variables
and values. Operators are used to manipulate the value of operands.
Arithmetic Operators:
Arithmetic operators in Python are used to perform mathematical operations
such as addition, subtraction, multiplication, and more.
Operator Operation Example

+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2*3=6

/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1

** Power 4 ** 2 = 16
Arithmetic Operators
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("Exponentiation:", a ** b)
Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000
Arithmetic Operators
a=7
b=2
print ('Sum: ', a + b) # addition
print ('Subtraction: ', a - b) # subtraction
print ('Multiplication: ', a * b) # multiplication
print ('Division: ', a / b) # division
print ('Floor Division: ', a // b) # floor division
print ('Modulo: ', a % b) # modulo
print ('Power: ', a ** b) # a to the power b
Output:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
Assignment Operators
Assignment operators are used to assign values to variables. They can also
perform operations while assigning values.
Operator Name Example

Assignment
= a=7
Operator

Addition
+= a += 1 # a = a + 1
Assignment

Subtraction
-= a -= 3 # a = a - 3
Assignment

Multiplication
*= a *= 4 # a = a * 4
Assignment

/= Division Assignment a /= 3 # a = a / 3

Remainder a %= 10 # a = a %
%=
Assignment 10

Exponent a **= 10 # a = a **
**=
Assignment 10
Assignment Operators
a = 10
a += 5 # a = a + 5
print("After += :", a)
a -= 3 # a = a - 3
print("After -= :", a)
a *= 2 # a = a * 2
print("After *= :", a)
a /= 4 # a = a / 4
print("After /= :", a)
a //= 2 # a = a // 2
print("After //= :", a)
a %= 2 # a = a % 2
print("After %= :", a)
a **= 3 # a = a ** 3
print("After **= :", a)
Output:
After += : 15 After -= : 12 After *= : 24 After /= : 6.0 After //= : 3.0 After
%= : 1.0 After **= : 1.0
Assignment Operators
# assign 10 to a
a = 10
# assign 5 to b
b=5
# assign the sum of a and b to a
a += b #a=a+b
print(a)
Output:
15
Relational Operators
Relational operators are used to compare two values. They return a
boolean value: True or False.
Relational Operators
a = 10
b=5
print("a == b:", a == b)
print("a != b:", a != b)
print("a > b:", a > b)
print("a < b:", a < b)
print("a >= b:", a >= b)
print("a <= b:", a <= b)

a == b: False
a != b: True
a > b: True
a < b: False
a >= b: True
a <= b: False
Logical Operators

Logical operators are used to combine conditional statements and return True or
False based on the conditions.
Logical Operators:
a = 10
b=5
# Using 'and' operator
print("a > 5 and b < 10:", a > 5 and b < 10) # True (Both conditions are True)

# Using 'or' operator


print("a > 5 or b > 10:", a > 5 or b > 10) # True (One condition is True)

# Using 'not' operator


print("not(a > 5):", not(a > 5)) # False (Reverses True to False)

Output:
a > 5 and b < 10: True
a > 5 or b > 10: True
not(a > 5): False
Bit wise Operators
Bitwise operators perform operations at the binary level (bitwise) on integers.
Bit wise Operators
a = 5 # 101 in binary
b = 3 # 011 in binary
print("a & b:", a & b) # 1 (001)
print("a | b:", a | b) # 7 (111)
print("a ^ b:", a ^ b) # 6 (110)
print("a << 1:", a << 1) # 10 (Shifts left: 1010)
print("a >> 1:", a >> 1) # 2 (Shifts right: 10)
Output:
a & b: 1
a | b: 7
a ^ b: 6
a << 1: 10
a >> 1: 2
Ternary Operator

The ternary operator in Python is a one-liner conditional expression that assigns a


value based on a condition.
Syntax: value_if_true if condition else value_if_false
a = 10
b = 20
min_value = a if a < b else b
print("Minimum value:", min_value) # Output: Minimum value: 10
Output:
Minimum value: 10
Membership operators:
Membership operators in Python are used to check whether a value or
variable is found in a sequence (such as a string, list, tuple, set, and
dictionary).
There are two membership operators:
✓ in – Returns True if the specified value is found in the sequence.
✓ not in – Returns True if the specified value is not found in the
sequence.
Membership operators are very useful in conditions, loops, and searching
operations within data structures in Python.
Examples of Membership Operators:
Example 1: Using in and not in with a List
my_list = [1, 2, 3, 4, 5]
print(3 in my_list) # Output: True
print(10 in my_list) # Output: False
print(6 not in my_list) # Output: True

Example 2: Using in and not in with a String


my_string = "Hello, Python!"
print("Python" in my_string) # Output: True
print("Java" in my_string) # Output: False
print("Java" not in my_string) # Output: True
Example 3: Using in and not in with a Tuple
my_tuple = ('apple', 'banana', 'cherry')

print('banana' in my_tuple) # Output: True


print(‘apple' not in my_tuple) # Output: False

Example 4: Using in and not in with a Set


my_set = {10, 20, 30, 40}

print(20 in my_set) # Output: True


print(50 not in my_set) # Output: True

Example 5: Using in and not in with a Dictionary


my_dict = {'name': ‘Ashok', 'age': 25, 'city': ‘Visakhapatnam'}

print('name' in my_dict) # Output: True


print(‘Ashok' in my_dict) # Output: False (Checks keys, not values)
print('gender' not in my_dict) # Output: True
Identity operators:
Identity operators in Python are used to compare the memory locations of two
objects. They determine whether two variables reference the same object in memory.
Python provides two identity operators:
is: Evaluates to True if both variables point to the same object in memory.
is not: Evaluates to True if both variables do not point to the same object in
memory.
Example 1:
a = [1, 2, 3]
b = a # b references the same object as a
print(a is b) # True, because both a and b point to the same object

Example 2:
x = 10
y = 10
z = 20
print(x is not y) # False (both refer to the same integer object 10)
print(x is not z) # True (different objects)
➢ Identity operators are different from equality operators (== and !=).
➢ is checks if two variables refer to the same object in memory.
➢ == checks if two variables have the same value, even if they are different objects.
Example 3:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (same values)
print(a is b) # False (different memory locations)
Example 4:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) # True, because the values are the same
print(list1 is list2) # False, because they are different objects in memory
print(list1 is list3) # True, because list3 references the same object as list1
print(id(list1))
print(id(list2))
print(id(list3))
Control flow
• A control statement is a statement that determines the
control flow of a set of instructions, i.e., it decides the
sequence in which the instructions in a program are to be
executed.
If
If the simple code of block is to be performed if the condition holds
true then the if statement is used. Here the condition mentioned holds
then the code of the block runs otherwise not.
Syntax: if condition:
Sequence of statements
if 10>5:
print("10 greater than 5")
print("Program ended")
num = int(input('Enter a number:'))
if (num%2 == 0):
print('Number is Even')
a=25
b = 25
if a == b:
print('Values are equal')
if age >=18:
print("Eligible for Voting")
if-else
In conditional if Statement the additional block of code is merged as
else statement which is performed when if condition is false.
Syntax:
if condition:
statements(s)
else:
statements(s)

Example:
history = 45
science = 57

if (history > science):


print('History marks greater than Science')
else:
print('Science marks greater than History')
• x=3
• if x == 4:
• print("Yes")
• else:
• print("No")

• age = int(input("Enter your age: "))

• if age >=18:
• print("Eligible for Voting")
• else:
• print("Not eligible for voting")

• num = float(input('Enter a number: '))

• if num >= 0:
• print('Positive Number found')
• else:
• print('Negative Number found')
if-elif-else
• A user can choose from a variety of alternatives here. In this variant
of ‘if statement’, there are many else if conditions declared. If the
first condition does not satisfy then the next condition is executed.
But if this condition also does not satisfy then the next condition is
executed. Let us look at the syntax and the flowchart of if…elif…else
statement.
Syntax:
• if condition1:
• statements(s) # body of if
• elif condition2:
• statements(s) # body of elif
• elif condition3:
• statements(s) # body of elif
• else:
• statements(s) # body of else
• marks = int(input('Enter marks from 0-50: '))

• if (marks<20):
• print('Student Failed')
• elif (marks>20 and marks<40):
• print('Student passed with B Grade')
• else:
• print('Student passed with A Grade')

• toy_price = 380

• if toy_price > 500:


• print('Toy price is Greater than Rs 500')
• elif toy_price < 500:
• print('Toy price is Less than Rs 500')
• else:
• print('Toy price is Rs 500')
Nested-if
• You can have if statements inside if statements, this is called nested if statements.
• Syntax:
• if condition1:
# Code to execute if condition1 is true

• if condition2: # Code to execute if both condition1 and condition2 are true

• num = 10
• if num > 5:
• print("Bigger than 5")

• if num <= 15:


• print("Between 5 and 15")
• val = int(input('Enter a number: '))

• if val>=0:
• if val == 0:
• print('Number is Zero')
• else:
• print('Number is positive')
• else:
• print('Number is negative')
• x = 41

• if x > 10:
• print("Above ten,")
• if x > 20:
• print("and also above 20!")
• else:
• print("but not above 20.")
Loop Structures / Iterative Statements:
• To execute a set of statements repeatedly.
While loop:
• While Loop In Python is used to execute a block of statement till the
givencondition is true. And when the condition is false, the control
will come out of the loop.The condition is checked every time at the
beginning of the loop.
• With the while loop we can execute a set of statements as long as a
condition is true.
• While Loop Syntax
• while (<condition>):
• statements
• Example:
• i= 0
• while(i<=10):
• print(i, end=” “)
• i=i+1
• Output: 0 1 2 3 ....10
• x=0
• while (x < 5):
• print(x, end= ” ” )
• x=x+1
• Output :-
• 01234
a=1
while a<5:
print(a, end= ” “ )
a+=2
Output: 1 3
• x=1
• while (x <= 5):
• print(―Welcome ―)
• x=x+1
• Output :-
• Welcome Welcome Welcome WelcomeWelcome
• Program to print first 10 numbers using a while loop
• i=1
• while(i<=10):
• print(i)
• i=i+1
• count = int(input('How many times you want to say "Hello": '))
• i=1
• while i <= count:
• print('Hello')
• i += 1
• print('Job is done! Thank you!!')
• With the break statement we can stop the loop even if the while
condition is true:
• i=1
• while i < 6:
• print(i)
• if (i == 3):
• break
• i += 1
• With the continue statement we can stop the current iteration, and
continue with the next:
• i=0
• while i < 6:
• i += 1
• if i == 3:
• continue
• print(i)
for loop
• For loop provides a mechanism to repeat a task until a particular
condition is True. It is usually known as a determinate or definite loop
because the programmer knows exactly how many times the loop will
repeat.
• For loop in Python is used to iterate over items of any sequence, such
as a list ora string.
• For Loop Syntax:
• for loop_control_var in sequence:
• Statement block
• Example:
• language = 'Python'
• # iterate over each character in language
• for x in language:
• print(x)
range() Function :
• The range( ) function is a built-in function in Python that is used to
iterate over a sequence of numbers.
• Syntax:
• range(beg, end, [step])
• The range( ) produces a sequence of numbers starting with beg
(inclusive) and ending with one less than the number end.
• The step argument is option (that is why it is placed in brackets). By
default, every number in the range is incremented by 1 but we can
specify a different increment using step. It can be both negative and
positive, but not
• Program to print first n numbers using the range() in a for loop
• If range( ) function is given a single argument, it produces an object
with values from 0 to argument-1. For example: range(10) is equal to
writing range(0, 10).
• If range( ) is called with two arguments, it produces values from the
first to the second. For example, range(0, 10) gives 0-9.
• If range( ) has three arguments then the third argument specifies the
interval of the sequence produced. In this case, the third argument
must be an integer. For example, range(1, 20, 3) gives 1, 4, 7, 10, 13,
16, 19.
• my_list = [1, 2, 3, 4, 5]
• for value in my_list:
• print(value)
• print('Job is done!')
• for i in range(1,5):
• print(i)
• Output :-
• 1
• 2
• 3
• 4
• for i in [1,2,3,4] :
• print(―WELCOME ‖)
• Output :-
• WELCOME
• WELCOME
• WELCOME
• WELCOME
• With the break statement we can stop the loop before it has looped
through all the items:
• fruits = ["apple", "banana", "cherry"]
• for x in fruits:
• print(x)
• if x == "banana":
• break
• With the continue statement we can stop the current iteration of the
loop, and continue with the next:
• fruits = ["apple", "banana", "cherry"]
• for x in fruits:
• if x == "banana":
• continue
• print(x)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy