Ubuntu 13.04 の python 2.7 で書いている小さな max_min プログラムがあります。このコードは、2 つの条件で中断する無限ループ内でユーザー入力を受け取ります。9 より大きい数値を入力すると、プログラムが間違った結果を返すことに気付きました。私がやりたいことは、ユーザーが数字を入力するたびに、その数字を以前の数字と比較し、ユーザーから入力された最大数と最小数を取得することです。
例えば:
Please enter a number:
10
Max: 1, Min: 0, Count: 1
Max が 1 ではなく 10 であるべき場合。ここに私のコードがあります:
count = 0
largest = None
smallest = None
while True:
inp = raw_input('Please enter a number: ')
# Kills the program
if inp == 'done' : break
if len(inp) < 1 : break
# Gets the work done
try:
num = float(inp)
except:
print 'Invalid input, please enter a number'
continue
# The numbers for count, largest and smallest
count = count + 1
# Gets largest number
for i in inp:
if largest is None or i > largest:
largest = i
print 'Largest',largest
# Gets smallest number
for i in inp:
if smallest is None or i < smallest:
smallest = i
print 'Smallest', smallest
print 'Count:', count, 'Largest:', largest, 'Smallest:', smallest
困惑した。