CyberKeeda In Social Media

Python For Loop cheat sheet





A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

  • Loop over a single list with a regular for-in:

     liquors = ["rum", "beer", "whisky", "vodka"] 
     for my_liquor in liquors:
           print("Hello, Lets have " + my_liquor + " today")

Save the file , i named it as alcohol.py and run it from terminal.
  #  python alcohol.py

 Hello, Lets have rum today
 Hello, Lets have beer today
 Hello, Lets have whisky today
 Hello, Lets have vodka today


  • Loop over a single word for-in:

   for letters in "hello":
         print(letters)

Save the file , i named it as demo1.py and run it from terminal.
# python demo1.py

h
e
l
l
o

  • Loop over a single list with a break statement
     liquors = ["rum", "beer", "whisky", "vodka"] 
     for my_liquor in liquors:
           print("Hello, Lets have " + my_liquor + " today")
           if  my_liquor == "whisky":
               break


Save the file , i named it as demo2.py and run it from terminal.
# python demo2.py

Hello, Lets have rum today
Hello, Lets have beer today
Hello, Lets have whisky today

  • Loops over multiple lists

liquors = ["rum", "beer", "whisky", "vodka"]
customers= ["John", "Sam", "Jack", "Ria"]
for liquor, customer in zip(liquors, customers):
    print( customer + " will have " + liquor)


Save the file , i named it as demo3.py and run it from terminal.


# python demo3.py

John will have rum
Sam will have beer
Jack will have whisky
Ria will have vodka

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
Designed By Kunal Saha