bob
bob

Reputation: 135

Python Using question marks in print statements?

I am trying to print c if a > b, else I want to print d. Currently I am using if statements, but I was wondering if there is a way to do this using question marks, as it complicates the code too much. I have seen it done before, but couldn't find any documentation on this.

#Current code
c = 'xxxxx'
d = 'xxxxxx'
print 'I like pie ',
if a > b:
    print c,
else:
    print d,
print ' that\'s why you should too!'

Upvotes: 0

Views: 3370

Answers (1)

jwodder
jwodder

Reputation: 57590

I assume that by "question marks" you mean the conditional operator a > b ? c : d. This syntax is from non-Python languages; in Python, the equivalent syntax for conditional expressions uses English keywords:

print (c if a > b else d),

(The parentheses aren't strictly necessary here, and you'll need to be careful if you try to run this in Python 3, but it makes the code easier to read.)

Upvotes: 4

Related Questions