问题已解决。但是,我的帐户是新的,因此它不会让我回答问题。似乎用 raw_input() 更改 input() 的实例可以使其工作。老实说,我不知道为什么,但这可能与 2 和 3 之间的差异有关。
我应该做一个可以计算面积和周长的程序。这部分并没有那么困难。
但是,菜单不起作用。菜单的第一部分工作正常,但是在您做出选择后,它不会打印它应该打印的内容。
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if ans == "1":
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == "2":
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == "0":
print("Thanks for hanging out with me!")
quit()
正确缩进后,if ans == "1"
更改为str(ans) == "1"
或ans == 1
,应该没问题。
这应该有效:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
if str(ans) == "1":
diameter = input("Enter the diameter: ")
print diameter
if float(diameter) > 0.0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
....
PS:正如评论中提到的,它有效,但令人作呕。如果您使用 python
代码的缩进显示每个"if"、"for"或"while"的控制范围。您需要进一步缩进每个主要"if"语句下的说明,以便它们仅在选择"if"语句时执行。 否则,一切即每次通过循环执行最左侧的缩进。 例如,您应该具有以下内容:
if answer == '1':
....<statements that execute under condition 1>
elif answer == '2':
....<statements that execute under condition 2>
我强调了用"...."缩进的地方。
第二个 if 语句不在第一个语句的括号内。 对于 1 和 2 都是如此。
if ans == "1";
diameter = float(input("enter the diameter: "))
if diameter ....
将 ans 视为整数有效。我的意思是将 ans 视为整数,而不是写 ans=="1",我写了 ans==1.it 打印相应的 cvalue。检查此代码:
import math
print ("""
1) Calculate circumference
2) Calculate area
""")
ans = input("Enter 1, 2, or 0 to exit this program: ")
print ans
if ans ==1:
diameter = float(input("Enter the diameter: "))
if diameter > 0:
circumference = (diameter*math.pi)
print("The circumference is", circumference)
else:
print("Error: the diameter must be a positive number.")
if ans == 2:
radius = float(input("Enter the radius: "))
if radius > 0:
area = ((radius**2)*math.pi)
print("The area is", area)
else:
print("Error: the radius must be a postive number.")
if ans == 0:
print("Thanks for hanging out with me!")
quit()