问题
I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.
So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:
x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
What would you do?
回答1:
There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break
and continue
. Here's one possible solution:
import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
continue
jumps to the next iteration of the loop, and break
terminates the loop altogether.
(Also note that I wrapped int(raw_input(...))
in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint
call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)
回答2:
Python does not support goto
or anything equivalent.
You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the control flow page for more information.
x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
In many other cases, you'll want to use a function to handle the logic you want to use a goto statement for.
回答3:
You can use infinite loop, and also explicit break if necessary.
x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break
来源:https://stackoverflow.com/questions/38494761/alternative-to-goto-label-in-python