替代Goto,Python中的Label? [英] Alternative to Goto, Label in Python?
问题描述
我知道我无法使用Goto,而且我知道Goto并非答案.我读过类似的问题,但我只是想不出办法解决问题.
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"`
你会做什么?
推荐答案
有很多方法可以做到这一点,但是通常您会希望使用循环,并且您可能希望探索break
和continue
.这是一种可能的解决方案:
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
跳转到循环的下一个迭代,并且break
完全终止循环.
continue
jumps to the next iteration of the loop, and break
terminates the loop altogether.
(还要注意,我将int(raw_input(...))
包装在try/except中,以处理用户未输入整数的情况.在您的代码中,不输入整数只会导致异常.我将0更改为在randint
调用中也设为1,因为根据您要打印的文本,您打算在1到100之间选择,而不是0到100.)
(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.)
这篇关于替代Goto,Python中的Label?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!