Fman_95
Fman_95

Reputation: 9

Why am I being displayed repeating inputs when executing the code inside a while loop?

After entering the the first two inputs inside the while loop, it fails to proceed to the next IF statement which includes the comparable operator of the previous input. Instead I'm getting the reoccurring inputs. What is the fix?

Thanks.

P.S. I'm a newbie here so apologies for the lack of understanding.

import random

game_started = True


while True:
    name = input("What is your name? ")
    roll_dice = input(f"Would you like to roll the dice {name}?(Y/N) ").lower
    
    if roll_dice == "y":
        player_number = random.randint(1, 6)
        print(f"You rolled a {player_number}!")
        ai_number = random.randint(1, 6)
        print(f"The computer rolled the die and got {ai_number}")
        
        if player_number > ai_number:
            print(f"YOU WIN! Your die number of {player_number} was bigger than the computers rolled die of {ai_number}")
            break
        elif player_number < ai_number:
            print(f"YOU LOST! The computer rolled a higher number of {ai_number} to your {player_number}")
            break
        elif player_number == ai_number:
            print(f"IT'S A DRAW! Both the you and the computer rolled the same number of {player_number}")
            break

Upvotes: 0

Views: 54

Answers (1)

Exelian
Exelian

Reputation: 5888

The while loop is infinite so it need an explicit break to exit:

import random

while True:
    name = input("What is your name? ")
    roll_dice = input(f"Would you like to roll the dice {name}?(Y/N) ").lower()
    
    if roll_dice == "y":
        player_number = random.randint(1, 6)
        print(f"You rolled a {player_number}!")
        ai_number = random.randint(1, 6)
        print(f"The computer rolled the die and got {ai_number}")
        
        if player_number > ai_number:
            print(f"YOU WIN! Your die number of {player_number} was bigger than the computers rolled die of {ai_number}")
            break
        elif player_number < ai_number:
            print(f"YOU LOST! The computer rolled a higher number of {ai_number} to your {player_number}")
            break
        elif player_number == ai_number:
            print(f"IT'S A DRAW! Both the you and the computer rolled the same number of {player_number}")
            break
    else: # When you don't select Y for the roll dice
        break

Upvotes: 2

Related Questions