简体   繁体   English

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

[英]Finding the Min and Max of User Inputs

I'm learning Python, and in trying to find out the min and max values of user number inputs, I can't seem to figure it out. 我正在学习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

break your program into small manageable chunks start with just a simple function to get the number 将您的程序分成几个易于管理的小块,从一个简单的函数开始

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!")

then write a function to continue getting numbers from the user until they are done entering numbers 然后编写一个函数以继续从用户那里获取数字,直到完成输入数字为止

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

then just put them together 然后把它们放在一起

 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)
inp=input("enter values seperated by space")
x=[int(x) for x in inp.split(" ")]
print (min(x))
print (max(x))

output: 输出:

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

x is a list, and to append an item to a list, you must call the append method on the list, rather than directly assigning an item to the list, which would override the list with that item. x是一个列表,并且要将项目追加到列表,必须在列表上调用append方法,而不是直接将项目分配给列表,这将用该项目覆盖列表。

Code: 码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM