简体   繁体   中英

I want to make an infinite input and end it when user input 0. After that I want to find the maximum number

I tried this code

while True:
    y = input("")
    if y== '0':
        break

max_number = max(y)
print(max_number)

Could just use max on an iterator over the inputs:

print(max(iter(input, '0'), key=int))

Should be like this

ys = []

while True:
    y = input("")
    if y== '0':
        break
    else:
        ys.append(y)

max_number = max(ys)
print(max_number)

The problem on your code is that you're treating the input as a string . In order to calculate the maximum number, you can convert the input to an integer (or float if you wish), then use the max() function.

ys = []
while True:
    y = int(input())
    if y == 0:
        break
    else:
        ys.append(y)

Note that the first input can be 0, so it will raise an error if you try to calculate the maximum value of an empty list. You can add a conditional to avoid that.

max_number = max(ys) if ys else None
print(max_number)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM