Reputation: 11
I am trying to make small random guessing game in PYTHON, it works fine however after the user plays I would like it to revert back to the start and allow the user to play again if "y" is entered. So it would revert back to the top of the code. I understand its a loop but i cant figure out how to make it work. any help is greatly appreciated!
import random
bet = input("How much would you like to bet?")
print ("You are betting €",bet,)
win = int(bet) * int(2)
print('Pick either 1 or 0')
number = random.randint(0,1)
guess = 0
while number < 2:
guess_number = int(input('Enter a number:'))
if guess_number == number:
print('Your guess is correct the number is',number)
print("you have won €",win,)
break
if guess_number >=2:
print ("Number too high")
else:
print("you are wrong, you have lost €",bet,)
break
play_again = input("Play Again? y/n")
y = bet
n = print("bye")
if play_again == y:
bet
Upvotes: 0
Views: 134
Reputation: 459
You could also put your code in a function as so:
import random
def game():
bet = input("How much would you like to bet?")
print ("You are betting €",bet,)
win = int(bet) * int(2)
print('Pick either 1 or 0')
number = random.randint(0,1)
guess = 0
while number < 2:
guess_number = int(input('Enter a number:'))
if guess_number == number:
print('Your guess is correct the number is',number)
print("you have won €",win,)
break
if guess_number >=2:
print ("Number too high")
else:
print("you are wrong, you have lost €",bet,)
break
play_again = input("Play Again? y/n: ")
if play_again =='y':
game()
if play_again =='n':
n = print("bye")
game()
Upvotes: 0
Reputation: 384
Put the entire code (apart from import random
) in a while
loop.
while True:
bet = input("How much would you like to bet?")
print ("You are betting €",bet,)
win = int(bet) * int(2)
print('Pick either 1 or 0')
number = random.randint(0,1)
guess = 0
while number < 2:
guess_number = int(input('Enter a number:'))
if guess_number == number:
print('Your guess is correct the number is',number)
print("you have won €",win,)
break
if guess_number >=2:
print ("Number too high")
else:
print("you are wrong, you have lost €",bet,)
break
play_again = input("Play Again? y/n")
if play_again.lower() == "y":
continue
else:
break
Upvotes: 1