首页 > 解决方案 > 我在代码中遇到了一些 int 和 str 转换问题

问题描述

我需要以下输出:下面的示例输出(红色文本代表用户输入):

请输入豆价:5
请输入豆价:17
请输入豆价:23
请输入豆价:max
最高豆价为 23
请输入豆价:min
最低豆价为 5
请输入bean price: mean
平均豆价为 15

我的代码是:

    li = []
    price = '0'
    val = True
    while val:
       price = int(input('Please input the bean price: ')
        if price!='max' and price!='min' and price!= 'mean':
           li.append(price)
        elif price=='max':
           max_value = li[0]
           for x in li:
              if int(x) > max_value:
                  max_value = int(x)
           print(f'The max bean price is {max_value}')

请问有人可以提供解决方案吗?

标签: pythonpython-3.x

解决方案


您可以使用内置minmax. 您应该将 移动int()到将数字添加到列表的行:li.append(int(price))。此外,.lower()将帮助您消除大小写敏感性。该if声明将有助于防止错误。

例如:如果用户max,min,mean在第一个语句中输入,则列表中没有任何内容。所以if...else检查 list 是否不为空或[].

li = []
price = '0'
val = True
li = []
price = '0'
val = True
while val:
    price = input('Please input the bean price: ')
    if price.lower()!='max' and price.lower()!='min' and price.lower()!= 'mean':
       li.append(int(price))
    elif price.lower()=='max':
       if li==[]:
          print("There is no item in the list.")
       else:
          print(f'The max bean price is {max(li)}')
    elif price.lower()=='min':
       if li==[]:
          print("There is no item in the list.")
       else:
          print(f'The min bean price is {min(li)}')
    elif price.lower()=='mean':
       if li==[]:
          print("There is no item in the list.")
       else:
          print(f'The mean bean price is {sum(li)/len(li)}')

输出:

Please input the bean price: 5
Please input the bean price: 17
Please input the bean price: 23
Please input the bean price: max
The max bean price is 23
Please input the bean price: min
The min bean price is 5
Please input the bean price: mean
The mean bean price is 15.0

推荐阅读