2016-09-17 47 views
1

刚刚在几个小时前启动了python,并发现了一个问题。 The blow snippet表明最初我将userInput存储为1或2,然后执行if块。问题是代码直接跳转到其他地方(即使我在控制台窗口中键入1)。 我知道我犯了一个简单的错误,但任何帮助将不胜感激。我的代码跳过了IF块并转到其他地方

使用Python 3.5 ===在Visual Studio 2015运行===具体的CPython

userInput = float(input("Choose 1 (calculator) or 2 (area check)\n")) 
if(userInput =='1') : 
    shape = input("Please enter name of shape you would like to calculate the area for\n") 

if(shape == 'triangle') : 
    base = int(input("Please enter length of BASE\n")) 
    height = int(input("Please enter HEIGHT\n")) 
    print("The area of the triangle is %f" % ((base * height)*0.5)) 

elif (shape == 'circle') : 
    radius = int(input("Please enter RADIUS\n")) 
    print("The Area of the circle is %f" % ((radius**2)*22/7)) 

elif (shape == 'square') : 
    length = int(input("Please Enter LENGTH\n")) 
    print("The area of the square is %f" % ((length**2)*4)) 

else : 
    initial1 = float(input("Please enter a number\n")) 
    sign1 = input("please enter either +,-,*,/ \nwhen you wish to exit please type exit\n") 
    initial2 = float(input("Please enter number 2\n")) 
if(sign1 == '+') : 
    answer = float(initial1) + float(initial2) 
    print(answer) 
elif(sign1 == '*') : 
    answer = float(initial1) * float(initial2) 
    print(answer) 
elif(sign1 == '-') : 
    answer = float(initial1) - float(initial2) 
    print(answer) 
elif(sign1 == '/') : 
    answer = float(initial1)/float(initial2) 
    print(answer) 

PS。如果[可能]你能保持尽可能基本的帮助,因为我想确保我完全理解基础知识。

感谢您的帮助! :D

+0

你正在转换为浮动,但比较字符串 –

回答

1

您正在将您的输入转换为浮点数,但检查数字的字符串。将其更改为:

If userInput == 1.0: 

或者更好的是,保持它的方式,并且不要将用户输入转换为浮动。只需要将输入转换为floatint如果您想对其进行数学运算。在你的情况下,你只是用它作为选项,所以你可以保留它作为一个字符串:

userInput = input("Choose 1 (calculator) or 2 (area check)\n") 

P.S.确保在Python中对缩进非常小心。我假设你的代码编辑器中的缩进是正确的,但是在粘贴到这个站点时也要小心。你在这里拥有同一层次的所有东西,但为了使程序正常工作,需要进一步缩进一些if块。

+0

非常感谢你@elethan - 完美的工作。虐待坚持删除“浮动”,因为它更有意义。 –

相关问题