0% found this document useful (0 votes)
16 views20 pages

Python Loops: For and While Explained

The document provides an overview of loops in Python, specifically focusing on for and while loops. It explains how to use for loops with various data types like lists and strings, as well as the functionality of the range() function. Additionally, it covers the structure and usage of while loops, including control statements like break and continue.

Uploaded by

pazeera76
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)
16 views20 pages

Python Loops: For and While Explained

The document provides an overview of loops in Python, specifically focusing on for and while loops. It explains how to use for loops with various data types like lists and strings, as well as the functionality of the range() function. Additionally, it covers the structure and usage of while loops, including control statements like break and continue.

Uploaded by

pazeera76
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

Loops in Python

for and while loops


For Loop
• For loop is used to iterate over a range or other Iterable sequence such as list,
tuple, dictionary, string etc
• This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
• With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
• We can also use it with range to do multiple tasks
For with Range() function:
• Definition and usage of range:
• The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.
• range(start, stop, step)

Parameter Description

start Optional. An integer number specifying at which position to start. Default is 0

stop Required. An integer number specifying at which position to stop (not included).

step Optional. An integer number specifying the incrementation. Default is 1


For with range examples:
numbers = range(1, 11)
for i in numbers:
print(i)
# this loop prints numbers from 1 to 10
OR

for i in range(1, 11):


print(i)
For with a List:
• What is a list?
• Lists are used to store multiple items in a single variable.
• Lists are one of 4 built-in data types in Python used to store collections of data
• Lists are created using square brackets
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index
[1] etc.
• We can use len() function to determine the length of a list
• Lists items can be of any datatype (int, float, string, Boolean, etc)
Examples of lists:
myList = ["Bahad", "Chakar", "Zamur", "Zemar", "Darwar"]
for i in myList:
print(i, end=" ")

numberList = [1, 2, 3, 46,99, 22, 44, 55, 66]


for i in numberList:
print(i, end=" ")
#OR

length = len(numbers)
for i in range(length):
print(numbers[i], end=" ")
Using for loop to iterate over a string:
myname = "Mehrbyaar"
for i in myname:
print(i, end = "")
#this loop iterates in the string myname and prints all
the characters one by one
Or you can write it like this:

for i in "Mehrbyaar":
print(i, end = " ")
Python for loop with else:
• A for loop can have an optional else block. The else part is executed
when the loop is exhausted (after the loop iterates through every
item of a sequence). For example,

digits = [1, 2, 3, 4, 12]


for j in digits:
print(j)
else:
print("All Digits Printed")
Things to mention
For loops can be nested
You can print with nested range functions
You can use nested for loops with lists and other structures

Go and Explore More…


While Loops in Python
One of the primitives loops in Python is while loop
Steps in while loop:
• A while loop evaluates the condition
• If the condition evaluates to True, the code inside the while loop is
executed.
• condition is evaluated again.
• This process continues until the condition is False.
• When condition evaluates to False, the loop stops.
The while Loop
• With the while loop we can execute a set of statements as long as a
condition is true.
Example:
• Print i as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Exit the loop when i is 3:

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

Note: remember to increment i, or else the loop will continue forever.


The continue Statement
• With the continue statement we can stop the current iteration, and
continue with the next:
• Continue to the next iteration if i is 3:
i = 0
while i <= 10:
i += 1
if i == 3:
continue
print(i)
The else Statement
• With the else statement we can run a block of code once when the
condition no longer is true:
• Print a message once the condition is false:
i = 1
while i <= 10:
print(i)
i += 1
else:
print("i is no longer less than or equal to 10")
While with different condition:
print("Enter 0 to stop")
number = int(input("Enter a Number: "))
sum = 0
while number != 0:
number = int(input("Enter a Number: "))
sum = sum + number

print("Total = ", sum)

Note:
Here we do not initialize and increase the while loop in traditional way. Rather we are taking input from user
and condition is based on the input given by user. If the input matches to our given condition, the loop will
terminate.
Lets have another example:
• namelist= []
print("Enter 'stop' to stop entering names... ")
name = input("Enter your names: ")
while name != "stop":
[Link](name)
name = input("Enter your names: ")

print(namelist)
While TRUE:

while True:

print("Hello")

This loops runs till infinity… because it is always true…


While TRUE:
• The "while true" loop in python runs without any conditions
until the break statement executes inside the loop.

counter = 0
while True:
print("Hello ")
counter += 1

if counter > 10:


break
While TRUE:
while True:
print("Printing while the while is True.... ")

check = input("Enter YES if you want to Exit the Loop: ")


if check == "YES":
break
else:
continue

You might also like