user1050619
user1050619

Reputation: 20856

How to set python variables to true or false?

I want to set a variable in Python to true or false. But the words true and false are interpreted as undefined variables:

#!/usr/bin/python
a = true; 
b = true;
if a == b:          
  print("same");

The error I get:

a = true
NameError: global name 'true' is not defined 

What is the python syntax to set a variable true or false?

Python 2.7.3

Upvotes: 47

Views: 311354

Answers (5)

Marwan Akram
Marwan Akram

Reputation: 25

as Poke said:

If you have a condition that is basically like this though:

if <condition>:
    var = True
else:
    var = False

then it is much easier to simply assign the result of the condition directly:

var = <condition>

but if you want to reverse it you can use:

var = <condition> is False

Upvotes: 0

Karanm0119
Karanm0119

Reputation: 31

you have to use capital True and False not true and false

Upvotes: 3

poke
poke

Reputation: 387707

First to answer your question, you set a variable to true or false by assigning True or False to it:

myFirstVar = True
myOtherVar = False

If you have a condition that is basically like this though:

if <condition>:
    var = True
else:
    var = False

then it is much easier to simply assign the result of the condition directly:

var = <condition>

In your case:

match_var = a == b

Upvotes: 76

Alireza
Alireza

Reputation: 4516

Python boolean keywords are True and False, notice the capital letters. So like this:

a = True;
b = True;
match_var = True if a == b else False
print match_var;

When compiled and run, this prints:

True

Upvotes: 6

Joran Beasley
Joran Beasley

Reputation: 113988

match_var = a==b

that should more than suffice

you cant use a - in a variable name as it thinks that is match (minus) var

match=1
var=2

print match-var  #prints -1

Upvotes: 13

Related Questions