Learn Python like a Professional! Take You from 0 to Hero
In this Python lecture, we will learn about the for loop.
"for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Loop continues until we reach the last item in the objects".
"for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Loop continues until we reach the last item in the objects".
Let's see some example-
Create for loop
for & list
Create for loop
for & list
l=[1,2,3,4,5]
print(l)
# Display all the elements in the list l
for var in l: print(var)
2
3
4
5
# Display all the elements even in the list l
for var in l:
if var%2 == 0: print(var)
4
# Display all the elements odd in the list l
for var in l:
if var%2 != 0: print(var)
3
5
# Display sum all the elements in the list l
sum=0
for var in l:
sum += var
print(sum)
>> 15
for & string
for & string
s= 'Hello World'
print(s)
# Display all the elements in the string one by one
for var in s:
print(var)
e
l
l
o
W
o
r
l
d
for & tuple
t=(1,2,3,'four',five)
print(t)
# Display all the elements in the tuple one by one
for var in s:
print(var)
2
3
'four'
'five'
for & Dictionary
d={'k1':1,'k2':2,'k3':3}
print(d)
# Display all the keys in the dictionary one by one
for var in d:
print(var)
k2
k3
# Display all the key-value pairs in the dictionary one by one
for key,val in d:
print(key)
print(val)
1
k2
2
k3
3
In the next Blog, we will discuss while loop
https://sngurukuls247.blogspot.com/2018/09/python-ninja-bootcamp-18-while-break.html
......................................................................................................................................
Instagram-
https://www.instagram.com/python.india/
View the Jupyter Notebook for this lecture
Download the Jupyter Notebook for this lecture
https://sngurukuls247.blogspot.com/2018/09/python-ninja-bootcamp-18-while-break.html
......................................................................................................................................
Follow the link below to access Free Python Lectures-
https://www.youtube.com/channel/UCENc9qI7_r8KMf6-_1R1xnwInstagram-
https://www.instagram.com/python.india/
View the Jupyter Notebook for this lecture
Feel free contact me on-
Email - sn.gurukul24.7uk@gmail.com
No comments:
Post a Comment