Python how-tos
Contents
1 How to create an infinite loop
while True: # always true
# your code in this block
2 How to loop from 1 to 100
for i in range(1, 101): # note 101 = 100+1
# your code in this block
3 How to break out of nested loops
done = False
while not done: # not done is True until done turns True or not done False
while not done:
# your code in this block
# set done = True and continue when you're done
Example:
done = False
while not done:
while not done:
inp = input('(h)ello, (q)uit? ')
if inp == 'h':
print('Hello')
elif inp == 'q':
done = True
# no need to continue here because of an exclusive else below
else:
print('Invalid input')
4 How to read a string input from the keyboard
inp = input('Input your string: ') # you don't need to print('Input your string: ')
# because input() does it for you
5 How to generate a pseudo-random number
5.1 Float in $[0, 1)$
from random import random # import the random function
x = random() # random() doesn't take any arguments
`random() never returns 1 so if you want to split its output into two equally probable ranges, `[python]0 <= x < 0.5 and `0.5 <= x < 1 is correct, not `[python]0 <= x <= 0.5 and `0.5 < x < 1. Since we know its output is always within $[0, 1)$, `[python]x < 0.5 and ``0.5 <= x'' would suffice.
5.2 Integer in $[1, 100]$
from random import randint # import the randint function
x = randint(1, 100) # randint() takes two arguments: start and end
Note that the second argument is not `100+1 like in `[python]range(). In fact, `randint(a, b) is equivalent to `[python]randrange(a, b+1).