You are on page 1of 34

LOOPS PYTHON

12th Jan(Friday)

Delivered By: Samra Mehboo


WHY WE NEED LOOPS?
 In computer programming, loops are used to repeat a block of code.

 For example, if we want to show a message 100 times, then we can use a loop
TYPES OF LOOPS
 There are 2 types of loops in Python:

 for loop
 while loop
FOR LOOP
 In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc. For
example

 languages = ['Swift', 'Python', 'Go', 'JavaScript']

 # run a loop for each item of the list


 for language in languages:
 print(language)
FOR LOOP SYNTAX
for val in sequence:
# statement(s)
FLOWCHART OF PYTHON FOR
LOOP
EXAMPLE: LOOP THROUGH A
STRING
 The in keyword in Python is commonly used in loops to iterate over elements in a sequence (like a
list, tuple, string, etc.) or other iterable objects

 for x in 'Python':
 print(x)

 # Iterate over elements in a list

numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
CHECKING IF AN ELEMENT IS
IN A LIST
 # Check if an element is in a list

fruits = ["apple", "banana", "orange"]


search_fruit = "banana"

if search_fruit in fruits:
print(f"{search_fruit} is in the list!")
else:
print(f"{search_fruit} is not in the list.")
PYTHON FOR LOOP WITH PYTHON RANGE()

 The range() function in Python is used to generate a sequence of numbers. It can be used in a
for loop to iterate over a sequence of numbers. The range() function has three forms:

 range(stop): Generates a sequence of numbers from 0 to stop - 1.


 range(start, stop): Generates a sequence of numbers from start to stop - 1.
 range(start, stop, step): Generates a sequence of numbers from start to stop - 1, with a
specified step between each number.
 range(stop):

for i in range(5):
print(i)
 range(start, stop):
 for i in range(2, 8):
 print(i)
 range(start, stop, step):

 for i in range(0, 10, 2):


 print(i)
PYTHON FOR LOOP WITH PYTHON RANGE() EXAMPLE

 values = range(4)
 Here, 4 inside range() defines a range containing values 0, 1, 2, 3.

 In Python, we can use for loop to iterate over a range. For example,

 # use of range() to define a range of values

values = range(4)

# iterate from i = 0 to i = 3
for i in values:
print(i)
EXPLANATION
 In the above example, we have used the for loop to iterate over a range from 0 to 3.

 The value of i is set to 0 and it is updated to the next number of the range on each iteration.
This process continues until 3 is reached.
CONTD..
USING A FOR LOOP WITHOUT ACCESSING
ITEMS

 It is not mandatory to use items of a sequence within a for loop. For example,

languages = ['Swift', 'Python', 'Go']

for language in languages:


print('Hello')
print('Hi')
PROBLEM: SIMPLE
CALCULATOR
 Write a Python program to create a simple calculator. The calculator should ask the user for
two numbers and an operation (addition, subtraction, multiplication, or division). Then, it
should perform the requested operation and display the result.
PROBLEM: GUESS THE
NUMBER GAME
 Write a Python program that generates a random number between 1 and 10 and asks the user
