Sunday, September 16, 2018

Python Ninja Bootcamp 17-for loop

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".


Let's see some example-

Create for loop

for & list

l=[1,2,3,4,5] 
print(l)
>> [1,2,3,4,5]


# Display all the elements in the list l
for var in l:
    print(var)
>>  1
      2
      3
      4
      5

# Display all the elements even in the list l
for var in l:    
   if var%2 == 0:
        print(var)
>> 2
     4

# Display all the elements odd in the list l
for var in l:    
   if var%2 != 0:
        print(var)
>> 1
     3
     5

# Display sum all the elements in the list l
sum=0
for var in l:
    sum += var
print(sum)
>> 15


for & string

s= 'Hello World' 
print(s)
>> 'Hello World'

# Display all the elements in the string one by one
for var in s:
    print(var)
>> H
      e
      l
      l
     o

     W
      o
      r
      l
     d


for & tuple


t=(1,2,3,'four',five)
print(t)
>> (1,2,3,'four','five')


# Display all the elements in the tuple one by one
for var in s:
    print(var)
>> 1
     2
     3
     'four'
     'five'


for & Dictionary


d={'k1':1,'k2':2,'k3':3}

print(d)
>> { 'k1':1,'k2':2,'k3':3 }


# Display all the keys in the dictionary one by one
for var in d:
    print(var)
>> k1
     k2
     k3

# Display all the key-value pairs in the dictionary one by one
for key,val in d:
    print(key)
    print(val)
>> k1
     1
     k2
     2
     k3
     3



EDITS ARE WELCOMED!!


In the next Blog, we will discuss while loop 

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-_1R1xnw

Instagram-
https://www.instagram.com/python.india/

View the Jupyter Notebook for this lecture

Download the Jupyter Notebook for this lecture 



Feel free contact me on-
Email - sn.gurukul24.7uk@gmail.com

No comments:

Post a Comment