if-else statement

G

Gandalf

other languages like PHP or javascript as this if-else operator like
this

myVar = checking == 1? 'string': 'other string'

is this stuff exist in python?

thanks!
 
P

Philip Semanchuk

Gandalf said:
other languages like PHP or javascript as this if-else operator like
this

myVar = checking == 1? 'string': 'other string'

is this stuff exist in python?
See http://docs.python.org/reference/expressions.html#boolean-operations

conditional_expression ::= or_test ["if" or_test "else" expression]

...

The expression x if C else y first evaluates C (not x); if C is
true, x is
evaluated and its value is returned; otherwise, y is evaluated and its
value is returned.

Gandalf,
I'd add to the above that this expression was only added to Python in
v2.5, so if you want your code to be compatible with versions of
Python <= 2.4, you should not use the ternary if.

bye
Philip
 
B

bearophileHUGS

Scott David Daniels:
      if checking:
          my_var = 'string'
      else:
          my_var = 'other string'

remember, vertical space only kills trees if printed.

I value clarity a lot. But this is more DRY, sometimes it's almost
equally clear, and you reduce vertical space, packing more code in the
same space, this allows you to see more logic, allowing you to have a
higher level view of the code, so allows you to understand the code
better:

my_var = 'string' if checking else 'other string'

So I think that sometimes it's useful.

Bye,
bearophile
 
A

Aaron Brady

Scott David Daniels:



I value clarity a lot. But this is more DRY, sometimes it's almost
equally clear, and you reduce vertical space, packing more code in the
same space, this allows you to see more logic, allowing you to have a
higher level view of the code, so allows you to understand the code
better:

my_var = 'string' if checking else 'other string'

So I think that sometimes it's useful.

Bye,
bearophile

It would be a good tool that allows you to see logic-- extra points
for dynamic!

A quick Google for 'python flow chart' turns up 'Visustin' (commercial
+ demo), 'Flowchart Python', & others. http://www.google.com/search?q=python+flow+chart
.. The "bird's eye view" in Visustin is pretty cool.

Control-flow-only could be a lot simpler, just filtering statements
with 'if/while/for', and try-except, not even in diagram. It's on the
way for the open source IDE, right?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,299
Messages
2,571,546
Members
48,300
Latest member
Markwen49

Latest Threads

Top