Question 5.20: Logical Operators You need to specify a complex condition in......

Logical Operators

You need to specify a complex condition in an if statement.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use one of the logical operators: and, or, and not.

Discussion

As an example, you may want to check whether a variable x has a value between 10 and 20. For that, you would use the and operator:

>>> x = 17
>>> if x >= 10 and x <= 20:
… print(‘x is in the middle’)

x is in the middle

You can combine as many and and or statements as you need and also use brackets to group them if the expressions become complicated.

See Also

See Recipes 5.18 and 6.15.

Related Answered Questions

Question: 5.24

Verified Answer:

Create a function that groups together lines of co...
Question: 5.23

Verified Answer:

Use the Python break statement to exit either a wh...
Question: 5.22

Verified Answer:

Use the Python while statement. The while statemen...
Question: 5.21

Verified Answer:

Use the Python for command and iterate over a rang...
Question: 5.19

Verified Answer:

Use one of the comparison operators: <, >, &...
Question: 5.17

Verified Answer:

Use the upper or lower function as appropriate. Fo...
Question: 5.18

Verified Answer:

Use the Python if command. The following example w...
Question: 5.15

Verified Answer:

Use the Python [:] notation. For example, to cut o...
Question: 5.14

Verified Answer:

Use the find Python function. For example, to find...