那时我该怎么办?

时间:2019-11-30 08:52:05

标签: python python-3.x

我正在尝试在python.org上学习Python

我找到了这段代码,我不知道这意味着什么。我运行了它,但是什么也没发生。

//Question 4

int num4 = MyConsole.readInt("Please enter a Number(integer) of people which you want me to test what is the safe spot in a Josephus problem: ");
int reducer = 1;
int c = 1;
while (num4 > reducer+1){
    num4 -= reducer;
    reducer += c++;
}
num4 = 1 + (num4-1)*2;
MyConsole.printPrompt("The Safe spot for the entered number is " + Integer.toString(num4));

那么,这段代码是做什么的?

2 个答案:

答案 0 :(得分:0)

此处定义了ask_ok()函数,该函数接受输入提示。 因此,如下所示,您可以在您拥有的任何python IDE中运行此代码。

第1行将使用提示=“您是否要继续”(您可以在此处写的任何消息)来调用该函数。调用该函数后,它将进入循环,该循环将检查输入是否为('y','ye','yes'),然后将重新运行 TRUE 要么 如果输入为“ n”,“否”,“ nop”,“ nope”,则它将返回false 但 如果输入的内容不是('y','ye','yes','n','no','nop','nope')值以外的其他值,则循环将继续并打印提醒[=“,请重试! “

如果您会看到循环

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

直到5次循环将允许您第六次输入输入,它将抛出异常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

为了练习,您可以更改函数定义中的值。 我建议先了解一下条件,循环,异常,函数等基础知识,然后再继续学习会更好。

答案 1 :(得分:-1)

# 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