简体   繁体   English

最大和最小数字使用输入while循环python

[英]largest and smallest number using input while loop python

This is my try to write a program that repeatedly prompts a user for integer numbers until the user enters done .这是我尝试编写一个程序,该程序反复提示用户输入 integer 数字,直到用户输入done Once done is entered, print out the largest and smallest of the numbers.输入done后,打印出最大和最小的数字。 If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.如果用户输入的不是有效数字,请使用try/except捕获它并发出适当的消息并忽略该数字。 Enter 7 , 2 , bob , 10 and 4 and match the output below.输入72bob104并匹配下面的 output。 But it's false.但这是错误的。 I need some help can someone explain my fault.我需要一些帮助,有人可以解释我的错。

largest = 0
smallest = 0



while True:
    num = input("Enter a number: ")
    if num =="done": break
    try:
           fnum = float(num)
    except:
        print("Invalid input")
        continue

    if largest == 0 or num >= largest: largest = num
    else: largest= largest
    if smallest == 0 or num <= smallest: smallest = num
    else: smallest= smallest

print("Maximum is", largest)
print("Minimum is", smallest)

Instead, why don't you a list to store the values, then you can use the min and max methods:相反,您为什么不使用list来存储值,然后您可以使用minmax方法:

nums = []

while True:
    num = input("Enter a number: ")
    if num == "done" : break
    try:
        fnum = float(num)

    except:
        print("Invalid input")
        continue

    nums.append(fnum)

largest = max(nums)
smallest = min(nums)

print("Maximum is", largest)
print("Minimum is", smallest)

You should be using fnum in those if statements, not num .您应该在那些 if 语句中使用fnum ,而不是num

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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