-2

I'm trying to create a number guessing game but when I run this it keeps running the while loop and doesnt break out. (very new to python by the way) thanks!

from random import randint
name1 = input("What is Player One's first name? ")
name2 = input("What is Player Two's first name? ")
cnumber = randint(1,25)
guess1 = ""
guess2 = ""
times_guessed1 = 0
times_guessed2 = 0

while guess1 != cnumber and guess2 != cnumber:
    guess1 = input(name1 + " guess a number between 1 and 25: ")
    times_guessed1 += 1
    guess2 = input(name2 + " guess a number between 1 and 25: ")
    times_guessed2 += 1

if guess1 == cnumber:
    print (name1, "wins!")
    print ("You guessed,", times_guessed1, "times.")
elif guess2 == cnumber:
    print (name2, "wins!")
    print ("You guessed,", times_guessed2, "times.")
revoh
  • 7

3 Answers3

1

input() returns a str.

randint(1,25) returns an int.

When it compares, '2' with 2, it will be false in python.

Solution: convert the input to int like below.

guess1 = int(input(name1 + " guess a number between 1 and 25: "))
guess2 = int(input(name2 + " guess a number between 1 and 25: "))
NanoBit
  • 196
  • 1
  • 10
0

input will return a string use int(input()) to covert to int to be able to match with randint

TheBigW
  • 54
  • 1
0

cnumber is an int, but guess1 and guess2 are strings, so they are never equal, because their types are different. The easiest would be to convert cnumber to a string: cnumber = str(randint(1,25)).

  • The advantage of converting cnumber is, that your program does not crash if something that can not be converted to int is entered. – chillturtle Nov 23 '20 at 18:00