Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop keeps looping
#1
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
Reply
#2
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))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  "while" loop is looping back too early mangurian 1 1,286 Jan-28-2022, 09:15 AM
Last Post: ibreeden
  Nested for loop not looping puttingwordstogether 0 1,722 Jun-16-2020, 11:15 PM
Last Post: puttingwordstogether
  while loop will not stop looping TheTechRobo 5 3,743 Apr-20-2020, 01:47 PM
Last Post: TheTechRobo
  'Looping' does not work out within a 'for Loop' Placebo 4 3,356 Sep-15-2018, 08:19 PM
Last Post: Placebo
  For looping over a list, editing the list from inside the loop? Krookroo 3 3,961 Sep-04-2017, 05:08 PM
Last Post: Krookroo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020