Python Forum
please help with while loops
Thread Rating:
  • 2 Vote(s) - 2.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
please help with while loops
#1
i am trying to get a while loop to repeat in my number guessing game and i dont kn
import random



print ("this is the number guessing game")
x=int(input("What is the min number? "))
s=int(input("What is the max number? "))
num=random.randrange(x,s)
guesses= int(input("how many guesses? "))
i=0
while guesses>0 or guess!=num or i==1:
    guess =int(input("take a guess " ))
    if guess>num:
        print ("to high you have",guesses-1,"guesses left")
        guesses-=1
    elif guess<num:
        print ("to low.you have",guesses-1,"guesses remaning")
        guesses-=1
    else:
        print ("congrats you guessed the number")
        break
    if guesses==0:
        break
if guess!=num:
    print("you have not guessed the number.it was",num,)
else:
    print ("you have completed the game")
o=int(input("press 1 to play agin"))
if o==1:
    i+=1

how do i get it to work?? thanks for any help
ow what im doing wrong
Reply
#2
Hello,

onyour very first iteration, you check
guess != num
that condition is initially true because guess hasn't been defined yet,
and I don't think that's what you want to check either.
I think you want to say
guess == num
To make it work you need to define guess before the loop:

guess = None
while ...
If done this way, you don't need the breaks, the next iteration will do it for you

Next, you test i == 1 which will never be true since it's never incremented within the while loop
Not sure what your intent was here, it's not needed, unless you want to assure at least one
iteration of the loop. If this is the case, you have to increment i at the bottom of the loop, otherwise
get rid of it.


Larz60+
Reply
#3
while True:
    # ...
    # ...
    # ...
    o=int(input("press 1 to play again: "))
    if o!=1:
        break
Reply
#4
There's a few things that look odd, but it looks like it should work.  What error are you getting?
Reply
#5
@nilamo: the program of the OP runs well, but only once, because the while-loop is wrong.
Reply
#6
Maybe put it in a function and then call it when the user enters '1' :)?
this seems to me like very difficult to achieve with a while loop..
Reply
#7
(Nov-17-2016, 12:04 PM)heiner55 Wrote: @nilamo: the program of the OP runs well, but only once, because the while-loop is wrong.

Right.  Which means there isn't an error message.  Which should make them think about what they really mean when they say "it doesn't work".
Reply


Forum Jump:

User Panel Messages

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