Python Forum

Full Version: While loop keeps looping
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

Really new to Python, and doing some coding to get use/understand it. I am working on a program, that creates a random number and the user needs to guess that random number. However the code I have done so far doesn't seem to work. Fo some reason the code keeps looping, even though I enter the correct number:

import random
attempts = 0
guess = 0
number = random.sample(range( 1,100),1)
print("Welcome to the random number guessing game!")
print(number)
while guess != number:
  guess = int(input("Please enter a number to guess: "))
  attempts +=1
else:
  print("Well done, you guesed the number")
Any idea why would be very much appreciated.

Thanks
random.sample will return list, in your case - list with just one element. You are comparing list with int - never True.
You want to use random.randint(1, 99) - https://docs.python.org/3/library/random...om.randint
or random.choice(range(1, 100))
I solved it. I realised that random.sample(range() was a list of numbers, which I was trying to compare to an integer. Instead I used
number = random.randint( 0,100)
, which solved my problem
note that randint(0, 100) will include 0 and 100, while your initial code is [1, 99], i.e. range will start from 1 and will not include 100