简体   繁体   中英

I'm really new to Python, and I was wondering why my “Else:” isn't working

import random

number = 50
guess = raw_input("Try to guess my number...")

while guess!=number:
if guess>number:
    print "Lower"
elif guess==number:
    print "Correct, you win!"
else:
    print "Higher"
guess = raw_input("Try again...")

I'm really new, and I'm wondering why it won't display "Higher" when the number I input is less than the number, plus, how can I make the number random, since randrange(1,100) won't work

It's not working because raw_input returns a string.

"50" == 50 # False!

You will need to ensure you are checking for equality of the same types. Try converting to an int first:

int(raw_input("Try to guess my number..."))

Of course this will throw an exception if you try to convert a non-numeric string to an int, so you will need some error-handling as well:

valid_num = False

while not valid_num:
    guess = raw_input()
    try:
        guess_num = int(guess)
        valid_num = True
    except ValueError:
        print "Please enter a valid number"


while guess!=number:
    if guess>number:
        print "Lower"
    elif guess==number:
        print "Correct, you win!"
    else:
        print "Higher"

First of all when you use raw_input("Try to guess my number...") ir returns a string and str!=int in any case so you were running an infinite while guess!=number: loop, as the condition would always hold true for comparison of a string and an integer.

Another thing was contradicting statements of while and elif , when you are running a while condition with while guess!=number: then how can you expect this elif guess==number: statement to run inside the while statement , So the answer would be handle this case outside the while loop.

import random

number = 50
guess = int(raw_input("Try to guess my number..."))

while guess!=number:
    if guess>number:
        print "Lower"
    else:
        print "Higher"
    guess = int(raw_input("Try again..."))

print "Correct, you win!"

raw_input returns a string. You will want to convert that to an int for your comparison:

guess = int(raw_input("Try to guess my number..."))

a str will never == an int

About your randrange problem:

You should use random.randint(a,b) instead. It chooses a random integer between the number a and b (exclusive, I think.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM