python - Python:权重转换脚本问题
问题描述
我目前正在学习 Python,并且正在做一个练习,我正在制作一个重量转换器。我一直遇到这个问题,请问any1可以帮忙吗?
weight = int(input("How much do you weigh? "))
unit = input("Was that in (K)gs or (L)bs? ")
if unit == "L" or "l":
converted = weight * 0.45
print("Kgs: {0}".format(converted))
if unit == "K" or "k":
converted = weight / 0.45
print("Lbs: {0}".format(converted))
终端只打印两者。我不知道问题是什么。
解决方案
将您的代码更新为:
weight = int(input("How much do you weigh? "))
unit = input("Was that in (K)gs or (L)bs? ")
if unit in ["L", "l"]:
converted = weight * 0.45
print("Kgs: {0}".format(converted))
elif unit in ["K", "k"]:
converted = weight / 0.45
print("Lbs: {0}".format(converted))
您基本上面临两个问题:
你需要使用
if ... : elif ...:
. 否则,将始终评估条件。你没有
or
正确使用。unit == "L" or "l"
将始终评估为True
,您要检查的是您的输入是否为"k"
或"K"
,因此您有一些选择:
unit in ["K", "k"]
unit == "k" or unit == "K"
unit.tolower() == "k"
unit.toupper() == "K"
推荐阅读
- java - 在 Docker 中,Spring Boot 数据库连接不起作用
- python - 如何使用python根据列的条件总和从大型csv文件创建多个批处理文件
- sql-server - Sql Server Always Encrypt - 从 .net 核心代码访问时出错 - 数据类型 varchar(50) ... 在等于运算符中不兼容
- node.js - 使用 node js 将文件上传到 ftp 服务器
- r - 如何使R直方图居中?
- ios - 为什么 svg filter fecomposite 算法在 safari 和 ios 上返回错误的颜色?
- vue.js - 事件未从子组件到达父组件
- android - 如果单击图标搜索android如何隐藏NavigationView的图标
- flutter - Flutter - 芯片的宽度和 IconButton
- sql - 从审计日志中获取问题计数