Skip to content

Commit 4a5da66

Browse files
committed
add loops
1 parent c48e795 commit 4a5da66

File tree

4 files changed

+363
-11
lines changed

4 files changed

+363
-11
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ it.**
3131
6. [Using functions](using-functions.md)
3232
7. [If, else and elif](if.md)
3333
8. [ThinkPython: Lists](lists.md)
34+
9. [Loops](loops.md)
3435

3536
Other things this tutorial comes with:
3637

answers.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,87 @@ These are answers for exercises in the chapters. In programming, there's always
110110
>>>
111111
```
112112

113+
## Loops
114+
115+
1.
116+
117+
```py
118+
users = [
119+
['foo', 'bar'],
120+
['biz', 'baz'],
121+
]
122+
123+
username = input("Username: ")
124+
password = input("Password: ")
125+
126+
logged_in = False
127+
for user in users:
128+
if username == user[0] and password == user[1]:
129+
logged_in = True
130+
break
131+
132+
if logged_in:
133+
print("Welcome, " + username + "!")
134+
else:
135+
print("Wrong username or password.")
136+
```
137+
138+
2. Just put the whole thing in a `while True:`. Remember that a break
139+
will always break the innermost loop it's in.
140+
141+
```py
142+
users = [
143+
['foo', 'bar'],
144+
['biz', 'baz'],
145+
]
146+
147+
while True:
148+
username = input("Username: ")
149+
password = input("Password: ")
150+
151+
logged_in = False
152+
for user in users:
153+
if username == user[0] and password == user[1]:
154+
logged_in = True
155+
break # break the for loop
156+
157+
if logged_in:
158+
print("Welcome, " + username + "!")
159+
break # break the while loop
160+
else:
161+
print("Wrong username or password.")
162+
```
163+
164+
3. Add a for loop that works as an attempt counter.
165+
166+
```py
167+
users = [
168+
['foo', 'bar'],
169+
['biz', 'baz'],
170+
]
171+
172+
for attempts_left in [3, 2, 1, 0]:
173+
if attempts_left == 0:
174+
print("No attempts left!")
175+
break
176+
177+
print(attempts_left, "attempts left.")
178+
username = input("Username: ")
179+
password = input("Password: ")
180+
181+
logged_in = False
182+
for user in users:
183+
if username == user[0] and password == user[1]:
184+
logged_in = True
185+
break # break the inner for loop
186+
187+
if logged_in:
188+
print("Welcome, " + username + "!")
189+
break # break the outer for loop
190+
else:
191+
print("Wrong username or password.")
192+
```
193+
113194
***
114195

115196
You may use this tutorial freely at your own risk. See [LICENSE](LICENSE).

introduction.md

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,20 @@ Everything in this tutorial contains lots of examples, and the tutorial
1010
should be easy to follow. But what should you do if you don't understand
1111
something the first time you read it?
1212

13-
1. Read the example code and the explanation for it again.
14-
2. Try the example yourself.
15-
3. If you still don't understand, please [tell me](contact-me.md). I
16-
want to improve the tutorial so other readers won't have the same
17-
problem you had.
18-
19-
One of the most important things with learning to program is to
20-
**not fear mistakes**. If you make a mistake, your computer will not
21-
break in any way. You'll get an error message that tells you what's
22-
wrong and where. Even professional programmers do mistakes and get error
23-
messages all the time, and there's nothing wrong with it.
13+
- Read the example code and the explanation for it again.
14+
- Try the example yourself.
15+
- If there's something you haven't seen before in the tutorial and it's
16+
not explained, try to find it from the previous chapters.
17+
- If you still have trouble understanding the tutorial or any other
18+
problems with the tutorial, please [tell me](contact-me.md). I want
19+
to improve the tutorial so other readers won't have the same
20+
problems as you have.
21+
22+
One of the most important things with learning to program is to **not
23+
fear mistakes**. If you make a mistake, your computer will not break in
24+
any way. You'll get an error message that tells you what's wrong and
25+
where. Even professional programmers do mistakes and get error messages
26+
all the time, and there's nothing wrong with it.
2427

2528
Even though a good tutorial is an important part about learning to
2629
program, you also need to learn to make your own things. Use what you

loops.md

Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
# Loops
2+
3+
In programming, a **loop** means repeating something multiple times.
4+
There are different kinds of loops:
5+
6+
- **While loops** repeat something while a condition is true.
7+
- **Until loops** repeat something until a condition is true.
8+
- **For loops** repeat something for each element of a sequence.
9+
10+
We'll talk about all of these in this tutorial.
11+
12+
## While loops
13+
14+
Now we know how if statements work.
15+
16+
```py
17+
its_raining = True
18+
if its_raining:
19+
print("Oh crap, it's raining!")
20+
```
21+
22+
While loops are really similar to if statements.
23+
24+
```py
25+
its_raining = True
26+
while its_raining:
27+
print("Oh crap, it's raining!")
28+
# we'll jump back to the line with the word "while" from here
29+
print("It's not raining anymore.")
30+
```
31+
32+
If you're not familiar with while loops, the program's output may be a
33+
bit surprising:
34+
35+
```
36+
Oh crap, it's raining!
37+
Oh crap, it's raining!
38+
Oh crap, it's raining!
39+
Oh crap, it's raining!
40+
Oh crap, it's raining!
41+
Oh crap, it's raining!
42+
Oh crap, it's raining!
43+
Oh crap, it's raining!
44+
Oh crap, it's raining!
45+
Oh crap, it's raining!
46+
Oh crap, it's raining!
47+
Oh crap, it's raining!
48+
Oh crap, it's raining!
49+
Oh crap, it's raining!
50+
Oh crap, it's raining!
51+
(much more raining)
52+
```
53+
54+
Again, this program does not break your computer. It just prints the
55+
same thing multiple times. We can interrupt it by pressing Ctrl+C.
56+
57+
In this example, `its_raining` was the **condition**. If something in
58+
the while loop would have set `its_raining` to False, the loop would
59+
have ended and the program would have printed `It's not raining anymore`.
60+
61+
Let's actually create a program that does just that:
62+
63+
```py
64+
its_raining = True
65+
while its_raining:
66+
print("It's raining!")
67+
answer = input("Or is it? (y=yes, n=no) ")
68+
if answer == 'y':
69+
print("Oh well...")
70+
elif answer == 'n':
71+
its_raining = False # end the while loop
72+
else:
73+
print("Enter y or n next time.")
74+
print("It's not raining anymore.")
75+
```
76+
77+
Running the program may look like this:
78+
79+
```
80+
It's raining!
81+
Or is it? (y=yes, n=no) i dunno
82+
Enter y or n next time.
83+
It's raining!
84+
Or is it? (y=yes, n=no) y
85+
Oh well...
86+
It's raining!
87+
Or is it? (y=yes, n=no) n
88+
It's not raining anymore.
89+
```
90+
91+
We can also interrupt a loop even if the condition is still true using
92+
the `break` keyword. In this case, we'll set condition to True and rely
93+
on nothing but `break` to end the loop.
94+
95+
```py
96+
while True:
97+
answer = input("Is it raining? (y=yes, n=no) ")
98+
if answer == 'y':
99+
print("It's raining!")
100+
elif answer == 'n':
101+
print("It's not raining anymore.")
102+
break # end the loop
103+
else:
104+
print("Enter y or n.")
105+
```
106+
107+
The program works like this:
108+
109+
```py
110+
Is it raining? (y=yes, n=no) who knows
111+
Enter y or n.
112+
Is it raining? (y=yes, n=no) y
113+
It's raining!
114+
Is it raining? (y=yes, n=no) n
115+
It's not raining anymore.
116+
```
117+
118+
## Until loops
119+
120+
Python doesn't have until loops. If you need an until loop, use
121+
`while not`:
122+
123+
```py
124+
raining = False
125+
while not raining:
126+
print("It's not raining.")
127+
if input("Is it raining? (y/n) ") == 'y':
128+
raining = True
129+
print("It's raining!")
130+
```
131+
132+
## For loops
133+
134+
Let's say we have a list of things we want to print. To print each item
135+
in stuff, we could just do a bunch of prints:
136+
137+
```py
138+
stuff = ['hello', 'hi', 'how are you doing', 'im fine', 'how about you']
139+
140+
print(stuff[0])
141+
print(stuff[1])
142+
print(stuff[2])
143+
print(stuff[3])
144+
print(stuff[4])
145+
```
146+
147+
The output of the program is like this:
148+
149+
```py
150+
hello
151+
hi
152+
how are you doing
153+
im fine
154+
how about you
155+
```
156+
157+
But this is only going to print five items, so if we add something to
158+
stuff, it's not going to be printed. Or if we remove something from
159+
stuff, we'll get an error saying "list index out of range".
160+
161+
We could also create an index variable, and use a while loop:
162+
163+
```py
164+
>>> length_of_stuff = len(stuff) # len(x) is the length of x
165+
>>> index = 0
166+
>>> while index < length_of_stuff:
167+
... print(stuff[index])
168+
... index += 1
169+
...
170+
hello
171+
hi
172+
how are you doing
173+
im fine
174+
how about you
175+
>>>
176+
```
177+
178+
But there's `len()` and an index variable we need to increment. That's
179+
a lot of stuff to worry about for just printing each item.
180+
181+
This is when for loops come in:
182+
183+
```py
184+
>>> stuff = ['hello', 'hi', 'how are you doing', 'im fine', 'how about you']
185+
>>> for thing in stuff:
186+
... # this is repeated for each element of stuff, that is, first
187+
... # for stuff[0], then for stuff[1], etc.
188+
... print(thing)
189+
...
190+
hello
191+
hi
192+
how are you doing
193+
im fine
194+
how about you
195+
>>>
196+
```
197+
198+
Without the comments, that's only two simple lines, and one variable.
199+
Much better than anything else we tried before.
200+
201+
```py
202+
>>> for thing in stuff:
203+
... print(thing)
204+
...
205+
hello
206+
hi
207+
how are you doing
208+
im fine
209+
how about you
210+
>>>
211+
```
212+
213+
There's only one big limitation with for looping over lists. You
214+
shouldn't modify the list in the for loop. If you do, the results can
215+
be surprising:
216+
217+
```py
218+
>>> stuff = ['hello', 'hi', 'how are you doing', 'im fine', 'how about you']
219+
>>> for thing in stuff:
220+
... stuff.remove(thing)
221+
...
222+
>>> stuff
223+
['hi', 'im fine']
224+
>>>
225+
```
226+
227+
Instead, you can create a copy of stuff and loop over it.
228+
229+
```py
230+
>>> stuff = ['hello', 'hi', 'how are you doing', 'im fine', 'how about you']
231+
>>> for thing in stuff.copy():
232+
... stuff.remove(thing)
233+
...
234+
>>> stuff
235+
[]
236+
>>>
237+
```
238+
239+
Or if you want to clear a list, just use the `.clear()` list method.
240+
241+
```py
242+
>>> stuff = ['hello', 'hi', 'how are you doing', 'im fine', 'how about you']
243+
>>> stuff.clear()
244+
>>> stuff
245+
[]
246+
>>>
247+
```
248+
249+
## Excercises
250+
251+
1. Back in "Using if, else and elif" we created a program that asked
252+
for username and password and checks them, and we made users "foo"
253+
and "bar" with passwords "biz" and "baz". Adding a new user would
254+
have required adding more code that checks the username and
255+
password. Add this to the beginning of your program:
256+
257+
```py
258+
users = [
259+
['foo', 'bar'],
260+
['biz', 'baz'],
261+
]
262+
```
263+
264+
Then rewrite the rest of the program using a for loop.
265+
266+
2. Make the program ask the username and password over and over again
267+
3. Can you limit the number of attempts to 3?

0 commit comments

Comments
 (0)