Why are these functions not defined, and does this work? How do I debug this?
Solution 1:
Implement the roll_dice function in hog.py. It takes two arguments: a positive integer called num_rolls giving the number of dice to roll and a dice function
As instructed, your function needs arguments
It returns the number of points scored by rolling the dice that number of times in a turn
Assuming you're using a newer version of Python3, type hints can be added to functions
either the sum of the outcomes or 1 ... call dice() exactly num_rolls times in the body of roll_dice. Remember to call dice() exactly num_rolls times even if Sow Sad happens in the middle of rolling.
list-comprehension can be used to run the function to roll multiple dice, and you can then check for ones or sum the lists
import random
def dice() -> int:
return random.randint(1, 6) # assumed to be 6 sided die
def roll_dice(num_rolls, dice_fn) -> int:
# roll a number of times, and store the results
rolls = [dice_fn() for _ in range(num_rolls)]
# if there's a 1, that's the score, else add all roll values
return 1 if any(r == 1 for r in rolls) else sum(rolls)
if __name__ == "__main__":
num_rolls = input("rolls: ")
# pass in the dice function, don't call it
print(roll_dice(int(num_rolls), dice))
Compared to your attempt ...
- functions ideally shouldn't be nested unless you have a good reason for it. That's more of an advanced topic
-
return
statements are used to return values to other places, and nothing after them will run within that same function - Types matter. A function name should not be referenced by a number, or vice versa. This is a hard problem in Python to deal with
- Dot-notation is reserved for classes and modules. There are no classes defined. The only module you have here is the imported
random