← Back to all posts
##### random number
SethElder1

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" ?

Voters
SethElder1
hotnewtop
widz

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:
break
else:
print("so you were wrong, good luck next time")

Spacecraft

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.

SixBeeps

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.

ch1ck3n

@SixBeeps so basically line 3 should be

`.css-o0gntx{position:absolute;left:-9999px;}.css-4kcfpn{-webkit-align-items:stretch;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;border-width:0;border-style:solid;box-sizing:border-box;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-basis:auto;-ms-flex-preferred-size:auto;flex-basis:auto;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;outline:none;min-height:0;min-width:0;position:absolute;left:-9999px;}n = int(input("guess a number from 1 to 10:"))`