从用户那里获取电话号码打印最大和最小(不使用内置功能) [英] get numbers from user & print maximum and minimum (w/o using built-in function)
问题描述
我正在审查一个执行以下操作的python练习:
I'm reviewing a python exercise which does the following :
-
读取直到完成"的数字列表 输入.
reads list of numbers til "done" gets entered.
输入完成"时,打印 最大和最小 数字.
When "done" is inputted, print largest and smallest of the numbers.
并且应该为,而不能直接 使用内置函数max() 和min().
And it should be without directly using the built-in functions, max() and min().
这是我的消息来源. Traceback说:'float'对象不可迭代"
Here is my source. Traceback says, "'float' object is not iterable"
我认为我的错误是由于未正确使用列表来计算最小和最大. 任何提示和帮助将不胜感激!
I think my errors are coming from not using the list properly to calculate smallest and largest. Any tips and help will be greatly appreciated!
while True:
inp = raw_input('Enter a number: ')
if inp == 'done' :
break
try:
num = float(inp)
except:
print 'Invalid input'
continue
numbers = list(num)
minimum = None
maximum = None
for num in numbers :
if minimum == None or num < minimum :
minimum = num
for num in numbers :
if maximum == None or maximum < num :
maximum = num
print 'Maximum:', maximum
print 'Minimum:', minimum
谢谢!
推荐答案
您不需要列表.您只需要随时跟踪当前的最小值和最大值.
You shouldn't need a list. You should only need to keep track of the current minimum and maximum as you go.
minimum = None
maximum = None
while True:
inp = raw_input('Enter a number: ')
if inp == 'done':
break
try:
num = float(inp)
except:
print 'Invalid input'
continue
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print 'Maximum:', maximum
print 'Minimum:', minimum
这篇关于从用户那里获取电话号码打印最大和最小(不使用内置功能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!