3 Loops
3 Loops
Python’s documentation:
https://docs.python.org/3/
GOOGLE in general!!!
Do not repeat yourself
foggodavid
Let’s say, we want to
print the name
character by character
You can access it with it’s position
● Index between [ ]
Strings
● First character
○ print(name[0])
● Last character
You can access a specific ○ print(name[-1])
character
Be careful! Indices start at 0
3.01. Exercise: Print first and
last character
Ask for a word and print it’s first
and last characters
Let’s try it
03-01-stringCharacter.py
To not repeat the code...
And to avoid the previous problem,
we can make use of loops Python
There are two kinds of
loops: for and while
Previous example with loops
foggodavid
for i in range(3):
print(i)
5 range(0,10) == range(10)
6
7
Range function: steps
calculations result = 1
for i in range(1, number+1):
result = result * i
In the same way, we can also do
print(result)
math in loops
Let’s try it
03-04-factorial.py
Unknown number of loops
Or, conditional loops
It is also useful for a fixed number of
Conditional loops loops
(while) i=0
while i < 3:
In general, we will use them in two print(i)
scenarios: i=i+1
● While a condition is reached
● Unknown number of loops
Design of loops
i=3
while i < 3:
print(i)