Question 5.18: Running Commands Conditionally You want to run some Python c......

Running Commands Conditionally

You want to run some Python commands only when some condition is true.

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 the Python if command.

The following example will print the message x is big only if x has a value greater than 100:

>>> x = 101
>>> if x > 100:
… print(“x is big”)

x is big

Discussion

After the if keyword, there is a condition. This condition often, but not always, compares two values and gives an answer that is either True or False. If it is True, then the subsequent indented lines will all be executed.

It is quite common to want to do one thing if a condition is True and something different if the answer is False. In this case, the else command is used with if, as shown in this example:

x = 101
if x > 100:
print(“x is big”)
else:
print(“x is small”)
print(“This will always print”)

You can also chain together a long series of elif conditions. If any one of the conditions succeeds, then that block of code is executed, but none of the other conditions are tried. For example:

x = 90
if x > 100:
print(“x is big”)
elif x < 10:
print(“x is small”)
else:
print(“x is medium”)

This example will print x is medium.

See Also

See Recipe 5.18 for more information on different types of comparisons you can make.

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.20

Verified Answer:

Use one of the logical operators: and, or, and not...
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.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...