0% found this document useful (0 votes)
17 views59 pages

Lecture4 Loops Updated

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

Lecture4 Loops Updated

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

opera

• OPERATORS
• CONDITIONAL STATEMENT
• LOOPING
LOOPING IN PROGRAMMING
• Doing the Same Thing Many Times
• It’s possible to do something repeatedly by just writing it all out
• Print ‘hello’ 5 times

>>> print('Hello!')
Hello
>>> print('Hello!')
Hello
>>> print('Hello!')
Hello
>>> print('Hello!')
Hello
>>> print('Hello!')
Hello
ITERATION
Doing the Same Thing Many
Times
• It’s possible to do something repeatedly by just writing it all out
• Print ‘hello’ 5 times
>>> print('Hello!')
Hello
>>> print('Hello!')
Count n Hello
times >>> print('Hello!')
Hello
>>> print('Hello!')
Hello
Statements >>> print('Hello!')
Hello
Iteration or Loops
• A loop repeats a sequence of statements
A
•>>>
...
definite loop repeats a sequence of statements a predictable number
for x in range(5): print('Hello!')

of times
Hello
Hello
Hello
Hello
Hello

Count n
times

Statements
• for x in range(5) ----0,1,2,3,4
• for x in range(1,5)--1,2,3,4
• for x in range(1,10,2)--1,3,5,7,9
• for x in range(5,0,-1)---5,4,3,2,1
• for x in range(5,0,-2)---5,3,1
• for x in range(-4,4)-- -4,-3,-2,-1,0,1,2,3
• for x in range(-4,4,2)--- -4,-2,0,2
• for x in range(0,1)---- 0
• for x in range(1,1)--- empty
• for x in range(0)---- empty
The for Loop
• Python’s for loop can be used to iterate a definite number of times
for <variable> in range(<number of times>): <statement>
•>>>
Useforthis
x insyntax when you have only one statement to repeat
range(3):
... print('Hello!')
... print('goodbye')
for <variable> in range(<number of times>):
...
<statement-1>
Hello!
<statement-2>
goodbye

Hello!
<statement-n>
goodbye
Hello!
goodbye
•Use indentation to format two or
more statements below the loop
header
Using the Loop Variable
• The loop variable picks up the next value in a sequence on each pass
through the loop
• The expression range(n) generates a sequence of ints from 0
through n - 1

loop variable

>>> for x in range(5): print(x)


...
0
1
2
3
4
>>> list(range(5)) # Show as a list
[0, 1, 2, 3, 4]
Counting from 1 through n
• The expression range(low, high) generates a sequence of ints from low
through high - 1

>>> for x in range(1, 6): print(x)


...
1
2
3
4
5
Counting from n through 1
• The expression range(high, low, step) generates a sequence of ints
from high through low+1.

>>> for x in range(6, 1, -1): print(x)


...
6
5
4
3
2
Skipping Steps in a Sequence
• The expression range(low, high, step) generates a sequence of ints
starting with low and counting by step until high - 1 is reached or
exceeded

>>> for x in range(1, 6, 2): print(x)


...
1
3
5
>>> list(range(1, 6, 2)) # Show as a list
[1, 3, 5]
Program1
• print("\tEnter the marks of the students...")
• for i in range(1,11):
• print("\trollno...",i)
• e=int(input("\tenter marks..."))
Problems
• Write a Python program to input the ages of 5 persons using a loop and print
each person’s age with their person number.

• Write a Python program to input the temperature of 7 days and display the
temperature entered for each day.

• Write a Python program to input the prices of 5 products and print the price
along with the product number.

• Write a Python program to input the scores of 3 matches and display the score
of each match.
Problem
• Write a Python program to calculate the Fuel Efficiency of 3 flights
using the formula

• Efficiency
• =Distance/Fuel Used
Progrmas
• print("Enter marks of 10 students:")

• pass_count = 0
• fail_count = 0

• for i in range(1, 11):


• marks = int(input("Enter marks of Roll No : "))
• if marks >= 40:
• pass_count += 1
• else:
• fail_count += 1

• print("\nNumber of students Passed =", pass_count)


• print("Number of students Failed =", fail_count)
Some programs on for
• for x in 'hello':
• print(x)
Some programs on for
• for i in range(5, 8):
• print(i, i ** 2)
• print('end of loop')
Some programs on for
• for i in range(0,20,2): -one method of doing it
• or
• For i in range(0,21):
• if (i %2==0):
• print(“even no…”,i)
• else:
• print(“odd no…”,i)
Some programs on for
• print("ASSIGN SET1 TO EVEN ROLL SET2 TO ODD ROLLNO")
• for i in range(1,22):
• if (i%2==0):
• print("SET1-ROLLNO",i)
• else:
• print("SET2-ROLLNO",i)
Some programs on for
• correct_id = 111
• correct_pwd = "xyz"

