你可以用不同的方法来做,给最小值和最大值变量值,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)