-1
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) 

试图找到用户输入的最低和最高价格。

4

3 回答 3

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) 
于 2013-09-18T02:38:52.353 回答
0

虽然 Paul Becotte 的回答可能效果很好,但这里有一个较小的实现,使用 python 的内置函数minmax函数。要初始化值,您可以解析inf(infinity),因此 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)
    # ...
于 2013-09-18T02:51:01.860 回答
0

你可以用不同的方法来做,给最小值和最大值变量值,float('inf')或者None以第三种方式从用户那里获取变量并将它放在最小值和最大值中

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)

另请注意,当您输入 range(n-1) 时,将询问的项目少于用户想要输入的项目数。所以只有在你让价格超出循环范围的情况下,范围是(n-1),在所有其他情况下,范围是(n)

于 2013-09-18T03:50:07.833 回答