Python Forum
define a variable using an if statement - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: define a variable using an if statement (/thread-30517.html)



define a variable using an if statement - Margaridalopes - Oct-24-2020

I would like to define a variable using an if statement, for example:

a=0
b=1

if a = 0:
   c = b
 else:
   c = a
I know the above does not work, but is there a way of defining 'c' with an if statement or something similar?

Thank you


RE: define a variable using an if statement - deanhystad - Oct-24-2020

#this
x = 2
#is no different than this
if 4 > 3:
    x = 2
#or this
a = 3
if a % 2:
    x = 2
You can define variables anywhere you want in Python. Your example didn't work because you don't know the difference between set equal to "=" and is equal to "=="
a=0
b=1

if a == 0:
    c = b
else:
    c = a



RE: define a variable using an if statement - jefsummers - Oct-24-2020

Your code would work if you change the = to == in your if statements