简体   繁体   中英

Assigning an if statement to a variable in Python

I'm working on (or, rather improving on) a python project of mine. For one of the outcomes in my program, I need an if statement to be assigned to a variable.

When I try to assign it to a variable, it wont work. For example:

var = if num1 == 0
print("You cannot choose 0!")

If I try to do that, I get "Invalid Syntax" . I would like to know a way around this, or if there's not, so my program can function properly.

x = <value_1> if <Boolean> else <value_2>

works in python. If you want to store just the Boolean then you can do

var = num1 == 0

Python will give you an error when you store an "if statement" inside a variable. What you can do instead is, store whatever Boolean needed in your if statement inside a variable. For example:

x = value1 == 0

and then define your if statement like this:

var = answer1 if value1 else answer2

So this would be the same as writing:

if value1 == 1:
   return answer1
else:
   return answer2

Hope this will fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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