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

Simplifying chained comparisons

My IDE is saying that the line

elif num_of_guesses_left <= 3 and num_of_guesses_left >= 2:

should be simplified. How?

1 Answer

Hi Miika,

In Python, you can write this as:

elif 2 <= num_of_guesses_left <= 3:

Nice, huh? It's cleaner, and a bit more semantic (reads as "num_of_guesses_left is between 2 and 3, inclusive").

You could also write it as:

elif num_of_guesses_left in range(2, 4):

range returns a list of integers starting with the first argument, and up to but not including the second argument (meaning 4 would not be included). This only works if you're checking integers (which we are), since range(2, 4) returns the list [2, 3], and 2.5 is not in that list.

I find the first method a bit more readable, but both would work in this case.

Cheers :beers:

-Greg