[Tutor] If - else Vs OR

Alan Gauld alan.gauld at yahoo.co.uk
Wed Jul 22 18:42:44 EDT 2020


Please use reply-ALL or Reply0List when responding to the group.
CCing my reply.

On 22/07/2020 19:00, Nick Kartha wrote:
> Since when could we do if else /inside/ the print()
> This is new to me, and have not seen this in another language.

print takes a string argument(as well as some others)
That argument can be a literal string or any python expression that
evaluates to a string.

The expression

<value> if <test> else <another value>

can be used anywhere that a value is required, including
inside a print.

C/C++ has a similar construct:

<value> ? <test> : <other value>

And a couple of others have borrowed that. Python took
it and made it more readable.

> I assume the condition is checked before the print 

Yes it is an expression that is evaluated and the result printed.
Think about these examples of similar things:

print(5+3)   # -> print(8) -> print"8")

myObject.name = "Alan"
print(myObject.name) # -> print("Alan")

x = 42
print("The answer to ... everything is {}".format(x))
-> print("The answer to ... everything is 42")

These are all expressions that get evaluated to a string
before printing. The conditional expression is no different.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list