Python learning road 4-if statement

This series is a compilation of notes for the introductory book "Python Programming: From Getting Started to Practice", which belongs to the primary content. The title sequence follows the title of the book.
This chapter mainly describes the structure of conditional statements if, if-else, if-elif, if-elif-else and so on.

Conditional test

Including "equal", "not equal", "greater than", "less than", "greater than or equal to", "less than or equal to", "exist in", "and or not" and other judgments. It's worth noting that Python is case sensitive:

>>> car = "Audi"
>>> car == "audi"
False

>>> car.lower() == "audi"
True

>>> car != "audi"
True

>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age >= 21
False

>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_0 >= 21 or age_1 >= 21
True

>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'mushrooms' not in requested_toppings
False

if statement

simple if statement

# 代码:
age = 19
if age >= 18:
    print("You are old enough to vote!")

# 结果:
You are old enough to vote!

if-else statement

# 代码:
age = 17
if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")

# 结果:
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

if-elif-else construct

# 代码:
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10

print("Your admission cost is $" + str(price) + ".")

# 结果:
Your admission cost is $5.

You can also use as many elifcode blocks as you want:

# 代码:
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
else:
    price = 5

print("Your admission cost is $" + str(price) + ".")

# 结果:
Your admission cost is $5.

Second, Python does not require a block of code to follow if-elifa structure . is an all-encompassing statement, as long as the previous conditions are not met, the code in it will be executed, which may introduce invalid or even malicious data. So if you know the final condition to be tested, you should consider using an elif code block instead of the code block to make the code clearer, as follows:elseelseelse

# 代码:
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 5
elif age < 65:
    price = 10
elif age >= 65:
    price = 5

print("Your admission cost is $" + str(price) + ".")

# 结果:
Your admission cost is $5.

Test multiple conditions

if-elif-elseThe structure is powerful, but it is only suitable for the case where only one condition is satisfied, that is, as long as one of the conditions is satisfied, the rest of the conditions will be skipped, which ensures the efficiency of the program. Sometimes, however, you have to check all the conditions you care about, in which case you should use a series of simple statements that don't contain elifand blocks:elseif

# 代码:
requested_toppings = ["mushrooms", "extra cheese"]

if "mushrooms" in requested_toppings:
    print("Adding mushrooms.")
if "pepperoni" in requested_toppings:
    print("Adding pepperoni.")
if "extra cheese" in requested_toppings:
    print("Adding extra cheese.")

print("\nFinished making your pizza!")

# 结果:
Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

In summary: if you only want to execute one block of code, use a if-elif-elsestructure; if you want to execute multiple blocks of code, use a series of independent ifstatements.

Working with lists using if statements

ifStatements are often used in conjunction with looping constructs.

Check for special elements

# 代码:
requested_toppings = ["mushrooms", "extra cheese", "green peppers"]

for requested_topping in requested_toppings:
    if requested_topping == "green peppers":
        print("Sorry, we are out of green peppers right now.")
    else:
        print("Adding " + requested_topping + ".")

print("\nFinished making your pizza!")

# 结果:
Adding mushrooms.
Adding extra cheese.
Sorry, we are out of green peppers right now.

Finished making your pizza!

Make sure the list is not empty

So far, a simple assumption has been made for each list processed, that is, they are not empty. However, in practical engineering, it is necessary to determine whether the list is empty before traversing it:

# 代码:
requested_toppings = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

# 结果:
Are you sure you want a plain pizza?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325658070&siteId=291194637