计算用户输入的最小值和最大值

时间:2013-09-18 02:26:28

标签: python-3.x max min

n = int(input("How many items?"))
for i in range(n-1):
    price = float(input("Price for the item? ")
    if price < ?:
        min_price = price
    if price > ?:
        max_price = price
    print("The least price is", min_price)
    print("The greatest price is", max_price) 

尝试查找用户输入的最低和最高价格。

3 个答案:

答案 0 :(得分:1)

n = int(input("How many items?"))
min_price = None
max_price = None
for i in range(n-1):
    price = float(input("Price for the item? "))
    if min_price is None:
        min_price = price
        max_price = price
    elif price < min_price:
        min_price = price
    elif price > max_price:
        max_price = price
    print("The least price is", min_price)
    print("The greatest price is", max_price) 

答案 1 :(得分:0)

虽然Paul Becotte的答案可能效果很好,但这是一个较小的实现,使用python的内置minmax函数。要初始化值,您可以解析inf(无穷大),因此min_price初始值将始终大于您输入的第一个值...

min_price = float("inf")
max_price = float("-inf")

for i in range(n-1):
    price = float(intput("Price for the item? "))
    min_price = min(min_price, price)
    max_price = max(max_price, price)
    # ...

答案 2 :(得分:0)

你可以用不同的方法做,给出float('inf')None的最小和最大变量值,或以第三种方式从用户获取变量并将其放入min和max

n=input('how many items?')
min=float('+inf')
max=float('-inf')
for i in range(n):
    price=input ('price for the item?')
    if price<min:
            min=price
    if price>max:
            max=price
print("the minimum is ",min)
print("the maximum is ",max)

另一种方法:

n=input('how many items?')
min=None
max=None
for i in range(n):
    price=input ('price for the item?')
    if min is None:
        min=price;
        max=price;
    elif price<min:
        min=price
    elif price>max:
        max=price
print("the minimum is ",min)
print("the maximum is ",max)

另一种方法:

n=input('how many items?')
price=input ('price for the item?')
min=max=price;
for i in range(n-1):
    price=input ('price for the item?')
    if price<min:
         min=price
    if price>max:
         max=price
print("the minimum is ",min)
print("the maximum is ",max)

另请注意,当您放置范围(n-1)时,要询问的项目小于用户想要输入的项目数。因此,只有在价格超出循环范围的情况下,范围为(n-1),在所有其他情况下,范围为(n)