Python Forum
define a variable using an if statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
define a variable using an if statement
#1
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
buran write Oct-24-2020, 02:06 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
#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
Margaridalopes likes this post
Reply
#3
Your code would work if you change the = to == in your if statements
Margaridalopes likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Define Variable xinyulon 5 1,227 Nov-03-2022, 01:12 AM
Last Post: Larz60+
  An IF statement with a List variable dedesssse 3 8,191 Jul-08-2021, 05:58 PM
Last Post: perfringo
  How to use a variable in Python (2.x) to define decimal part? MDRI 4 2,324 May-07-2021, 12:39 AM
Last Post: MDRI
  How to define a variable in Python that points to or is a reference to a list member JeffDelmas 4 2,642 Feb-28-2021, 10:38 PM
Last Post: JeffDelmas
  How to store the value from variable into list & run a statement then put in variable searching1 1 2,444 May-29-2019, 06:36 AM
Last Post: heiner55
  How to I define a variable between strings in telnetlib write? Fez 2 3,381 May-02-2019, 06:53 PM
Last Post: Fez
  SELECT statement query question using a variable DT2000 2 3,009 Feb-23-2019, 07:35 AM
Last Post: DT2000
  Invalid syntax in two variable if statement? 00712411 1 2,260 Oct-10-2018, 12:36 AM
Last Post: stullis
  If statement variable not defined MTom5 3 6,743 Sep-03-2018, 04:31 PM
Last Post: ichabod801
  i can use this statement as a variable name Skaperen 6 3,251 Aug-01-2018, 08:46 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020