首页 > 解决方案 > 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))

终端只打印两者。我不知道问题是什么。

标签: python

解决方案


将您的代码更新为:

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

您基本上面临两个问题:

  1. 你需要使用if ... : elif ...:. 否则,将始终评估条件。

  2. 你没有or正确使用。unit == "L" or "l"将始终评估为True,您要检查的是您的输入是否为"k""K",因此您有一些选择:

  • unit in ["K", "k"]
  • unit == "k" or unit == "K"
  • unit.tolower() == "k"
  • unit.toupper() == "K"

推荐阅读