【问题标题】:not receiving the output that im supposed to [duplicate]没有收到我应该[重复]的输出
【发布时间】:2021-08-05 04:28:57
【问题描述】:

所以我试图制作一个重量转换器应用程序。它首先询问用户他们的体重,然后询问它是以磅还是公斤为单位,然后将其转换为另一个单位。例如,如果有人以公斤为单位输入他们的体重,它会将其转换为磅。但问题是,每当我输入磅时,它应该将其转换为公斤,但它不会,并将其“转换”为磅,即使它是以磅为单位。

weight = int(input("Enter your weight: "))
user_choice = input ("(L)bs or (K)g: ")

if user_choice == "K" or "k":
    converted = int(weight) * 2.2046
    print (f"Your weight in pounds is {converted} lbs")
elif user_choice == "L" or "l":
    converted = int(weight) / 2.2046
    print (f"Your weight in kilograms is {converted} kg")
else:
    print ("Please enter a valid option.")

我是 python 的初学者,所以任何帮助将不胜感激。

【问题讨论】:

  • if条件应该是user_choice == 'K' or user_choice == 'k'或者user_choice in ['K', 'k']
  • 这是因为 or "k" 被评估为 True,因为 "k" 不是 False。试试False or True 看看发生了什么

标签: python python-3.x


【解决方案1】:

使用 user_choice=="k" 或 user_choice=="K"

    weight = int(input("Enter your weight: "))
    user_choice = input ("(L)bs or (K)g: ")
    
    if (user_choice == "K" or user_choice=="k"):
        converted = int(weight) * 2.2046
        print (f"Your weight in pounds is {converted} lbs")
    elif(user_choice == "L" or user_choice=="l"):
        converted = (int(weight) / 2.2046)
        print (f"Your weight in kilograms is {converted} kg")
    else:
        print ("Please enter a valid option.")

【讨论】:

  • 你对括号的使用很不合常规
  • @MadPhysicist 是的!我来自 c++ 背景,我喜欢括号!哈哈
  • @MadPhysicist Python 开发人员可能会被冒犯! XD
【解决方案2】:

您可以通过稍微修改 if-elif 条件来使其工作

weight = int(input("Enter your weight: "))
user_choice = input ("(L)bs or (K)g: ")

if user_choice in ('k', 'K'):
    converted = int(weight) * 2.2046
    print (f"Your weight in pounds is {converted} lbs")
elif user_choice in ('l', 'L'):
    converted = int(weight) / 2.2046
    print (f"Your weight in kilograms is {converted} kg")
else:
    print ("Please enter a valid option.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2016-12-12
    • 2016-09-05
    • 2018-04-21
    相关资源
    最近更新 更多