问题已经解决了。但是,我的帐户是新的,所以它不会让我回答这个问题。似乎用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()
答案 0 :(得分:1)
正确缩进后,将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<我们应该只使用ans == 1
或修改input to input_raw
python 3
答案 1 :(得分:0)
您的代码缩进显示每个'if','for'或'while'的控制范围。 您需要进一步缩进每个主要'if'语句下的说明,以便这样做 它们仅在选择“if”语句时执行。否则,一切 每次循环时都会执行最左边的缩进。例如,你应该有:
if answer == '1':
....<statements that execute under condition 1>
elif answer == '2':
....<statements that execute under condition 2>
我用'....'强调了缩进。
答案 2 :(得分:0)
第二个if语句不在第一个的括号内。对于1和2都是如此。
if ans == "1";
diameter = float(input("enter the diameter: "))
if diameter ....
答案 3 :(得分:0)
我将ans视为整数。我将ans视为整数是什么意思而不是写ans ==“1”,我写了ans == 1.it print corret 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()