Here are some important concepts that we didn't have a chance to go into in great detail last week. You can use the sections below to review the concepts individually. You can also review how they work together in math_game.py
.
Select random items from a set with random.choice()
Generating a list of numbers easily with range()
>>> range(5) [0, 1, 2, 3, 4] >>> for i in range(5): ... print("Hi" * i) ... Hi HiHi HiHiHi HiHiHiHi
The range()
function returns a list of numbers. This is handy for when you want to generate a list of numbers on the fly instead of creating the list yourself.
>>> range(5) [0, 1, 2, 3, 4]
Use range
when you want to loop over a bunch of numbers in a list, or perform an operation a certain number of times:
>>> numbers = range(5) >>> for number in numbers: ... print(number * number) ... 0 1 4 9 16
We could rewrite the above example like this:
>>> for number in range(5): ... print(number * number) ... 0 1 4 9 16
You can also set the start, end, and increment value (called "step") for a range.
>>> for i in range(2,20,2): ... print(i) 2 4 6 8 10 12 14 16 18
Get user input with input()
>>> for i in range(100): ... my_input = input("Please type something> ") ... if my_input == "Quit": ... print("Goodbye!") ... break ... else: ... print("You said: " + my_input) ... Please type something> Hello You said: Hello Please type something> How are you? You said: How are you? Please type something> Quit Goodbye! >>>
Iterating an indeterminate number of times with while
loops
grocery_list = [] testAnswer = input('Press y if you want to enter more groceries: ') while testAnswer == 'y': food = input('Next item:') grocery_list.append(food) testAnswer = input('Press y if you want to enter more groceries: ')
print('Your grocery list:') for food in grocery_list: print(food)