简体   繁体   English

Python追踪(最近一次通话)错误

[英]Python Traceback (most recent call last) error

I have started coding for about a week, and while practicing to create a shape calculator, I encountered such an error: 我已经开始编码大约一周了,在练习创建形状计算器时,遇到了这样的错误:

Traceback (most recent call last):
File "python", line 4
if option = 'C':
          ^
SyntaxError: invalid syntax

The code is as follows: 代码如下:

print "The Calculator has been launched"
option = raw_input ("What shape is your object?     Enter C for circle or T 
for Triangle.")
if option = 'C': 
    radius = float (raw_input ("What is the radius of your circle?") )
    area_1 = 3.14159 * ( radius ** 2)
    print area_1 

elif option = 'T':
    base = float (raw_input ("What is the base of the triangle?"))
    height = float (raw_input ("What is the corresponding height of the 
    triangle?"))
    area_2 = (base * height) * 1/2
    print area 
else :
    print "Please, enter a valid shape" 

I would be very grateful if someone could explain the cause of the error. 如果有人可以解释错误的原因,我将不胜感激。

Thanks! 谢谢!

When comparing you must use a == . 比较时,必须使用== The = is only used for assignment. =仅用于分配。

So in your example the line should be 因此,在您的示例中,该行应为

if option == 'C':

Yes it is actually a very basic error that everyone does in the beginning :) 是的,这实际上是每个人一开始都会犯的一个非常基本的错误:)
The = operator does not mean the same thing in code as it does in math. =运算符在代码中的含义与在数学中的含义不同。 Here it means that you want to assign a value to a variable (you can also think of it as the := operator that you can see in maths or other coding languages). 在这里,这意味着您要为变量分配一个值(也可以将其视为可以在数学或其他编码语言中看到的:=运算符)。

The operator you need to compare two elements is == which returns a boolean value: either True or False 您需要比较两个元素的运算符是== ,它返回一个布尔值: TrueFalse

It is worth to mention that this code will be difficult for user to work beacue of nescessity of inputting big letters (Shitf + letter). 值得一提的是,由于不需要输入大写字母(Shitf +字母),该代码将使用户难以工作。 To avoid that, just use lower() method. 为了避免这种情况,只需使用lower()方法。

if option.lower() == "c":
   do_something()

Now, user can input both big or small letter ("c" or "C"), and program will be no differ to that. 现在,用户可以输入大写或小写字母(“ c”或“ C”),程序也没有什么不同。 Of course the nesscesity of using "==" in any comparing is necessity. 当然,在任何比较中都必须使用“ ==”的必要性。

you can also use 'is' 您也可以使用“是”

if option is 'C':

Don't use the equality "==" symbol to compare objects to None Use "is" instead 不要使用等号“ ==”将对象与“无”进行比较,而应使用“ is”

"etc" is None  # => False
None is None  # => True
# negate with not
not True  # => False
not False  # => True

# Equality is ==
1 == 1  # => True
2 == 1  # => False

# Inequality is !=
1 != 1  # => False
2 != 1  # => True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM