Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

For Loop Python

Uploaded by

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

For Loop Python

Uploaded by

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

For loop

1. A for-loop is a set of instructions that is repeated, or


iterated, for every value in a sequence.
2. Sometimes for-loops are referred to as definite
loops because they have a predefined begin and end as
bounded by the sequence.
Syntax

for looping variable in sequence:


code block
TRY IT! What is the sum of every integer from
1 to 3? WHAT IS HAPPENING?
1. First, the function range(1, 4) is generating a list of numbers
beginning at 1 and ending at 3.
n=0 Check the description of the function range and get familiar
with how to use it.
for i in range(1, 4): In a very simple form, it is range(start, stop, step), and
the step is optional with 1 as the default.
n=n+i
2. The variable n is assigned the value 0.
3. The variable i is assigned the value 1.
4. The variable n is assigned the value n + i (0+1=10+1=1).
print(n) 5. The variable i is assigned the value 2.
6. The variable n is assigned the value n + i (1+2=31+2=3).
7. The variable i is assigned the value 3.
8. The variable n is assigned the value n + i (3+3=63+3=6).
Output 9. With no more values to assign in the list, the for-loop is
terminated with n = 6.
6
EXAMPLE: Print all the characters in the string "banana".

for c in "banana": Output


print(c) b
a
n
a
n
a
EXAMPLE: Print all the characters in the string "banana".
ALTERNATIVE METHOD
s = "banana" Output
for i in range(len(s)): b
a
print(s[i]) n
a
n
a
EXAMPLE: Given a List of integers, a, add all the elements of a.
s=0
a = [2, 3, 1, 3, 3] Output
for i in a: 12
s += i
print(s)
EXAMPLE: Define a dictionary and loop through all the keys
and values.
dict = {"One":1, "Two":2, "Three":3}
Output
One 1
Two 2
for key in dict.keys(): Three 3
print(key, dict[key])
NOTE: In the above example,
we first get all the keys using
the method keys, and then use
the key to get access the value.
EXAMPLE: Define a dictionary and loop through all the keys
and values. ALTERNATIVE METHOD
dict = {"One":1, "Two":2, "Three":3}
Output
One 1
Two 2
for key, value in dict.items(): Three 3
print(key, value)
NOTE: Alternatively, we could
use the item method in a
dictionary, and get the key and
value at the same time
Loop Through Set Items

set = {"apple", "banana", "cherry"} Output


banana
for x in set: cherry
print(x) apple
Loop Through Tuples Items

tuple = ("apple", "banana", "cherry“) Output


apple
for x in tuple: banana
print(x) cherry
Suppose we want to find even numbers from 0 to 20 then we can do it
using a for loop, as shown below:

nums = []
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
for x in range(21):
if x%2 == 0:
nums.append(x)
print(nums)

NOTE: The same result can be easily achieved


using a list comprehension technique shown in
next slide
Find even numbers from 0 to 20

USING FOR LOOP USING COMPREHENSION


nums = [] nums = [x for x in range(21) if x%2 == 0]
for x in range(21): print(nums)
if x%2 == 0:
nums.append(x)
print(nums)
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
EXPLANATION
1. In the Previous Slide, [x for x in range(21) if x%2 == 0] returns a new list
using the list comprehension.
2. First, it executes the for loop for x in range(21) if x%2 == 0.
3. The element x would be returned if the specified condition if x%2 == 0
evaluates to True. If the condition evaluates to True, then the
expression before for loop would be executed and stored in the new
list.
4. Here, expression x simply stores the value of x into a new list.
Example: List Comprehension
List comprehension to build a list of squares of the numbers between
1 and 10.

squares = [x*x for x in range(11)]


print(squares)

Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
List comprehension with string lists

names = ['Steve', 'Bill', 'Ram', 'Mohan', 'Abdul']


names2 = [s for s in names if 'a' in s]
print(names2)

Output
['Ram', 'Mohan']
List Comprehension using Nested Loops

nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
nums=[(x,y) for x in nums1 for y in nums2]
print(nums)

Output
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
List Comprehension with Multiple if Conditions

nums = [x for x in range(21) if x%2==0 if x%5==0]


print(nums)

Output
[0, 10, 20]
List Comprehension with if-else Condition
EXAMPLE 1
odd_even_list = ["Even" if i%2==0 else "Odd" for i in range(5)]
print(odd_even_list)

Output
['Even', 'Odd', 'Even', 'Odd', 'Even']
List Comprehension with if-else Condition
EXAMPLE 2
odd_even_list = [str(i) + '=Even' if i%2==0 else str(i) + "=Odd" for i in range(5)]
print(odd_even_list)

Output
['0=Even', '1=Odd', '2=Even', '3=Odd', '4=Even']
ZIP Function in Python
The zip() function returns a zip object, which is an iterator of tuples
where the first item in each passed iterator is paired together,
and then the second item in each passed iterator are paired together
etc.
EXAMPLE: if we have two lists with same length, and we want to loop through
them, we could do as the following example using the zip function:

a = ["One", "Two", "Three"] Output


b = [1, 2, 3] One 1
Two 2
Three 3
for i, j in zip(a, b):
print(i, j)
THANK YOU !!!!

You might also like