5

Possible Duplicate:
Conditional operator in Python?

Is there a c-like operator in python that check if a condition holds and assign a value accordingly?

<condition> ? <operation> : <operation>
5
  • 4
    please don't make such a claim as "best language in the world" It is 'best' for certain programmer for certain purpose. You probably won't build an OS kernel in python. The same as you won't use a hammer to cut a rope. Commented Feb 5, 2012 at 19:44
  • 2
    What were you expecting? That Python follows C syntax? Commented Feb 5, 2012 at 19:50
  • @amit The OP probably means "overall, taking the whole thing into account..." ;-) Commented Feb 5, 2012 at 19:55
  • @joaquin: languages are tools. The more tools you have - the better you can accomplish what you want to do. The same as a hammer is not better then scissors, python is not better then C. You'll probably be best if you master both of them [or in general: most of them], and use the right tool for the right task. Also, since I doubt the OP knows all languages, he cannot claim it is better then the rest. Commented Feb 5, 2012 at 19:58
  • 2
    -1: Making assumptions and then asking why the assumption wasn't followed is a particularly bad kind of question. Why not ask for the ALTER statement (from COBOL)? Why not ask for labels and GOTO's? Why not ask for any other random feature of a random language? Commented Feb 5, 2012 at 21:00

2 Answers 2

8

The syntax is different in Python.

<operation> if <condition> else <operation>

For example,

x = max(y, z)

is roughly the same as:

x = z if z > y else y
Sign up to request clarification or add additional context in comments.

7 Comments

I also saw somewhere: [<f_operation>, <t_operation>][condition] it has the advantage of also grouping together operations but in the left side instead of the right side as in the OP code
@joaquin: That evaluates both statements in the list, so it's nothing like a if
oh I see what you mean. when b=0 this x = [10, 3 / b][b > 0] fails
@benw: Incorrect. First, the brackets are extraneous, it's the same as condition and true_option or false_option. Second, it's incorrect: it will fail when true_option is false. For example, True and "" or "False" will evaluate to "False", whereas "" if True else "False" will evaluate to "".
RIGHT, I knew I was forgetting something: (condition and [true_option] or [false_option])[0]. Since the t if c else f syntax was introduced I've forgotten the way it went.
|
2

One of Python's design philosophies seems to be to use words instead of symbols when possible. In this case, the best words to use are if and else. But those words are already taken. So Python cheats a bit and uses syntax to disambiguate the version of if that controls flow from the version of if that returns a value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.