python - 绝对价值计划
问题描述
我是一个初学者级的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))
解决方案
只需要一点点改变。new_num
在num
else 中,它应该可以正常工作:
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))
推荐阅读
- python - 如何设置自定义目录以输出 selenium 保存的 pdf 文件
- python - 如何在没有控制台外壳的情况下在 python tkinter 列表框中运行 cmd 命令?
- c# - EmguCV 如何使用现有的垫子创建垫子?
- c - 我的添加大数字代码有什么问题?
- javascript - 位置从固定切换到静态时不会出现反向粘性导航栏?
- c++ - 矩阵中的行和列的总和
- python - 如何去除气缸上的网格?
- javascript - 错误:如何在隐藏和显示之间切换
- react-native - React-Native:在 props.navigation.navigate("XYZScreen", myFunction()) 中传递函数
- r - 添加一列,显示前两列是否包含 0