一个程序,反复提示用户输入整数,直到用户输入“完成”为止。输入“完成”后,它将打印最大和最小的数字。如果用户输入的数字不是有效数字,则它将使用try / except进行捕获,并显示“ Invlid input”,并忽略该数字
largest=0
smallest=0
while True:
num=input("Enter a number: ")
try:
n=int(num)
if(n>=largest):
largest=n
elif(n<=smallest):
smallest=n
else:
smallest=n
largest=n
except:
if(num=='done'):
break
else:
print("Invalid input")
print("Maximum is ",largest)
print("Minimum is ",smallest)
答案 0 :(得分:0)
您有缩进错误和冒号。
正确的代码:
largest = 0
smallest = 0
while True:
num = input("Enter a number: ")
try:
n = int(num)
if n >= largest:
largest = n
elif n <= smallest:
smallest = n
else:
smallest = n
largest = n
except:
if num == 'done':
break
else:
print("Invalid input")
print("Maximum is ",largest)
print("Minimum is ",smallest)
答案 1 :(得分:-1)
您的代码几乎不需要更新:
:
固定代码:
import sys
largest=0
smallest=sys.maxsize
while True:
num=input("Enter a number: ")
try:
n=int(num)
if(n>=largest):
largest=n
if(n<=smallest):
smallest=n
except:
if(num=='done'):
break
else:
print("Invalid input")
print("Maximum is ",largest)
print("Minimum is ",smallest)
不过,我还是建议您阅读基本的python教程。