在 python 中创建确认函数

lui*_*jie 3 python function python-2.7 python-3.x

def confirm_choice():
    confirm = input("[c]Confirm or [v]Void: ")
    if confirm != 'c' and confirm != 'v':
        print("\n Invalid Option. Please Enter a Valid Option.")
        confirm_choice() 
    print (confirm)
    return confirm
Run Code Online (Sandbox Code Playgroud)

例如,当键入无效输入时,字母“k”后跟有效输入“c”,该函数将打印输入“c”和“k”

输出:

c
k
Run Code Online (Sandbox Code Playgroud)

如何更改上述程序,使其仅返回“c”或“v”,并在输入无效时重复该函数。

tza*_*man 7

不需要递归;while为此使用循环更容易:

while True:
    confirm = input('[c]Confirm or [v]Void: ')
    if confirm.strip().lower() in ('c', 'v'):
        return confirm
    print("\n Invalid Option. Please Enter a Valid Option.")
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

7406 次

最近记录:

2 年,11 月 前