python - 我在代码中遇到了一些 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}')
请问有人可以提供解决方案吗?
解决方案
您可以使用内置min
和max
. 您应该将 移动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
推荐阅读
- android-workmanager - 单击按钮时,正在运行的工作管理器服务如何取消?
- python - 按列中的最大数量过滤
- excel - 带有偏移的 VBA Excel 循环,用于扩展单元格范围
- java - Clickhouse 在 INSERT INTO CSV 上的 DateTime 值无效
- python - 基于布尔值扩展选择
- javascript - dotenv throw err internal/modules/cjs/loader.js:800 找不到模块
- c# - 处理使用 C# 打开 Excel 文件时弹出的宏
- java - Google Play 应用内计费:ClassyTaxiAppWeb 在哪里?
- laravel - Laravel - 按列非数字顺序对 Eloquent 查询结果进行排序 [2、1、3 等]
- tensorflow - 如何结合独立的 CNN 和 LSTM 网络