-4

I ask if I can to use a variable condition on PYTHON like PHP :

<?php $var = (5 = 5) ? true : false; ?>
Benabra
  • 199
  • 2
  • 3
  • 13
  • I hope you mean `$var = (5 == 5) ? true : false;` rather than `$var = (5 = 5) ? true : false;` – Mark Baker Jul 15 '13 at 10:49
  • Why would you do that in PHP? Doesn't `$var = true` (or `$var === true` if that's the intent here...) work just as well? – Wooble Jul 15 '13 at 10:52
  • @Wooble `==` is a comparison operator; `=` is an assignment operator. `5 = 5` should give an error in PHP because you can't assign a value to a value, only to a variable – Mark Baker Jul 15 '13 at 11:18

3 Answers3

2

Just assign the result of the boolean test in your case:

var = 5 == 5  # assigns `True`

Otherwise you are looking for a conditional expression:

var = 'bar' if foo == 5 else 'spam'
Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
1

There's a conditional expression (also known as the ternary operator) in python, if that's what you mean:

me = 5 if a == b else c
TerryA
  • 52,957
  • 10
  • 101
  • 125
0

I guess you mean:

$var = (5 == 5) ? true : false

In Python (2.5 up) this can be written as:

b if a else c

"First a is evaluated, then either b or c is returned based on the truth value of a; if a evaluates to true b is returned, else c is returned." http://northisup.com/blog/the-ternary-operator-in-python/

honederr82
  • 334
  • 1
  • 5