Python Programming: from introduction to practice -- if statement (Chapter 5 + answers after class)

Corresponding Bibliography: Python Programming: from introduction to practice

if statement (Chapter 5)

The best way to understand new programming concepts is to try to use them in programs

  1. The core of each if statement is an expression with a value of True or False, which is called a conditional test
  2. To determine that a specific value is not included in the list, you can use the keyword not in

Try it yourself

5-1 condition test: write a series of condition tests; Print out each test and your prediction and actual results of its results. The code you write should look like this:
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
 study the actual results in detail until you understand why it is True or False
 create at least 10 tests, and there are at least 5 tests whose results are True and False respectively

car = 'subaru'
if car == 'subaru':
    print("Is car == 'subaru'? I predict True.")
else:
    print("False")
if car == 'subaru':
    print("\nIs car == 'audi'? I predict False.")

5-2 more conditional tests: you can't only create 10 tests. If you want to try more comparisons, write some more tests and add them to conditional_tests.py. For the various tests listed below, write at least one test with True and False results.
 check that the two strings are equal and unequal
 test using function lower()
 check that the two numbers are equal, unequal, greater than, less than, greater than or equal to, and less than or equal to
 tests using the keywords and and or
 test whether specific values are included in the list
 test whether specific values are not included in the list

if 'a' == 'b':
    print("True")
else:
    print("False")

if 'A'.lower() == 'a':
    print("True")
else:
    print("False")

if 4 >= 3:
    print("True")
else:
    print("False")

if 4 >= 3 and 3 >= 2:
    print("True")
else:
    print("False")

num = ['a','b','c','d','e']
if 'c' in num:
    print("True")
else:
    print("False")

if 'x' not in num:
    print("True")
else:
    print("False")
  1. It is often necessary to check more than two cases. For this purpose, you can use the if elif else structure provided by Python
  2. The elif line of code is actually another if test that runs only if the previous test fails

Try it yourself

5-3 alien color #1: suppose you just shot an alien in the game, please create an alien named alien_color and set it to 'green', 'yellow', or 'red'
 write an if statement to check whether aliens are green; if so, print a message indicating that the player has obtained 5 points
 write two versions of this program. In one version, the above test passes and in the other version, it fails (there is no output when the test fails)

alien_color = ['green','yellow','red']
if 'green' in alien_color:
    print("you get 5 points")

alien_color = ['blue','yellow','red']
if 'green' in alien_color:
    print("you get 5 points")
else:
    print()

5-4 alien color #2: set the alien color as in exercise 5-3 and write an if else structure
 if the alien is green, print a message indicating that the player has obtained 5 points for shooting the alien
 if the alien is not green, print a message indicating that the player has obtained 10 points
 write two versions of the program, in which the if code block is executed and the else code block is executed in the other version

alien_color = ['green','yellow','red']
if 'green' in alien_color:
    print("you get 5 points")
if 'green' not in alien_color:
    print("you get 10 points")

alien_color = ['green','yellow','red']
if 'green' in alien_color:
    print("you get 5 points")
else:
    print("you get 10 points")

5-5 alien color #3: change the if else structure in exercise 5-4 to if elif else structure
 if the alien is green, print a message indicating that the player has obtained 5 points
 if the alien is yellow, print a message indicating that the player has obtained 10 points
 if the alien is red, print a message indicating that the player has obtained 15 points
 write three versions of this program, which print a message when the alien is green, yellow and red

alien_color = ['green','yellow','red']
if 'green' in alien_color:
    print("you get 5 points")
elif 'yellow' in alien_color:
    print("you get 10 points")
else:
    print("you get 15 points")