• for i in range(3):
• user_id = int(input("Enter ID: "))
• pwd = input("Enter Password: ")

• if user_id == correct_id and pwd == correct_pwd:


• print("Login Successful")
• break
• else:
• print(" Incorrect… TRY AGAIN")
• print("Attempts left:", 2 - i)

• else:
• print("ACCOUNT LOCKED! Too many failed attempts.")
Some programs on for
• y=0
• n=0
• print("\t\tDO YOU FIND PYTHON EASY.....")
• print("\t\tSTART THE POLLING....")
• for i in range(5):

• s=str(input("\t\tselect your option y/n...."))
• if (s=='y' ):
• y=y+1
• else:
• n=n+1
• print("\t\ttotal no of yes are...",y)
• print("\t\ttotal no of no are....",n)
Program
• alice = 0 • print("\n--- VOTING RESULT ---")
• bob = 0
• print("Alice =", alice, "votes")
• print("\t\tCLASS REPRESENTATIVE VOTING")
• print("\t\tOptions: 1. Alice 2. Bob")
• print("Bob =", bob, "votes")

• for i in range(1, 6):


• vote = int(input(f"\tStudent {i}, enter your vote (1/2): "))
• if alice > bob:
• • print("Winner: Alice ")
• if vote == 1:
• alice += 1 • elif bob > alice:
• elif vote == 2: • print("Winner: Bob ")
• bob += 1
• else: • else:
• print("\tInvalid vote!")
• print("Result: Tie ")
Program
• active = 0
• inactive = 0

• print("\t\tAIRCRAFT SENSOR STATUS (5 Sensors)")

• for i in range(1, 6):


