[英]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.输入
7
、 2
、 bob
、 10
和4
并匹配下面的 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
来存储值,然后您可以使用min
和max
方法:
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.