5-6 different stages of life: set the value of the variable age, and then write an if elif else structure to judge which stage of life you are in according to the value of age
 if a person is younger than 2 years old, print a message indicating that he is a baby
 if a person is 2 (inclusive) to 4 years old, print a message indicating that he is toddler
 if a person is 4 (inclusive) to 13 years old, print a message indicating that he is a child
 if a person is between 13 and 20 years old, print a message indicating that he is a teenager
 if a person is between 20 and 65 years old, print a message indicating that he is an adult
 if a person is over 65 years old, print a message indicating that he is an elderly person

age = 13
if age < 2:
    print("He is a baby")
elif age < 4:
    print("He is a toddler")
elif age < 13:
    print("He is a child")
elif age < 20:
    print("He is a teenager")
elif age < 65:
    print("He is a adult")
else:
    print("He is an old man")

5-7 favorite fruits: create a list containing your favorite fruits, and then write a series of independent if statements to check whether the list contains specific fruits
 name the list favorite_fruits and contains three kinds of fruits
 write five if statements, each of which checks whether a certain fruit is included in the list. If it is included in the list, print a message, such as "You really like bananas!"

favorite_fruits = ['banana','strawberry','grapes']
if 'banana' in favorite_fruits:
    print("You really like " + favorite_fruits[0] + "!")#An entire list cannot be output with a string, but a single element can because it is a string
if 'strawberry' in favorite_fruits:
    print("You really like " + favorite_fruits[1] + "!")
if 'grapes' in favorite_fruits:
    print("You really like " + favorite_fruits[2] + "!")
if 'durian' not in favorite_fruits:
    print("You really don't like " + "durian" + "!")

Try it yourself

5-8 say hello to the administrator in a special way: create a list of at least 5 user names, one of which is' admin '. Imagine writing code to print a greeting message after each user logs in to the website. Traverse the list of user names and print a greeting message to each user
 if the user name is' admin ', print a special greeting message, such as "Hello admin, would you like to see a status report?"
 otherwise, print an ordinary greeting message, such as "Hello Eric, thank you for logging in again"

names = ['admin','b','c','d','e']
for name in names:
    if name == 'admin':
        print("Hello " + name + ", would you like to see a status report?")
    else:
        print("Hello "+ name +", thank you for logging in again")

5-9 dealing with situations without users: in the program written to complete exercise 5-8, add an if statement to check whether the list of user names is empty
 if it is empty, print the message "We need to find some users!"
 delete all user names in the list and make sure that the correct message will be printed

names = []
if names:
    for name in names:
        if name == 'admin':
            print("Hello " + name + ", would you like to see a status report?")
        else:
            print("Hello "+ name +", thank you for logging in again")
else:
    print("null")

5-10 check user name: write a program according to the following instructions to simulate the website and ensure that each user's user name is unique
 create a list of at least five user names and name it current_users
 create another list of five user names and name it new_users and make sure one or two of them are also included in the list current_ In users
 traverse the list new_users, for each user name, check whether it has been used. If so, print a message indicating that another user name needs to be entered; Otherwise, a message is printed indicating that the user name is not used
 ensure that big messages are not distinguished during comparison; In other words, if the user name 'John' is already in use, the user name 'John' should be rejected

current_users = ['a','b','c','D','e']
new_users = ['c','E','f','g','h']
for new_user in new_users:
    if new_user.lower() in current_users:
        print("You need to enter a different user name")
    else:
        print("Indicates that the user name is not in use")

5-11 ordinal number: ordinal number indicates position, such as 1st and 2nd. Most ordinals end with th, with the exception of 1, 2, and 3
 store numbers 1 to 9 in a list
 traverse this list
 use an if elif else structure in the loop to print the ordinal number corresponding to each number. The output content should be 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th and 9th, but each ordinal number is exclusive

nums = range(1,10)
for num in nums:
    if num == 1:
        print(str(num) + "st")
    elif num == 2:
        print(str(num) + "nd")
    elif num == 3:
        print(str(num) + "rd")
    else:
        print(str(num) + "th")


 

Tags: Python Programming

Posted by mamoman on Sat, 26 Mar 2022 04:26:08 +0300