Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python简介:如何使用while循环获得最大值?_Python - Fatal编程技术网

Python简介:如何使用while循环获得最大值?

Python简介:如何使用while循环获得最大值?,python,Python,编写一个程序,提示用户输入1到20之间的数字,直到遇到数字20为止。不包括20,计算最大值 有人能帮我写个代码吗 inp = 0 x = 9999 while inp != 20: inp = int(input("Please enter a number from 1 to 20 (20 to stop): ")) print(inp) if inp != 20: print("the maximum value i

编写一个程序,提示用户输入1到20之间的数字,直到遇到数字20为止。不包括20,计算最大值

有人能帮我写个代码吗

inp = 0
x = 9999
while inp != 20:
    inp = int(input("Please enter a number from 1 to 20 (20 to stop): "))
    print(inp)
    if inp != 20:          

print("the maximum value is", inp)

我被卡住了

您的思路是正确的,但是您需要一个单独的变量来容纳最大的数字——您不能为此重用输入变量

另外,由于您已经在检查循环中的输入是否为20,因此在while条件下也检查相同的内容是重复的。只需使用
,而使用True

# keep track of the largest number entered
largest = 0

# loop forever
while True:
    # ask for input
    inp = int(input("Please enter a number from 1 to 20 (20 to stop): "))

    # if 20 was entered, quit the loop
    if inp == 20:
        break

    # if the input is larger than the largest number entered so far, save it as the largest
    if inp > largest:
        largest = inp

print("The largest number was", largest)

一个相当简单的解决方案

prompt = "Please enter a number from 1 to 20 (20 to stop): "

# stores the numbers that were inputted
numbers = []

number = int(input(prompt))

# keeps asking for input as long as number inputted, is not 20
while number != 20:
    numbers.append(number)
    number = int(input(prompt))

# gets the max value from the list, and prints it
print("the maximum value is", max(numbers))

拥有哨兵是iter的一个很好的用例:

max(iter(lambda: int(input("Please enter a number from 1 to 20 (20 to stop): ")), 20))
演示:

>>> max(iter(lambda: int(input("Please enter a number from 1 to 20 (20 to stop): ")), 20))
Please enter a number from 1 to 20 (20 to stop): 4
Please enter a number from 1 to 20 (20 to stop): 12
Please enter a number from 1 to 20 (20 to stop): 7
Please enter a number from 1 to 20 (20 to stop): 20
12