• status = input(f"\tSensor {i} Active (a) or Inactive (i)?
").lower()

• if status == 'a':
• active += 1
• else:
• inactive += 1

• print("\n--- SENSOR STATUS REPORT ---")


• print("Active Sensors =", active)
• print("Inactive Sensors =", inactive)
Some programs on for
absent=0
• present=0
• for i in range(1,21):
• print("rollno….",i)
• mark=str(input("present or absent select p or a"))
• if mark=='p':
• present=present+1
• else:
• absent=absent+1

• print("total present…..”,present)
• print("total absent…..”,absent)
Program
• total = 0

• print("\t\tWELCOME TO SHOPPING CART") • print("\n--- BILL SUMMARY ---")


• print("\t\t(3 Items Only in This Demo)\n") • print("Total Amount = Rs", total)

• for i in range(1, 4): • if total > 1000:


• item = input("Enter name of item : ") • discount = total * 0.10
• price = float(input(f"Enter price of item: Rs"))
• total -= discount
• qty = int(input("Enter quantity of item : "))
• print("Discount Applied = Rs", discount)
• print("Final Amount = Rs", total)
• cost = price * qty
• else:
• total += cost
• print("No Discount Applied")
Some programs on for

• for i in range(1,6):
• s=i*i
• print("square of no is",s)
Some programs on for

• print("capital letters A TO Z")


• for i in range(65,96):
• print(chr(i))
Some programs on for
• # performing sum of natural
• # number
• sum = 0
• for i in range(1, 11):
• sum = sum + i
• print("Sum of first 10 natural number :", sum)
Some programs on loop
• print(".....BESTPRICE BILLING.....")
• tp=0
• n=int(input("specify total number of item ..."))
• for i in range(n):
• print("\t\t enter price for item",i)
• p=int(input("enter price..."))
• tp=tp+p
• print("\t\t\t total bill amount is...",tp)
Some programs on for
• printing first 10
• # whole number
• for i in range(10):
• print(i, end =" ")
• print()

• # printing first 20
• # whole number
• for i in range(20):
• print(i, end = " ")
Some programs on for
• using range to print number
• # divisible by 3
• for i in range(0, 30, 3):
• print(i, end = " ")
• print()

• # using range to print number
• # divisible by 5
• for i in range(0, 50, 5):
• print(i, end = " ")

Some programs on for
• # incremented by -2
• for i in range(25, 2, -2):
• print(i, end =" ")
• print()

• # incremented by -4
• for i in range(30, 1, -4):
• print(i, end =" ")
• print()

• # incremented by -3
• for i in range(25, -6, -3):
• print(i, end =" ")
Program
• # given number
• given_number= 5

• factorial = 1

• # iterate till the given number
• for i in range(1, given_number + 1):
• factorial = factorial * i

• print("The factorial of ", given_number, " is ", factorial)
program
• # Multiplication table (from 1 to 10) in Python

• num = 12

• # To take input from the user


• # num = int(input("Display multiplication table of? "))

• # Iterate 10 times from i = 1 to 10


• for i in range(1, 11):
• print(num, 'x', i, '=', num*i)
Programs output
• for num in range(1, 11): •1
• print(num) •2
• if num ==3 : •3
• break
Program output
• for num in range(1, 11): • 1
• if num ==3: • 2
• continue • 4
• 5
• print(num)
• 6
• 7
print("Loop completed • 8
successfully!")
• 9
• 10
• Loop completed successfully!
While Loop
A for loop is used when a program knows it needs to repeat a block of
code for a certain number of times.
A while loop is used when a program needs to loop until a particular
condition occurs.
Flow of Execution for WHILE
Statement
Looping Until User Wants To Quit
Program to count no of digits
• num = 3452
• count = 0

• while num != 0:
• num //= 10
• count += 1

• print("Number of digits: " ,count)


Program to reverse the digit
• num = 1234
• reversed_num = 0

• while num != 0:
• digit = num % 10
• reversed_num = reversed_num * 10 + digit
• num //= 10

• print("Reversed Number: " ,reversed_num))


Nested Loops
• rows = int(input("Enter the
number of rows: "))

• for i in range(1, rows+1):


• for j in range(1, i + 1):
• print(j, end=" ")

• print()
Nested Loops
• rows = int(input("Enter the
number of rows: "))

• for i in range(rows, 0, -1):


• num = i
• for j in range(0, i):
• print(num, end=" ")

• print()
Nested Loops
• rows = int(input("Enter the number of rows: "))

• #Outer for loop to handle number of rows


• for num in range(rows+1):
• #Inner for loop to handle number of columns
• #values change according to the outer loop
• for i in range(num):
• print(num, end=" ")

• #End line after each row
• print()
Nested Loops
• #Outer for loop to handle number of rows

• for i in range(0, rows):


• #Inner for loop to handle number of
columns
• #values change according to the outer
loop
• for j in range(0, i + 1):
• print("* ", end=" ")

• #End line after each row
• print()
MCQ
• What will be the output of the • a) 1
following Python code?
• b) 1 2
• c) 1 2 3 4 5 6 …
• i=1
• d) 1 3 5 7 9 11 …
• while True:
• if i%2 == 0:
• break
• print(i)
• i += 2
MCQ
• What will be the output of the • a) 2 4 6 8 10 …
following Python code? • b) 2 4
• c) 2 3
• i=2 • d) error
• while True:
• if i%3 == 0:
• break
• print(i)
• i += 2
MCQ
• What will be the output of the • a) 1
following Python code? • b) 1 3 5 7 …
• c) 1 2 3 4 …
• i=1 • d) none of the mentioned
• while False:
• if i%2 == 0:
• break
• print(i)
• i += 2
MCQ
• What will be the output of the • a) True
following Python code? • b) False
• c) None
• d) none of the mentioned
• True = False
• while True:
• print(True)
• break
MCQ
• What will be the output of the following • a) 0 1 2 0
Python code?
• b) 0 1 2
• i=0 • c) error
• while i < 5: • d) none of the mentioned
• print(i)
• i += 1
• if i == 3:
• break
• else:
• print(0)
MCQ
• What will be the output of the • a) 0 1 2 3 0
following Python code? • b) 0 1 2 0
• i=0 • c) 0 1 2
• while i < 3: • d) error
• print(i)
• i += 1
• else:
• print(0)
MCQ
• What will be the output of the • a) a b c d e f
following Python code? • b) abcdef
• x = "abcdef" • c) i i i i i i …
• while i in x: • d) error
• print(i, end=" ")
MCQ
• What will be the output of the • a) no output
following Python code? • b) i i i i i i …
• c) a b c d e f
• x = "abcdef" • d) abcdef
• i = "i"
• while i in x:
• print(i, end=" ")
MCQ
• . What will be the output of the • a) no output
following Python code? • b) i i i i i i …
• c) a a a a a a …
• x = "abcdef" • d) a b c d e f
• i = "a"
• while i in x:
• print(i, end = " ")
MCQ
• Which of the following is the • a) for i = 0 to 10:
correct syntax for a `for` loop? • b) for i in range(0, 10):
• c) for (i = 0; i < 10; i++):
• d) for (i in range(0, 10))
MCQ
• What is the output of the • a) 0 1 2 3 4 5
following code? • b) 1 2 3 4 5
• x=0 • c) 0 1 2 3 4
• while x < 5: • d) 0 1 2 3
• print(x, end=” “)
• x += 1
MCQ
• What is the result of the • a) 4 3 2 1 0
following code? • b) 4 3 1 0
• i=5 • c) 5 4 3 1
• while i > 0: • d) 4 3 2 1 0 2
• i -= 1
• if i == 2:
• continue
• print(i, end=” “)
MCQ
• What will be the output of the • a) 7 4 1 -2
following code? • b) 7 4 1
• x = 10 • c) 7 5 2 0
• while x > 0: • d) 7 4 1 -2 -5
• x -= 3
• print(x, end=” “)

You might also like