Python:有没有办法告诉程序回去?

2024-05-23 21:36:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在想,有没有一种方法可以编写一行代码,告诉python返回到代码中的其他地方?你知道吗

像这样:

choose = int(input())
if choose == 1:
    print(“Hi.”)
else:
*replay line1*

像这样基本的东西?你知道吗

我并不特别想使用一个更大的循环,但我可以如果可能的话?你知道吗

有什么想法吗,我对python真的很陌生?你知道吗


Tags: 方法代码inputreplayif地方hielse
2条回答

这有点奇怪,它适用于期望值为布尔值(仅两个期望值)的情况,这些布尔值不是0就是1,而不是其他任意字符串,aa和您不想存储输入的情况。你知道吗

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))

对于更模糊的情况

choose = 0
while (choose != 1)
    choose = int(input())
    if choose == 1:
        print(“Hi.”)

相关问题 更多 >