【问题标题】:Python code neither running proper nor showing errors in VS CodePython 代码既不能正常运行,也不能在 VS Code 中显示错误
【发布时间】:2019-03-23 14:34:36
【问题描述】:

我正在使用 Vs 代码(Charm 在我的 PC 上运行不顺畅)进行 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】:

    你的脚本:

    • 错过了一个()
    • 使用未知名称Unit
    • 尝试添加字符串和数字:print("Weight in pounds: " + weight)
    • 英镑计算错误
    • 在不适用的情况下使用 ()
    • 使用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

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2016-03-15
      • 2021-05-12
      相关资源
      最近更新 更多