0% found this document useful (0 votes)
29 views

Python For Loops

The for loop iterates over a sequence, like a list or string, and executes the code within the loop body once for each item. It allows accessing each item without using indexes. Various statements like break, continue, else can be used to control loop behavior. Nested loops run inner loops for each iteration of the outer loop. Range function generates sequences of numbers for looping a specific number of times.

Uploaded by

obed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Python For Loops

The for loop iterates over a sequence, like a list or string, and executes the code within the loop body once for each item. It allows accessing each item without using indexes. Various statements like break, continue, else can be used to control loop behavior. Nested loops run inner loops for each iteration of the outer loop. Range function generates sequences of numbers for looping a specific number of times.

Uploaded by

obed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

We can get each item in an iterable(e.g list, tuple, dictionary, set or string) instead of calling them by index.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

In [14]: # Example
# Print each country in a country list:
# countries = ["Nigeria", "Ghana", "Russia"]
# for country in countries:
# print(country)
# names = ["Akura", "Anastasia", "John", "Paul", "eanu"]
# for name in names:
# print("Hello" + " " + name)
numbers = [2, 4, 6, 7, 8]
for eanu in numbers:
print(eanu)

2
4
6
7
8

In [ ]: # The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

In [1]: # Example
# Loop through the letters in the word "nigeria":
for x in "nigeria":
print(x)

n
i
g
e
r
i
a

The break Statement


With the break statement we can stop the loop before it has looped through all the items:

In [15]: # Example
# Exit the loop when country is "Canada":
# countries = ["Nigeria", "Ghana", "Canada", "Russia"]
# for country in countries:
# print(country)
# if country == "Canada":
# break
names = ["Akura", "Anastasia", "John", "Paul", "eanu"]
for name in names:
print(name)
if name == "John":
break

Akura
Anastasia
John

The continue Statement


With the continue statement we can stop the current iteration of the loop, and continue with the next:

In [12]: # Example
# Do not print Canada:
# countries = ["Nigeria", "Ghana", "Canada", "Russia"]
# for country in countries:
# if country == "Canada":
# continue
# print(country)
names = ["Akura", "Anastasia", "John", "Paul", "eanu"]
for name in names:
if name == "Anastasia":
continue
print(name)

Akura
John
Paul
eanu

The range() Function


To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of
numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

In [14]: # Example
# Using the range() function:
# for x in range(6):
# print(x)
for num in range(11):
print(num)

0
1
2
3
4
5
6
7
8
9
10

In [ ]: # Note that range(11) is not the values of 0 to 11, but the values 0 to 10.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2,
6), which means values from 2 to 6 (but not including 6):

In [2]: # Example
# Using the start parameter:
for x in range(2, 6):
print(x)

2
3
4
5

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third
parameter: range(2, 30, 3):

In [16]: # Example
# Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)

2
6
10
14
18
22
26

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

In [19]: # Example
# Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")

0
1
2
3
4
5
Finally finished!

In [ ]: # Note: The else block will NOT be executed if the loop


# is stopped by a break statement.

In [14]: # Example
# Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3:
break
print(x)
else:
print("Finally finished!")

#If the loop breaks, the else block is not executed.

0
1
2

Nested Loops
A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

In [20]: # Example
# Print each adjective for every fruit:
countries = ["Nigeria", "Ghana", "South Africa"]
names = ["akura", "paul", "john"]

for country in countries:


for name in names:
print(country, name)

Nigeria akura
Nigeria paul
Nigeria john
Ghana akura
Ghana paul
Ghana john
South Africa akura
South Africa paul
South Africa john

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an
error.

In [22]: # Example
for x in [0, 1, 2]:
pass

# having an empty for loop like this, would raise


# an error without the pass statement

In [4]: # Write a python program to get username, append the username to a list
# called username.

# Ask the user to enter their username if the username is in the list
# called username, print("Hello, you are welcome")
# else print("You have to register")
print("Hello Welcome to my platform, Kindly register!!!")
username = []
user = input("please enter your username: ")
username.append(user)
print("Thank you for registering!!")

print("--------------")
users = input("Kindly enter your username to login: ")
if users in username:
print("Hello, you are welcome")
else:
print("You have to register")

Hello Welcome to my platform, Kindly register!!!


please enter your username: emma
Thank you for registering!!
--------------
Kindly enter your username to login: peter
You have to register

In [23]: # Exercises
# Write a for loop which appends the square of each number in this list:
# [2, 4, 5, 6, 7, 8] to a new list.
# solution
# akura = []
# eanu_numbers = [2, 4, 5, 6, 7, 8]
# for x in eanu_numbers:
# akura.append(x * x)
# print(akura)

# append only positive numbers to a new list.


# [2, -4, 5, -6, 7, -8]
# solution
# akura = []
# eanu_numbers = [2, -4, 5, -6, 7, -8]
# for x in eanu_numbers:
# if x > 0:
# akura.append(x)
# print(akura)

# sum the numbers in this list [2, 4, 5, 6, 7, 8]


# my_numbers = [2, 4, 5, 6, 7, 8]
# john = 0
# for number in my_numbers:
# john = john + number
# print(john)

# Write a program that prints your name 100 times.


# solution
# for i in range(101):
# print(i, ": emma")

0 : emma
1 : emma
2 : emma
3 : emma
4 : emma
5 : emma
6 : emma
7 : emma
8 : emma
9 : emma
10 : emma
11 : emma
12 : emma
13 : emma
14 : emma
15 : emma
16 : emma
17 : emma
18 : emma
19 : emma
20 : emma
21 : emma
22 : emma
23 : emma
24 : emma
25 : emma
26 : emma
27 : emma
28 : emma
29 : emma
30 : emma
31 : emma
32 : emma
33 : emma
34 : emma
35 : emma
36 : emma
37 : emma
38 : emma
39 : emma
40 : emma
41 : emma
42 : emma
43 : emma
44 : emma
45 : emma
46 : emma
47 : emma
48 : emma
49 : emma
50 : emma
51 : emma
52 : emma
53 : emma
54 : emma
55 : emma
56 : emma
57 : emma
58 : emma
59 : emma
60 : emma
61 : emma
62 : emma
63 : emma
64 : emma
65 : emma
66 : emma
67 : emma
68 : emma
69 : emma
70 : emma
71 : emma
72 : emma
73 : emma
74 : emma
75 : emma
76 : emma
77 : emma
78 : emma
79 : emma
80 : emma
81 : emma
82 : emma
83 : emma
84 : emma
85 : emma
86 : emma
87 : emma
88 : emma
89 : emma
90 : emma
91 : emma
92 : emma
93 : emma
94 : emma
95 : emma
96 : emma
97 : emma
98 : emma
99 : emma
100 : emma

In [ ]:

You might also like