那时候你应该怎么做?

2024-04-28 15:26:03 发布

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

我正在努力学习Pythonpython.org网站你知道吗

我找到了这个密码,我不知道它是什么意思。我跑了,但什么也没发生。你知道吗

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

那么,这个代码是做什么的?你知道吗


Tags: inorgtrue密码returnif网站def
2条回答
# you're definition a method `ask_ok` which takes `prompt` as a required argument
# and the rest as optional arguments with default values
def ask_ok(prompt, retries=4, reminder='Please try again!'):

    # while (condition) starts a perpetual loop, broken with control flow
    # statements like `return` or `break` or errors raised.
    while True:
        ok = input(prompt) # ask for user input after displaying `prompt`
        if ok in ('y', 'ye', 'yes'): # checking if the input value is in a tuple
            return True # this returns a Boolean value True and breaks out of the method
        if ok in ('n', 'no', 'nop', 'nope'): # see above
            return False # see above

        # you're iterating for number of times input will be asked
        # if input is in neither tuple; you could use `retries -= 1` as well
        retries = retries - 1 

        # if you're out of retries, you raise an error and break out of the method
        if retries < 0:
            raise ValueError('invalid user response')
        # this prints the reminder if the earlier conditions aren't met
        # and till you're out of retries
        print(reminder)

没有输出,因为您定义了一个方法,但没有调用它。如果在传递一些参数的同时,使用方法调用跟踪它,它将返回一个布尔值或打印提醒,直到重试次数结束(此时它将引发ValueError)。你知道吗

>>ask_ok("Enter Input: ")
# Enter Input: no
# False

>>ask_ok("Enter your Input: ")
# Enter your Input: y
# True

>>ask_ok("Input: ", 2, "Try Again")
# Input: FIFA
# Input: World
# Input: Cup
# Try Again

这里定义的函数是ask_ok(),它接受输入提示。 因此,如下所示,您可以在任何pythonide中运行此代码。你知道吗

第1行将调用函数并提示=“Doyouwant to continue”(您可以在此处编写的任何消息)。函数被调用后,它进入循环,循环将检查输入是否为('y','ye','yes'),然后它将重新运行TRUE 或者 如果输入为'n'、'no'、'nop'、'nope',则返回false 但是 如果输入不是('y'、'ye'、'yes'、'n'、'no'、'nop'、'nope')值,则循环将继续并打印reminder=“请重试!”你知道吗

如果你能看到循环

 retries = retries - 1  # reties =4
    if retries < 0: 
        raise ValueError('invalid user response') 

直到5次循环将允许您输入第6次,它将抛出异常ValueError('无效用户响应')。你知道吗

循环最多持续5次)

def ask_ok(prompt, retries=4, reminder='Please try again!'):#funcDefintion
while True: 
    ok = input(prompt) 
    if ok in ('y', 'ye', 'yes'): 
        return True 
    if ok in ('n', 'no', 'nop', 'nope'): 
        return False 

    retries = retries - 1 
    if retries < 0: 
        raise ValueError('invalid user response') 
    print(reminder)

询问#确定(“是否继续”)#第1行

为了练习,您可以更改函数定义中的值。 我建议您先学习一些基础知识,比如if条件、循环、异常、函数,然后继续学习。你知道吗

相关问题 更多 >