Python:有没有办法告诉程序回去?
问题描述:
我一直在想,是否有一种方法来编码一行,告诉python回到代码中的其他地方?Python:有没有办法告诉程序回去?
事情是这样的:
choose = int(input())
if choose == 1:
print(“Hi.”)
else:
*replay line1*
一些真正的基本这样呢?
我不是特别想要使用更大的循环,但如果可能,我可以吗?
任何想法,我真的是新的python?
答
choose = 0
while (choose != 1)
choose = int(input())
if choose == 1:
print(“Hi.”)
答
这是有点怪异一个,并且它适合于其中值预计布尔例(只有两个预期值),并且这些布尔值是0或1,而不是一些其他任意字符串,aaand您不希望存储输入的位置。
while int(input()) != 1:
# <logic for else>
pass # only put this if there's no logic for the else.
print("Hi!")
虽然有替代方法,例如:
choose = int(input())
while choose != 1:
<logic for else>
choose = int(input())
或者你可以创建一个函数:
def poll_input(string, expect, map_fn=str):
"""
Expect := list/tuple of comparable objects
map_fn := Function to map to input to make checks equal
"""
if isinstance(expect, str):
expect = (expect,)
initial = map_fn(input(string))
while initial not in expect:
initial = map_fn(input(string))
return initial
就这样用它作为这样的:
print("You picked %d!" % poll_input("choice ", (1, 2, 3), int))
对于更多不明确的情况
你必须使用循环。 – Li357
您要查找的术语是_control flow statement_。是的,Python有一些。正如@AndrewLi已经说过的,你可以使用一个循环来完成这个任务。 –
基本上,您正在寻找一种在现代编程语言中不再被广泛使用的控制结构:'GOTO'语句。这是因为[结构化编程](https://en.wikipedia.org/wiki/Structured_programming)的出现。你应该为此使用一个循环。 –