简体   繁体   English

如果变量具有特定值,如何执行代码?

[英]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!")

You misspelled the equality check operator.您拼错了相等检查运算符。

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.

相关问题 如何在特定时间执行一段代码 - How to execute a piece of code on a certain time 仅对给定列具有特定值的行执行代码 - Execute code only on rows with a certain value for a given column 我如何在HTML中放置一个值并执行以该值作为变量的python代码 - How can i put a value in HTML and execute a python code with that value as a variable 是否有python函数来运行特定变量具有特定值的计数? - Is there a python function to run a count where a specific variable has a certain value? Pandas:如何找到具有特定值的列 - Pandas: How to find the column that has certain value Python-如何执行代码并存储到变量中? - Python-How to execute code and store into variable? 如何在实例变量的更改上执行代码? - How to execute code on a change in a instance variable? 当变量值不匹配时如何停止python运行某些'if'代码 - How to stop python from running certain 'if' code when the variable value doesn't match 如何在不不断重复代码的情况下使捕获异常为变量分配特定值? - How can I make catching exceptions assign a variable a certain value without constantly repeating the code? 如果变量的值不等于 nan,如何执行条件? - How to execute a condition if the value of the variable is not equal to nan?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM