Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Dungeon Game Movement

os.system("cls" if os.name == "nt" else "clear")

this syntax is different from what I had seen previously. Is this particular to only this function? or is it expandable to other areas. It kinda looks like a comprehension, but I don't think it is.

2 Answers

It is similar to a list comprehension! However, it isn't related to lists (unless you use a list) and it is basically the shorthand of the if and else statements instead of the for loop.

Let's look at an example:

def my_func(a, b):
    return a if (a > b) else b

This is the same as:

def my_func(a, b):
    if a > b:
        return a
        return b

As James said, it is basically the Python's way of using the ternary operator. In other languages (in this case Ruby) it might look like this:

(3 > 4) ? 3 : 4

As you see, the condition is first, followed by the ?, followed by the value that's returned if the condition is true, followed by a :, followed by the value if the condition is false.

I hope this helps :grin:

Happy C0D1NG! :tada:

:dizzy: ~Alex :dizzy:

Alex, thanks for the visual on that.