这是任务
编写一个程序,反复提示用户输入整数,直到用户输入'done'。一旦输入"done",打印出最大和最小的数字。如果用户输入的不是一个有效的数字,用try/except捕获它,并输出一个适当的消息,忽略数字
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
intnum = int(num)
except ValueError:
print('Invalid')
continue
for size in (num):
if largest is None:
largest = size
if smallest is None:
smallest = size
if largest < size:
largest = size
if smallest > size:
smallest = (size)
print("Maximum is", largest)
print('Minimum is', smallest)type here
当我使用一位数时,代码可以工作,但如果我使用像10这样的双位数,那么它会打印0作为最小的数字
例如,如果我输入1,3,10,2,6, done
即使最小的数字是1,它也会打印:
maximum is 6
minimum is 0
我正在努力弄清楚,所以任何帮助都会很感激,谢谢!
你几乎是对的,你可以删除for循环,只是比较最大值和最小值与intnum
变量。代码应该是这样的:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
intnum = int(num)
except ValueError:
print('Invalid')
continue
if largest is None:
largest = intnum
if smallest is None:
smallest = intnum
if largest < intnum:
largest = intnum
if smallest > intnum:
smallest = (intnum)
print("Maximum is", largest)
print('Minimum is', smallest)
您可以通过应用反向循环来减少if语句。
从初始化最小值(float('-inf'))
开始,初始化最小值(float('inf'))
开始
和检查用户输入,如果number>largest
修改largest
。number<smallest
modifysmallest
一个edgecase假设用户没有直接输入任何数字,那么它将打印inf
-inf
,这是不正确的。所以把它们转换成no minimum
no maximum
代码:
largest = float('-inf')
smallest = float('inf')
while True:
num = input("Enter a number: ")
if num.lower() == "done": #Works for Done also..
break
try:
intnum = int(num)
except ValueError:
print('Invalid')
continue
if intnum>largest:
largest=intnum
if intnum<smallest:
smallest = intnum
print("Maximum is", largest if largest!=float('-inf') else 'No maximum')
print('Minimum is', smallest if smallest!=float('inf') else 'No minimum')
你也可以把if
都放在try语句里面…!
输出:
当用户不输入任何数字
Enter a number: done
Maximum is No maximum
Minimum is No minimum
用户只输入一个数字
Enter a number: 4
Enter a number: done
Maximum is 4
Minimum is 4
用户输入多于1个数字时的正常情况
Enter a number: 2
Enter a number: 7
Enter a number: 1
Enter a number: 3
Enter a number: 8
Enter a number: 9
Enter a number: done
Maximum is 9
Minimum is 1