编写一个程序,反复提示用户输入整数,直到用户输入“完成”。输入“完成”后,打印出最大和最小的数字。如果用户输入除有效数字以外的任何内容,请使用try / except捕获它并输出相应的消息并忽略该数字。
到目前为止我有这个但是我很困惑如何创建比较最大值的方法?我是编程新手,我只是寻求帮助。我也可以在尝试之前包括try和except块吗?然后是除了错误的错误
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
print num
print "Maximum", largest
答案 0 :(得分:5)
nums = []
while True:
n = raw_input("Enter a number: ")
if n == "done":
break
try:
nums.append(int(n))
except ValueError:
print "Invalid input"
print "Min: %d" % min(nums)
print "Max: %d" % max(nums)
答案 1 :(得分:2)
largest = None
smallest = None
first_number = True
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
try:
num = int(num)
if first_number:
largest = num
smallest = num
first_number = False
else:
largest = max(largest, num)
smallest = min(smallest, num)
except Exception, e:
print "Not Valid Input!!!"
continue
print "Maximum", largest
print "Minimum", smallest
答案 2 :(得分:0)
numbers =[]
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
else:
numbers.append(num)
print max(numbers)
print min(numbers)
因此,逻辑是将数字添加到列表中并使用函数max和min。您可以编写代码来自己处理异常。
答案 3 :(得分:0)
largest = None
smallest = None
while True:
num = raw_input("Enter a number: ")
if num == "done": break
if len(num) < 1 : break
try:
num=int(num)
except:
print "Invalid input"
continue
if num is smallest:
smallest = num
if num > largest:
largest = num
print "Maximum is ", largest
print "Minimum is ", smallest
答案 4 :(得分:0)
您可以通过对原始程序进行非常小的修改来完成此操作:只需记下您认为最小和最大数字的标签。
largest = None
smallest = None
while True:
string = raw_input("Enter a number: ")
if string == "done":
break
try:
num = int(string)
except ValueError:
print "Not a number"
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
答案 5 :(得分:0)
largest = None
smallest = None
while True:
num = raw_input('Enter a number: ')
if num == 'done':
print 'Maximum is %s' % largest
print 'Minimum is %s' % smallest
break
try:
num = int(num)
if smallest is None or num <= smallest:
smallest = num
if largest is None or num >= largest:
largest = num
except:
print 'Invalid input'
答案 6 :(得分:0)
我也是python的初学者,我在Charles Russell Severance的“ Python for Everyone”中注意到了这个问题。我的答案在下面。
prompt = 'Enter the number: '
initial_value = 0.0
while True:
thing = input(prompt)
if thing == 'done':
break
try:
num = float(thing)
except:
print('Invalid input')
continue
num = float(thing)
if num > initial_value:
max = num
min = initial_value
else:
min = num
print('Max', max)
print('Min', min)
答案 7 :(得分:-1)
通过将num
分配给单个值,您将在循环的每次迭代中覆盖它。改为使用列表。
num = []
finish = "n"
while finish.lower() == "n"
try:
num.append(int(raw_input("Enter a number: ")))
except ValueError:
print "Not a number"
finish = raw_input("Would you like to add another number? (y/n): ")
print max(num)