如何记录Python中输入的最高和最低数字?

时间:2014-10-27 19:02:19

标签: python python-2.7

我没有意识到我的错误是什么,这就是我现在所取得的成就:

x = 1
e = 0
while x <= 50:
    print "Please enter a number (from 1 to 9):"
    b = float(raw_input())
    asd = 0
    if asd == 0:
        h = b
        l = b        
        asd = 1
    if b < l:
        l = b
    elif b > h:
        h = b
    if 1 <= b or b <= 9:
        x = x * b
        print x
    else:
        print "Number is too large or too small."
    e = e + 1

print "You have reached a value over 50."
print "Highest number entered:", h
print "Lowest number entered:", l
print "Entered numbers:", e

这是节目的输出:

Please enter a number (from 1 to 9):
5
5.0
Please enter a number (from 1 to 9):
4
20.0
Please enter a number (from 1 to 9):
5
100.0
You have reached a value over 50.
Highest number entered: 5.0
Lowest number entered: 5.0
Entered numbers: 3

为什么程序给我5而不是4作为输入的最低数字,我该如何纠正?

3 个答案:

答案 0 :(得分:1)

你不断重复asd每次迭代,你需要在循环外设置变量,我会使用一个列表,这将使你能够得到最小/最大和有效输入的数量:

nums = [] # hold all nums outside the loop
limit = 1 
while 50 >= limit:
    num = float(raw_input("Please enter a number (from 1 to 9)")
    if 1 <= num <= 9: 
        limit *= num
        nums.append(num) # add all to list
    else:
        print "Number is too large or too small."

print "You have reached a value over 50."
print "Highest number entered:", max(nums) 
print "Lowest number entered:", min(nums)
print "Entered numbers:", len(nums)

答案 1 :(得分:0)

每次进行循环时,都会将asd设置为0,导致其下方的if语句每次都执行,因此您总是盲目地更新{{1}使用用户刚输入的值,您将其命名为l

答案 2 :(得分:0)

只是为了好玩:)

def get_float_input(msg="Enter a Number:"):
    while True:
       try:
          return float(raw_input(msg))
       except ValueError:
           print "Invalid Input Please Enter A Float!"

from itertools import takewhile
my_list = sorted(takewhile(lambda val:val < 50,iter(get_float_input,"Y")))
print "You Have Entered A # Greater than 50"
print "Min:",my_list[0]
print "Max:",my_list[-1]
print "Entered %d Numbers"%len(my_list)