Strings, Control flow and Loops¶
Karën Fort (CC BY-NC-SA) -- 2024
Fanny Ducel slightly modified the material.
Before we begin¶
You will have to download the .ipynb files for the labs (TDs) from my website instead of Karën's, as I slightly modified the content.
The URL will be provided during the lab session.
Strings¶
Reminders¶
🥳 What do you already know about strings?
Strings are declared using double quotes or single quotes:
my_string = "saperlipopette !"
my_other_string = 'pouettt'
print(my_string)
print(my_other_string)
saperlipopette ! pouettt
If you need to include quotes in your string, use the other type of quote
chaine = "This is a 'new' string"
print(chaine)
This is a 'new' string
🆕 you can write a multiple line string with three quotes:
bella = '''Una mattina mi sono alzato
O bella ciao, bella ciao, bella ciao ciao ciao
Una mattina mi sono alzato
E ho trovato l'invasor'''
print(bella)
Una mattina mi sono alzato O bella ciao, bella ciao, bella ciao ciao ciao Una mattina mi sono alzato E ho trovato l'invasor
Strings are in Unicode, which means you can represent any language
my_chinese_string = "猫" #the word "cat" in simplified Chinese (according to Google translate)
print(my_chinese_string)
猫
Strings in Python are arrays of bytes.
This means you can access a character of a string like an element in an array.
We'll see soon that we can iterate on a string
poppins_string = "superfragilistiexpialidocious"
print(poppins_string[-2])
u
and yes, do not forget that Python counts from 0! (you will forget, but keep that in mind)
Some operations on strings¶
You already know one of them:
len
: returns the size of the string
print(len(poppins_string))
29
There are also a lot of methods (see here), here are some of them:
print(poppins_string.lower()) #note the difference of syntax: len(x) vs x.upper(), we'll come back to it later
superfragilistiexpialidocious
print(poppins_string.capitalize())
Superfragilistiexpialidocious
Note that some methods take parameters:
trouve = "We will rock you!"
found = trouve.find("rock")#finds the first occurrence of the specified value
print(found)
not_found = trouve.find("show")#returns -1 if not found
print(not_found)
8 -1
song = "only our rivers run free"
final = song.replace("rivers", "people")
print(final)
only our people run free
🥳 Replace "alzato" by "svegliato" in bella:
bella = '''Una mattina mi sono alzato
O bella ciao, bella ciao, bella ciao ciao ciao
Una mattina mi sono alzato
E ho trovato l'invasor'''
# Code Me!
bella.replace("alzato", "svegliato")
"Una mattina mi sono svegliato\nO bella ciao, bella ciao, bella ciao ciao ciao\nUna mattina mi sono svegliato\nE ho trovato l'invasor"
⚠️ Strings are immutable
This means they cannot be modified, once created.
first_string = "Hello, world!"
first_string[0] = "V" #trying to modify the array
print(first_string)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-19-e396701c91c2> in <module> 1 first_string = "Hello, world!" ----> 2 first_string[0] = "V" #trying to modify the array 3 4 print(first_string) TypeError: 'str' object does not support item assignment
However, you can modify the reference to the string:
song = "only our rivers run free"
song = song.replace("rivers", "people")
print(song)
only our people run free
More about print()
¶
By default, the print()
function adds a newline character \n
at the end of the output.
print("this is a")
print("test")
this is a test
print()
can take several parameters and concatenates them with spaces:
import math #you need this to use pi
pi = math.pi
print("The value of pi is", pi,"!")#here, print is used with 3 parameters of different types
The value of pi is 3.141592653589793 !
Control flow¶
if
instruction¶
Theif
operator introduces a block of code which will be executed if and only if the expressed condition is met:
answer = input("Do you feel ok?")
if "no" in answer: # note the ":"!
print("Poor dear! What's wrong?") # note the indentation!
Do you feel ok?yes
if "yes" in answer:
print("Cool!")
Cool!
if
can be included in if
s:
answer = input("how old are you?")
if int(answer) > 50: # note int() to change the type of the answer
if int(answer) > 70:
print("Ok, boomer!") # this print() depends on the "so bad" condition
print("So how was it to live the 80s?") # this print() depends only on the first condition
print("Thank you!") # this print() will execute in all cases
how old are you?10 Thank you!
and
and or
¶
and
and or
are logical operators allowing you to specify (typically) two conditions at the same time:
upper_age = 65
lower_age = 27
my_age = input ("What's your age? ")
if int(my_age) < upper_age and int(my_age) > lower_age: # AND: the two conditions have to be met at the same time
print("There is no SNCF reduction available for you, sorry!")
else:
print("In order for you to get your reduction we need a blood sample and a liver biopsy.")
What's your age? 52 There is no SNCF reduction available for you, sorry!
upper_age = 25
upper_revenue = 35000
my_age = input("What's your age?")
my_revenue = input("What's your annual revenue?")
if int(my_age) > upper_age or int(my_revenue) > upper_revenue: # OR: one of the conditions has to be met
print("There is no benefit available for you, sorry!")
else:
print("In order for you to get your benefit we need a blood sample and a liver biopsy.")
What's your age?26 What's your annual revenue?34000 There is no benefit available for you, sorry!
not
¶
You can negate a condition:
upper_age = 25
my_age = input("What's your age?")
#if not int(my_age) > upper_age:
if int(my_age) < upper_age:
print("You're too young!")
else:
print("You're too old!")
What's your age?23 You're too young!
else
instruction¶
The else
operator introduces a block of code which will be executed if the if
condition is not met. else
is linked to the preceeding if
and does not allow to add a condition:
answer = input("how old are you?")
if int(answer) > 50: # note int() to change the type of the answer
if int(answer) > 70:
print("Ok, boomer!") # this print() depends on the "so bad" condition
print("So how was it to live the 80s?") # this print() depends only on the first condition
else:
print("You're so young!") # this print() will execute only if the > 50 condition is not met
print("Thank you!") # this print() will execute in all cases
how old are you?49 You're so young! Thank you!
elif
instruction¶
elif
is an else
with a condition: it checks both that the condition is true
and that all the previous conditions are false
.
answer = input("how old are you?")
if int(answer) > 50: # note int() to change the type of the answer
if int(answer) > 70:
print("Ok, boomer!") # this print() depends on the "so bad" condition
print("So how was it to live the 80s?") # this print() depends only on the first condition
elif int(answer) > 40:
print("You're older than I thought")
else:
print("You're so young!") # this print() will execute only if none of the previous conditions are met
print("Thank you!") # this print() will execute in all cases
how old are you?45 You're older than I thought Thank you!
for
loops¶
for
loops allow to iterate over elements of containers such as strings, and to access items of those containers individually, in order:
for character in "chat": # this string means "cat" in standard Arabic (according to Google translate)
print(character)
c h a t
Of course, loops and control flow can be mixed:
for character in "cat": # Note the ":"
if character == "c":
print("This is the first character:",character, end=" ")
else:
print(character, end=" ")
This is the first character: c a t
🥳 Print the number of occurrences of "a" and "e" in the following string (please use for
...)
Perec = "Anton Voyl n'arrivait pas à dormir. Il alluma. Son Jaz marquait minuit vingt. Il poussa un profond soupir, s'assit dans son lit, s'appuyant sur son polochon. Il prit un roman, il l'ouvrit, il lut; mais il n'y saisissait qu'un imbroglio confus, il butait à tout instant sur un mot dont il ignorait la signification. "
nb_a = 0
nb_e = 0
for char in Perec:
if char == "a" or char=="A":
nb_a += 1 # nb_a = nb_a + 1
elif char=="e" or char=="E":
nb_e +=1
print("The number of a is", nb_a)
print("The number of e is", nb_e)
The number of a is 23 The number of e is 0
nb_a_or_e = 0
for char in Perec:
if char == "a" or char=="A" or char=="e" or char=="E":
nb_a_or_e += 1 # nb_a = nb_a + 1
print(nb_a_or_e)
23
Practical reminders:¶
- You must work in pairs for the labs and the pairs must change every week.
- NLP people are in my group.
- You must use the files that are on my website (not Karën's)
- You must send your file by the end of the session, to your teacher: NLP people -> to me, SC/Mlex -> Nasser
Before we go back on while
loops and move on, let's recap what we saw last time...¶
Quizz time! - on the lecture¶
- What to use to create a string?
- How to access the second character of a word?
- How to print a string and an int together?
- How to create three conditions? (what keywords to use?)
- What is the difference between
and
,or
,not
? - What happens in a
for loop
?
# Waiting for your answers!
Before we go back on while
loops and move on, let's recap what we saw last time...¶
Quizz time! - on the lecture > answers¶
- strings : simple, double, triple quotes
word[i]
to access element (= character) at position iprint(my_string, my_int)
with a comma, orprint(my_string + str(my_int))
- if/elif/else
and
= both statements must be True,or
= only one must be True,not
= the statement must be False- At each iteration, the loop will "see" one element (= char) of the string. It will continue until it reaches the end of the string.
round = 3
stitch = 1
print("round 1 : 7 regular stitches")
print("round 2 : 7 increases")
while round < 11:
print("round", round,": (", stitch,"regular stitches", "1 increase)*7")
round += 1
round 1 : 7 regular stitches round 2 : 7 increases round 3 : ( 1 regular stitches 1 increase)*7 round 4 : ( 1 regular stitches 1 increase)*7 round 5 : ( 1 regular stitches 1 increase)*7 round 6 : ( 1 regular stitches 1 increase)*7 round 7 : ( 1 regular stitches 1 increase)*7 round 8 : ( 1 regular stitches 1 increase)*7 round 9 : ( 1 regular stitches 1 increase)*7 round 10 : ( 1 regular stitches 1 increase)*7
round(1.543)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[2], line 1 ----> 1 round(1.543) TypeError: 'int' object is not callable
while
loops¶
while
loops indicate a stopping condition for a loop.
i = 1
while i < 10: # Note the ":"
print(i)
i += 1 # Note this operator, which is equivalent to i = i +1
1 2 3 4 5 6 7 8 9
🥳 Print the characters of a string using while
instead of for
(tip: use len
)
# CODE ME!
string = "hello"
print(string[0])
counter = 0
while counter < len(Perec):
print(Perec[counter])
counter += 1
A n t o n V o y l n ' a r r i v a i t p a s à d o r m i r . I l a l l u m a . S o n J a z m a r q u a i t m i n u i t v i n g t . I l p o u s s a u n p r o f o n d s o u p i r , s ' a s s i t d a n s s o n l i t , s ' a p p u y a n t s u r s o n p o l o c h o n . I l p r i t u n r o m a n , i l l ' o u v r i t , i l l u t ; m a i s i l n ' y s a i s i s s a i t q u ' u n i m b r o g l i o c o n f u s , i l b u t a i t à t o u t i n s t a n t s u r u n m o t d o n t i l i g n o r a i t l a s i g n i f i c a t i o n .
What will happen if i write this (you can interrupt the execution by entering i
twice):
while True:
print("spam")
spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam
spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam
spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam spam
--------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) <ipython-input-1-e61e1f19f6ea> in <module> 1 while True: ----> 2 print("spam") ~/Dev/notebook/jupyterenv/lib/python3.6/site-packages/ipykernel/iostream.py in write(self, string) 400 is_child = (not self._is_master_process()) 401 # only touch the buffer in the IO thread to avoid races --> 402 self.pub_thread.schedule(lambda : self._buffer.write(string)) 403 if is_child: 404 # mp.Pool cannot be trusted to flush promptly (or ever), ~/Dev/notebook/jupyterenv/lib/python3.6/site-packages/ipykernel/iostream.py in schedule(self, f) 201 self._events.append(f) 202 # wake event thread (message content is ignored) --> 203 self._event_pipe.send(b'') 204 else: 205 f() ~/Dev/notebook/jupyterenv/lib/python3.6/site-packages/zmq/sugar/socket.py in send(self, data, flags, copy, track, routing_id, group) 618 ) 619 data.group = group --> 620 return super().send(data, flags=flags, copy=copy, track=track) 621 622 def send_multipart( zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send() zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.send() zmq/backend/cython/socket.pyx in zmq.backend.cython.socket._send_copy() ~/Dev/notebook/jupyterenv/lib/python3.6/site-packages/zmq/backend/cython/checkrc.pxd in zmq.backend.cython.checkrc._check_rc() KeyboardInterrupt:
When using while
, one has to be sure that the condition can become false
(can be falsified), else, it will generate an infinite loop.
You can use break
to stop a loop before the condition is false
(it's always better not to use it, but you might see it):
n = 0
while n < 9:
print(n)
if n == 7:
break
n = n + 1
0 1 2 3 4 5 6 7
Of course, for
loops are easier to write in Python, so they are used more often than while
. However, there are times when while
loops will be easier to use:
available_ingredients = ["pepper", "leek", "mushroom", "carot"]
ingredient = input("Please enter an ingredient: ")
while ingredient not in available_ingredients:
print("I don't have that!")
ingredient = input("Please enter an ingredient: ")
print("Ah, yes,", ingredient, "I have some")
Please enter an ingredient: tomato I don't have that! Please enter an ingredient: brussel I don't have that! Please enter an ingredient: mushroom Ah, yes, mushroom I have some
🥳 Write a program that will:
- randomly select a number between 0 and 20
- ask the user to guess this number and if it is not found, to try again
import random
to_find = random.randint(0, 20)
chosen_number = int(input("Choose a number: "))
while chosen_number != to_find:
print("Oops, try again!")
chosen_number = input("Try again: ")
import random
to_find = random.randint(0, 20)
guess = int(input("Guess a number between 0 and 20: "))
while guess != to_find:
guess = int(input("Guess a number between 0 and 20: "))
if guess == to_find:
print("Congrats! The number was", to_find)
Guess a number between 0 and 20: 20 Guess a number between 0 and 20: 15 Guess a number between 0 and 20: 10 Guess a number between 0 and 20: 5 Guess a number between 0 and 20: 1 Guess a number between 0 and 20: 0 Guess a number between 0 and 20: 2 Guess a number between 0 and 20: 3 Guess a number between 0 and 20: 4 Guess a number between 0 and 20: 6 Guess a number between 0 and 20: 8 Guess a number between 0 and 20: 11 Congrats! The number was 11
Good Practices¶
Testing your code¶
- check the values stored in your variables regularly (use
print()
for example) - check with extreme values to see if your code behaves as expected:
- what if the string is "" (empty string)?
- what if the number if negative? 0? a floating number?
Reminders¶
- write clear, explicit code (avoid "geeky" versions of the code)
- add comments
Going further¶
- Other
String
methods: Check the W3School doc