Python代码既没有正确运行也没有在VS代码中显示错误

问题描述 投票:1回答:1

Screenshot of Code & output我正在使用Vs代码(Charm在我的电脑上工作不顺畅)用于python开发它在调试后卡住而没有显示错误或输出。

我在堆栈溢出中搜索了匹配的解决方案

weight = int(input("Enter weight: "))
unit   = input("(K)kilograms or (P)pounds? ")

if unit.upper == "P":
    (weight*=1.6)
    print("Weight in kilograms: " + weight)
else if Unit=="K":
    (weight*=1.6)
    print("Weight in pounds: " + weight)
else:
    print("ERROR INPUT IS WRONG!")

我希望它能获取输入并提供转换后的输出

python-3.x visual-studio-code vscode-settings
1个回答
1
投票

你的脚本:

  • 错过了一个()
  • 使用未知名称Unit
  • 尝试添加字符串和数字:print("Weight in pounds: " + weight)
  • 英镑计算错了吗?
  • uses()在不适用的地方
  • 使用else if ... :

weight = int(input("Enter weight: "))
unit   = input("(K)kilograms or (P)pounds? ")

if unit.upper == "P":                         # unit.upper()
    (weight*=1.6)                             # ( ) are wrong, needs /
    print("Weight in kilograms: " + weight)   # str + float?
else if Unit=="K":                            # unit  ... or unit.upper() as well
    (weight*=1.6)                             # ( ) are wrong
    print("Weight in pounds: " + weight)      # str + float
else:
    print("ERROR INPUT IS WRONG!")

您可以直接使用.upper()输入:

# remove whitespaces, take 1st char only, make upper 
unit   = input("(K)kilograms or (P)pounds? ").strip()[0].upper() 

甚至可能更好:

weight = int(input("Enter weight: "))
while True:
    # look until valid
    unit = input("(K)kilograms or (P)pounds? ").strip()[0].upper()
    if unit in "KP":
        break
    else: 
        print("ERROR INPUT IS WRONG! K or P")

if unit == "P":                          
    weight /= 1.6                           # fix here need divide
    print("Weight in kilograms: ", weight)  # fix here - you can not add str + int
else:  
    weight *= 1.6                        
    print("Weight in pounds: ", weight) 

你应该看看str.format:

    print("Weight in pounds: {:.03f}".format(weight))  # 137.500

见f.e. Using Python's Format Specification Mini-Language to align floats

© www.soinside.com 2019 - 2024. All rights reserved.