[英]What should I do at that point in Python?
我正在尝试在 python.org 上学习 Python
我找到了这段代码,我不知道它是什么意思。 我运行它,但什么也没发生。
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)
那么,这段代码有什么作用呢?
这里定义了 ask_ok() 函数,它接受输入prompt 。 因此,如下所示,您可以在您拥有的任何 Python IDE 中运行此代码。
第 1 行将调用带有 prompt = "do you want to continue" 的函数(您可以在此处写入任何消息)。 函数被调用后它进入循环,它将检查输入是否为 ('y', 'ye', 'yes') 然后它将重新运行TRUE OR 如果输入为 'n', 'no', 'nop', 'nope' 然后它会返回 false 但是如果输入不是 ('y', 'ye', 'yes', 'n', 'no', 'nop', 'nope') 值然后循环将继续并打印提醒="请再试一次!"
如果你会看到循环
retries = retries - 1 # reties =4
if retries < 0:
raise ValueError('invalid user response')
直到 5 次循环将允许您输入第 6 次输入,它将抛出异常 ValueError('invalid user response') 。
循环将最多持续 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)
ask_ok("你要继续吗") #line 1
为了练习,您可以更改函数定义中的值。 我建议先学习基础知识,比如 if 条件、循环、异常、函数,然后你会更好地继续下去。
# 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.