查找用户输入的最小值和最大值

时间:2016-10-14 01:16:55

标签: python python-3.x

我正在学习Python,并且在试图找出用户数输入的最小值和最大值时,我似乎无法弄明白。

count = 0
x = []
while(True):
    x = input('Enter a Number: ')
    high = max(x)
    low = min(x)
    if(x.isdigit()):
        count += 1
    else:
        print("Your Highest Number is: " + high)
        print("Your Lowest Number is: " + low)
        break

3 个答案:

答案 0 :(得分:1)

将程序分解为可管理的小块,只需一个简单的函数即可获得数字

def input_number(prompt="Enter A Number:"):
    while True:
         try: return int(input(prompt))
         except ValueError:
             if not input: return None #user is done
             else: print("That's not an integer!")

然后编写一个函数来继续从用户那里获取数字,直到输入数字为止

def get_minmax_numbers(prompt="Enter A Number: "):
   maxN = None
   minN = None
   tmp = input_number(prompt)
   while tmp is not None: #keep asking until the user enters nothing
        maxN = tmp if maxN is None else max(tmp,maxN)
        minN = tmp if minN is None else min(tmp,minN)
        tmp = input_number(prompt) # get next number
   return minN, maxN

然后把它们放在一起

 print("Enter Nothing when you are finished!")
 min_and_max = get_numbers()
 print("You entered Min of {0} and Max of {1}".format(*min_and_max)

答案 1 :(得分:1)

inp=input("enter values seperated by space")
x=[int(x) for x in inp.split(" ")]
print (min(x))
print (max(x))

输出:

Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux

enter values seperated by space 20 1 55 90 44
1
90

答案 2 :(得分:0)

x是一个列表,要将项目附加到列表中,您必须在列表中调用append方法,而不是直接将项目分配给列表,这将覆盖列表那个项目。

代码:

count = 0
x = []
while(True):
    num = input('Enter a Number: ')
    if(num.isdigit()):
        x.append(int(num))
        count += 1
    elif(x):
        high = max(x)
        low = min(x)
        print("Your Highest Number is: " + str(high))
        print("Your Lowest Number is: " + str(low))
        break
    else:
        print("Please enter some numbers")
        break