Ask coding questions

← Back to all posts
random number

so im trying to get the code to run until the user guesses the right number, but for some reason, even if the user guesses the right answer, it still says "sorry that was wrong" (or whatever i put in the code) any ideas why it isnt printing the "congradulations" ?


simply x need to be the first line
import random

x = random.randint(0, 10)
while 1:
print("guess a number from 1 to 10, then i will say a random number, and we will see if you get it right,")
n = int(input("guess a number from one to ten:"))
if n == x:
print("Congradulations, thats correct")
print("so you were wrong, good luck next time")


Inputs are always in the form of a string, even if they are numbers. You are trying to compare a string and an integer, so they never match. Either convert the input into an integer or convert the random number into a string and then compare them.


This is a very common issue seen in new developers (especially ones who are learning Python or JavaScript, in your case Python) where you are trying to compare two values which are of different types.

When you call input(), it will always return a string. If you type in 12, it will be the string "12".

Calling random.randint() will always return a number, never a string. Because of this, and input and a random number will never directly be the same. "12" is not the same as 12.

If you want to properly compare these two, you have to match the types. This can either be done using the int() function to turn the input into a number, or with the str() function to turn the random number into a string.


@SixBeeps so basically line 3 should be