-1

I am trying to create a guessing game where I have a variable that gets a random value and then a while loop that requires me to type in a number. This should go on until I get the same value as the random generated one and then print out a list with all the numbers that I typed in. For some reason the loop goes on and on even when I do get the same number.

This is my code so far:

import random

x = random.randint(1,10)
y = []
lst = []

while y != x:
    y = input('Your number:')
    lst.append(y)
    pass
print(lst)

Thank you!

Edd
  • 13
  • 1

4 Answers4

2

The problem is: input() returns a string, so you have to convert it result to integer. Function random.randint(1,10) returns an integer number, so without converting input() function result to integer, condition y != x always will be True.

import random

x = random.randint(1,10)
y = None
lst = []

while y != x:
    y = int(input('Your number:'))
    lst.append(y)        
print(lst)
Dawid Rutkowski
  • 410
  • 3
  • 8
1

You need to convert your x variable into a string before comparing it to the y variable in the While loop. This works: (only change was adding the str() conversion to the x variable.)

import random

x = str(random.randint(1,10))
y = []
lst = []

while y != x:
    y = input('Your number:')
    lst.append(y)
    pass
print(lst)
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
pillemer
  • 11
  • 3
0

In your code x is an integer while y is a string. You need to convert your input (which is y) from the user to int. Simply do this to the code:

import random

x = random.randint(1,10)
y = []
lst = []

while y != x:
    y = int(input('Your number:'))
    lst.append(y)
    pass
print(lst)
RishiC
  • 768
  • 1
  • 10
  • 34
0

First thing, you are comparing type:int and type:str. "==" will always false. Here is how i did your program

import random

x = random.randint(1,10)
y = []
lst = []

while True:
  y = int(input('Your number:'))
  print(x)
  print(y)

 if(x==y):
   break
 else :
  lst.append(y) 
print(lst)
parlad
  • 1,143
  • 4
  • 23
  • 42