to guess the number. The program should continue prompting the user for guesses until they
correctly guess the number. Provide feedback to the user if their guess is too high or too low.
 import random
 secret_number = random.randint(1, 10)
 import random  print("Congratulations! You guessed the
correct number.")
 break # Exit the loop if the guess is correct
 def guess_the_number():

 # Generate a random number between 1 and 10
 # Provide feedback if the guess is too high or
 secret_number = random.randint(1, 10) too low

 elif user_guess > secret_number:
 # Welcome message  print("Too high! Try again.")
 print("Welcome to the Guess the Number  else:
Game!")
 print("Too low! Try again.")

 else:
 # Allow the player three attempts
 # This block executes if the loop completes
 for attempt in range(3): without a break (i.e., the player did not guess the
 # Get user input for their guess correct number)
 user_guess = int(input("Enter your guess  print(f"Sorry! The correct number was
(between 1 and 10): ")) {secret_number}. Better luck next time.")
 # Check if the guess is correct  # Call the function to start the game

 if user_guess == secret_number:  guess_the_number()


 Write a Python program that takes a number as input from the user and generates the multiplication table for that number from 1 to
10. For example, if the user enters 5, the program should output the following:
 Input the number for which user wants to generate multiplication table if enters 5

 Output 5,10, 15,20

 Range(1,11)

 Num= int(input(Enter number you want to print)) # suppose user entered 5

 For I in range(1,11):

 result= num*I #result= 5* 1=5


 #result= 5*2 = 10
 #result= 5*3= 15
 #result= 5*4= 20
 print(result) print($num “+” $i “=” $result)
 1 5
 2

 3

 4

 5x1=5

 5 x 2 = 10

 5 x 3 = 15

 5 x 10 = 50
Sum i Sum = sum+i
Step 1 1 1 Sum= 1+1=2
Step 2 2 2 Sum = 2+2 = 4
Step 3 4 3 Sum= 3+3 = 7
Step 4 6 4 10

1, 2, 3, 4, 5, 6
1+2= 3
3+3=6
6+4=10
10+5=15

sum=1
for i in range(1,6):
sum = sum+i
SOLUTION
number = int(input("Enter a number to generate its multiplication table: "))

# Display the multiplication table from 1 to 10


for i in range(1, 11):
result = number * i
print(f"{number} x {i} = {result}")
PROBLEM: COUNTING VOWELS IN A WORD

 Write a Python program that takes a word as input from the user and counts the number of
vowels in that word. Display the count of each vowel (a, e, i, o, u).
SOLUTION
# Get a word from the user count_a += 1 print(f"Count of 'e':
{count_e}")
word = input("Enter a word: elif char.lower() == 'e':
") print(f"Count of 'i':
count_e += 1 {count_i}")
elif char.lower() == 'i': print(f"Count of 'o':
# Initialize counters for each {count_o}")
vowel count_i += 1
elif char.lower() == 'o': print(f"Count of 'u':
count_a = count_e = count_i {count_u}")
= count_o = count_u = 0 count_o += 1
elif char.lower() == 'u':
# Iterate through each count_u += 1
character in the word
for char in word:
# Display the counts for each
# Check if the character is a vowel
vowel (case-insensitive)
print(f"Count of 'a':
IS THE STRING ODD OR EVEN?
 Given a string, return True if its length is even or False if the length is odd.

 odd_or_even("apples") ➞ True
 # The word "apples" has 6 characters.
 # 6 is an even number, so the program outputs True.

 odd_or_even("pears") ➞ False
 # "pears" has 5 letters, and 5 is odd.
 # Therefore the program outputs False.

 odd_or_even("cherry") ➞ True
WHILE LOOP
 Python while loop is used to run a block code until a certain condition is met.

 The syntax of while loop is:


 while condition:
 # body of while loop
FLOWCHART OF PYTHON
WHILE LOOP
 # Python program to illustrate
 # while loop

count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
PYTHON WHILE LOOP
 # program to display numbers from 1 to 5

Range(1,6,3)
# initialize the variable
i=1
n=5
# while loop from i = 1 to 5
while i <= n:
print(i)
i=i+3
WHILE-LOOP EXERCISE CODE
TO BUILD COUNTDOWN
CLOCK
countdown = 10
while countdown > 0:
print(countdown)
countdown -= 1
print("Blast off!")
PROGRAM TO CALCULATE THE SUM OF
NUMBERS
# UNTIL THE USER ENTERS ZERO
Ask the user to input number
4
While
 Ask user to enter number if user enters 0 exit loop

 Num= input(Enter number if you enter zero you will exit loop)

 While condition
 num= input(Enter a number )
 print(you pressed 5 )

 Print(You entered zero number )


PYTHON WHILE LOOP TO
PRINT A NUMBER SERIES
FINDING THE AVERAGE OF 5
NUMBERS USING WHILE
LOOP
p=5
sum = 0
count = 0
while p > 0:
count += 1
f = int(input("Enter the number "))
sum += f
p -= 1
average = sum/count
print("Average of given Numbers:",average)
THE BREAK STATEMENT
 Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

You might also like