Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
    else:
        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.