MY Programming

Python Basics Tutorial 4 for loop part 2

Python Icon

4. Looping over dictionaries

person = {"Name": "Alice", "Age": "13", "City": "New York"}

#Keys only (default)

for key in person:

     print(key)

#Keys explicitly

for key in person.keys():

      print(key)

#Values

for value in person.values():

    print(value)

 

#Key + Value (most useful)

for key, value in person.items():

     print(key, "->", value)

 

5. Looping over multiple sequences -> 'zip()'

 

names = ["Alice", "Bob", "Charlie"]

ages =[13, 30, 35]

for name, age in zip(names, ages):

    print (f"{name} is {age} years old")

 

6. Nested 'for' loops

for i in range(1, 4):

     for j in range(1, 4):

         print(i, j)

 

Useful for matrices, combinations, paterns, ect.

 

7.'break', 'continue', and 'else'

#break -> exit the loop immediately

for i in range(10):

      if i ==5:

            break

     print(i)

 

#continue -> skip the rest of the current interation

for i in range(10):

      if i % 2 == 0:

           continue

      print(i)           #only odd numbers

 

#else clause -> runs only if the loop finished normally (no break)

for i in range(5):

     print(i)

else:

     print("Loop finished successfully")

 

8. Practical examples

Sum of numbers:

total = 0

for num in [3, 7, 2, 9]:

  total += num

print(total)

 

Finding something:

numbers = [4, 8, 15, 16, 23, 42]

found = False

for num in numbers:

    if num == 23:

       found = True

       break

if found:

   print("Found 23")

 

Building a new list:

squares = [ ]

for x in range(1, 6):

      squares.append(x ** 2)

      print(squares)

 

9. List/Dict Comprehensions 

 

Instead of a normal for loop + append, you can write:

squares = [x ** 2 for x in range(1, 6)]

 

even = [x for x in range(10) if x % 2 == 0]

 

person_upper = {k: v.upper() for k, v in person.items() if isinstance(v, str)}

These are usually faster and more readable for simple transformations.

 

 

 

How do you rate this article?

4


Slash13
Slash13

I like making music, programming, gaming, blogging.


MY Programming
MY Programming

In this blog i post my programms.

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.

Page not displaying correctly?