首页 > 解决方案 > 绝对价值计划

问题描述

我是一个初学者级的python程序员,我正在尝试制作这个短程序,它需要一个数字并打印它的绝对值。但是,每次我运行它时,编译器都会说我用来保存新数字的变量没有定义。IDK 我做错了什么。

print("Welcome to the ABSOLUTE-VALUEINATOR")
num=float(input("Enter number to find absolute value: "))

if num<=0:
    new_num=num*-1
    print("The absolute value is: "+str(new_num))

else:
    print("The absolute value is: " +str(new_num))

标签: pythonpython-3.x

解决方案


只需要一点点改变。new_numnumelse 中,它应该可以正常工作:

print("Welcome to the ABSOLUTE-VALUEINATOR")
num=float(input("Enter number to find absolute value: "))

if num<=0:
    new_num=num*-1
    print("The absolute value is: "+str(new_num))

else:
    print("The absolute value is: " +str(num))

这是因为 new_num 是在 if 条件下定义的,如果条件为假,它永远不会被定义。然而,一个好的方法是对更改的数字和实际输入使用相同的变量,这将避免所有混淆:

print("Welcome to the ABSOLUTE-VALUEINATOR")
num=float(input("Enter number to find absolute value: "))

if num<=0:
    num=num*-1
    print("The absolute value is: "+str(num))

else:
    print("The absolute value is: " +str(num))

推荐阅读