[英]How to execute code if a variable has a certain value?
I have a problem with my code.我的代码有问题。 The language is python.
语言是python。 I am trying to use an if statement to execute some code if a variable has a certain value.
如果变量具有特定值,我正在尝试使用 if 语句来执行一些代码。
op = 5
if(op = 5):
print("op is 5!")
Every time I run this program, it gives me a syntax error.每次我运行这个程序时,它都会给我一个语法错误。 I have tried doing this instead;
我试过这样做;
op = 5
if op = 5:
print("op is 5!")
But it still gives me the error.但它仍然给我错误。 I am asking this question because I am doing a calculator project and need this.
我问这个问题是因为我正在做一个计算器项目并且需要这个。
=
is the assignment operator. =
是赋值运算符。 You're looking for the equality check operator, ==
:您正在寻找相等检查运算符
==
:
if op == 5:
print("op is 5!")
The equality check operator is ==
.相等检查运算符是
==
。 You put the assignment operator, which is this: =
.您放置了赋值运算符,即:
=
。
The following code will return a SyntaxError
:以下代码将返回
SyntaxError
:
foo = input('Enter the value of foo: ')
if foo = '5':
print('foo is equal to 5!')
else:
print('foo is not equal to 5!')
But this won't:但这不会:
foo = input('Enter the value of foo: ')
if foo == '5':
print('foo is equal to 5!')
else:
print('foo is not equal to 5!')
You just need to change the operator in the if statement to ==
.您只需要将 if 语句中的运算符更改为
==
。
For comparison we used double equal sign ==为了进行比较,我们使用了双等号 ==
Not single不单身
if op == 5:
print("op is 5!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.