Rishab Patil
Rishab Patil

Reputation: 13

Guessing Game - Looping Problem in Python

I had to build a game which awards players based on their guess. The user guesses a number and the algorithm compares that to a randomly-generated 2-digit number and awards the player accordingly.

Problem: The player needs to play this game 3 times before the game ends. When I loop it 3 times with a while loop it only loops by asking the user for their guess and does not print or return the award message. When I remove the while loop and use a for loop it only runs once and prints the message.

How do I solve this looping issue and run this program thrice?

import random

jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0
play = 3
turns = 1

def lottery_game():
    for x in range(play):
        lottery = random.randrange(10,99)
        lot = list(map(int, str(lottery)))
    
        guess = int(input("Choose a 2 digit number: "))
        n_guess = list(map(int, str(guess)))
    
        if guess == lottery:
            return "You won: " + str(jackpot) + " Euros"
        elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
            return "You won: " + str(award2) + " Euros" 
        elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
            return "You won: " + str(award3) + " Euros"
        else: 
            return "I am sorry, you won: " + str(noaward) + " Euros" + " try again"

while i <= 3:
    lottery_game()
    i = i + 1

Upvotes: 0

Views: 293

Answers (3)

Alderven
Alderven

Reputation: 8260

You need to

  • replace return with print statement:
  • replace while i <= 3 with for i in range(3)

Here is updated code:

import random

jackpot = 10000
award2 = 3000
award3 = 100
noaward = 0


def lottery_game():
    lottery = random.randrange(10, 99)
    lot = list(map(int, str(lottery)))

    guess = int(input('Choose a 2 digit number: '))
    n_guess = list(map(int, str(guess)))

    if guess == lottery:
        print(f'You won: {jackpot} Euros')
    elif n_guess[0] == lot[0] or n_guess[1] == lot[1]:
        print(f'You won: {award2} Euros')
    elif n_guess[0] == lot[1] or n_guess[1] == lot[0]:
        print(f'You won: {award3} Euros')
    else:
        print(f'I am sorry, you won: {noaward} Euros. Try again')


for i in range(3):
    lottery_game()

Sample output:

Choose a 2 digit number: I am sorry, you won: 0 Euros. Try again
Choose a 2 digit number: You won: 100 Euros
Choose a 2 digit number: You won: 10000 Euros

Upvotes: 0

Abhishek Prusty
Abhishek Prusty

Reputation: 864

you have not initialized i

Before the while statement add i=1

Upvotes: 0

Jao
Jao

Reputation: 586

According to your code, you're not initialising your i variable before your while you shoud definitely do it. But for your use case, you shouldn't use a while, you should use a for loop like this:

for i in range(0,3):

This will run the code in the loop three times.

Upvotes: 1

Related Questions