Course 3.2Lesson 2 of 5
To check a range, write two comparisons joined by and, or use the short chain 50 <= marks <= 75. The word in asks whether a value is inside a group: a letter in a text, a word in a longer text, or a value in a list. not in is the opposite. A condition such as letter == 'a' or 'e' is a trap, because the text 'e' alone is always True, so each comparison must have its own left side. Use in to write such a test in one short line.
Try the code and the simulations beside the lesson.
After this lesson you can
in and not in,letter == "a" or "e" is a trap, andA value is in a range when it is at least the smallest and at most the biggest. Two comparisons joined with and say it exactly. Python also lets you write it as one chain, as you do in mathematics.
Two things to watch.
<= includes the end value, < does not. Test with the end values, as you learned in the last chapter.marks >= 50 and <= 75. Remove the # to see the SyntaxError, and then put the # back. Each comparison needs a variable on its left.The short chain and the long way with and always give the same answer.
Often a value must be one of several allowed choices. The word in asks: is this value inside that group?
You want to test that a letter is a vowel. In English you say "if the letter is a or e or i or o or u". So you write it like that:
Python reads the condition as five separate pieces: letter == "a", then "e", then "i", "o", "u". The first piece is False. But the others are not comparisons. They are bare pieces of text, and a piece of text that is not empty counts as True. So the whole or is True, whatever the letter is.
There are two correct ways.
Version 1: letter == "a" or letter == "e" or letter == "i" or letter == "o" or letter == "u"
Version 2: letter in "aeiou"
Put either one after the word if and a colon.
The second is short, clear and easy to extend. Whenever you catch yourself writing a long line of or with the same variable, think of in.
x == 1 or 2. The 2 alone is always True. Write x == 1 or x == 2, or x in [1, 2].in is case sensitive for text. Use letter.lower() in "aeiou".in with a number and a text: 5 in "12345" is a TypeError.not letter in "aeiou" and not knowing it is the same as letter not in "aeiou". Both work. The second reads better.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
in to write the test.and, or the chain low <= x <= high.x in group asks whether x is inside the group. x not in group is the opposite.x == a or b. Write x == a or x == b, or x in (a, b).Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
"a" in "banana"? And "nan" in "banana"?x == 1 or x == 2, x == 1 or 2, x in [1, 2]?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.