Home > Blockchain >  Assigning an if statement to a variable in Python
Assigning an if statement to a variable in Python

Time:12-01

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related