Now we know how for loops work in Python. But for loops aren't limited to printing each item in a list, they can do a lot more.
To be able to understand for loop tricks we need to first know assigning values to multiple variables at once. It works like this:
>>> a, b = 1, 2
>>> a
1
>>> b
2
>>>
We can use ()
and []
around these values however we want and
everything will still work the same way. []
creates a list, and
()
creates a tuple.
>>> [a, b] = (1, 2)
>>> a
1
>>> b
2
>>>
We can also have []
or ()
on one side but not on the other
side.
>>> (a, b) = 1, 2
>>> a
1
>>> b
2
>>>
Python created a tuple automatically.
>>> 1, 2
(1, 2)
>>>
If we're for looping over a list with pairs of values in it we could do this:
>>> items = [('a', 1), ('b', 2), ('c', 3)]
>>> for pair in items:
... a, b = pair
... print(a, b)
...
a 1
b 2
c 3
>>>
Or we can tell the for loop to unpack it for us.
>>> for a, b in items:
... print(a, b)
...
a 1
b 2
c 3
>>>
Now you're ready to read this awesome looping tutorial. Read it now, then come back here and do the exercises.
-
Create a program that works like this. Here I entered everything after the
>
prompt that the program displayed.Enter something, and press Enter without typing anything when you're done. >hello there >this is a test >it seems to work > Line 1 is: hello there Line 2 is: this is a test Line 3 is: it seems to work
-
Create a program that prints all letters from A to Z and a to z next to each other:
A a B b C c ... X x Y y Z z
Start your program like this:
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' lowercase = 'abcdefghijklmnopqrstuvwxyz'
Hint: how do strings behave with
zip
? Try it out on the>>>
prompt and see. -
Can you make it print the indexes also?
1 A a 2 B b 3 C c ... 24 X x 25 Y y 26 Z z
The answers are here.
If you have trouble with this tutorial please tell me about it and I'll make this tutorial better. If you like this tutorial, please give it a star.
You may use this tutorial freely at your own risk. See LICENSE.