forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdice.py
More file actions
38 lines (29 loc) · 1.09 KB
/
Copy pathdice.py
File metadata and controls
38 lines (29 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import random
def parse_input(input_string):
"""Return `input_string` as an integer between 1 and 6.
Check if `input_string` is an integer number between 1 and 6.
If so, return an integer with the same value. Otherwise, tell
the user to enter a valid number and quit the program.
"""
if input_string.strip() in {"1", "2", "3", "4", "5", "6"}:
return int(input_string)
else:
print("Please enter a number from 1 to 6.")
raise SystemExit(1)
def roll_dice(num_dice):
"""Return a list of integers with length `num_dice`.
Each integer in the returned list is a random number between
1 and 6, inclusive.
"""
roll_results = []
for _ in range(num_dice):
roll = random.randint(1, 6)
roll_results.append(roll)
return roll_results
# ~~~ App's main code block ~~~
# 1. Get and validate user's input
num_dice_input = input("How many dice do you want to roll? [1-6] ")
num_dice = parse_input(num_dice_input)
# 2. Roll the dice
roll_results = roll_dice(num_dice)
print(roll_results) # Remove this line after testing the app