Search code examples
pythoncurrency

Continue playing this game until they have 0 or less in the money_amount


I want the user to continue playing this game until they have 0 or less in the money_amount. How can i possibly do this?

import numpy as np

random_number = np.random.randint(1, 6)
money_amount = 10

try:
    user_wager = int(input('Your wager: '))
    if (user_wager < 0) or (user_wager > money_amount):
        print("You don't have that amount of money!")
except(ValueError):
    print('Enter a numerical value!')

try:
    user_guess = int(input('Guess: '))
    if (user_guess < 1) or (user_guess > 5):
        print('Please choose a number between 1 and 5!')
    elif user_guess == random_number:
        money_amount += user_wager
        print(f'Correct! You now have ${money_amount}!')
    else:
        money_amount -= user_wager
        print(f'Wrong! The number was {random_number} and you now have ${money_amount}.')
except(ValueError):
    print('Choose a number!')

Solution

  • The best way to do this would be to use a while loop. From the wiki:

    While loops, like the ForLoop, are used for repeating sections of code - but unlike a for loop, the while loop will not run n times, but until a defined condition is no longer met. If the condition is initially false, the loop body will not be executed at all.

    For your game you want to loop "while" the player has "more than" "0" dollars. So you're loop will be:

    while money_amount > 0:
        # game logic