Chapter 5 - if statement

Keywords: Python less

5-1 Conditional Test: Write a series of conditional tests; print out each test and your predictions and actual results. The code you write should be similar to the following:

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 they are True or False.  

# Create at least 10 tests, and the results are at least 5 tests for True and False, respectively.  

1 car = 'subaru'
2 print("Is car == 'subarur'? I predict True.")
3 print(car == 'subaru')
4 
5 print("\nIs car == 'audi'? I predict False")
6 print(car == 'audi')

Output:

1 Is car == 'subarur'? I predict True.
2 True
3 
4 Is car == 'audi'? I predict False
5 False

5-2 More conditional tests: You don't have to create 10 tests. If you want to try to do more comparisons, write some more tests and add them to conditional_test.py. For the various tests listed below, write at least one test that results in True and False.

# Check that the two strings are equal and unequal.

# Test using the 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.

# Testing using keywords and or.

# Test whether a specific value is included in the list.

# Determine whether a specific value is not included in the list.

 1 str1='aa'
 2 str2='bb'
 3 print(str1==str2)
 4 print(str1!=str2)
 5 name1='Ada'
 6 print(name1.lower()=='ada')
 7 num1=5
 8 num2=8
 9 print(num1==num2)
10 print(num1!=num2)
11 print(num1>num2)
12 print(num1<num2)
13 print(num1>=num2)
14 print(num1<=num2)
15 print(num1>=2 and num2>=2)
16 print(num1<=6 or num2<=6)
17 info=['a','b','c']
18 print('a' in info)
19 print('d' not in info)

Output:

 1 False
 2 True
 3 True
 4 False
 5 True
 6 False
 7 True
 8 False
 9 True
10 True
11 True
12 True
13 True

 

5-3 Alien Color #1: Assuming that an alien has just been shot in the game, create a variable named alien_color and set it to'green','yellow'or'red'.

# Write an IF statement to check if the alien is green; if so, print a message indicating that the player has obtained five points.

# Write two versions of this program, in one version of the above test passed, but failed in another version (no output when failed).

1 alien1="green"
2 if alien1=="green":
3     print("You get 5 point because you killed  an alien.")
4 alien2="red"
5 if alien2=="green":
6     print("You get 5 point because you killed  an alien.")

Output:

You get 5 point because you killed  an alien.

5-4 Alien Colour #2: Set the Alien Colour as Exercise 5-3, and write an if-else structure.

# If the alien is green, print a message indicating that the player got five points for shooting the alien.

# If the alien is not green, print a message indicating that the player has 10 points.

# Write two versions of this program, execute if code block in one version, and execute else code block in another version.

 1 alien1="green"
 2 if alien1=="green":
 3     print("You get 5 point because you killed  an alien.")
 4 else :
 5     print("You get 10 point.")
 6 alien2="red"
 7 if alien2=="green":
 8     print("You get 5 point because you killed  an alien.")
 9 else :
10     print("You get 10 point.")

Output:

1 You get 5 point because you killed  an alien.
2 You get 10 point.

 

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 five points.

# If the alien is yellow, print a message indicating that the player has 10 points.

# If the alien is red, print a message indicating that the player has obtained 15 points.

# Write three versions of the program, which print a message when aliens are green, yellow and red.

 

 1 alien='green'
 2 if alien =='green':
 3     print('You get 5 point.')
 4 elif alien =='yellow':
 5     print('You get 10 point.')
 6 else :
 7     print('You get 15 point.')
 8 
 9 alien2='yellow'
10 if alien2=='green':
11     print('You get 5 point.')
12 elif alien2=='yellow':
13     print('You get 10 point.')
14 else:
15     print('You get 15 point.')
16 
17 alien3='red'
18 if alien3=='green':
19     print('You get 5 point.')
20 elif alien3=='yellow':
21     print('You get 10 point.')
22 else :
23     print('You get 15 point.')

Output:

You get 5 point.
You get 10 point.
You get 15 point.

5-6 different stages of life: set the value of the variable age, then write an if-elif-else structure, according to the value of age to determine which stage of life is in.

# If a person is younger than 2 years old, print a message indicating that he is a baby.

# If a person is between 2 and 4 years old, print a message indicating that he is toddling.

# If a person is between 4 and 13 years old, print a message indicating that he is a child.

# If a person's age ranges from 13 to 20, 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.

 1 age=25
 2 if age<2:
 3     print("He is a baby. ")
 4 elif age>=2 and age <4:
 5     print("He is learning how to walk. ")
 6 elif age>=4 and age<13:
 7     print("He is a child. ")
 8 elif age>=13 and age <20:
 9     print("He is a young man. ")
10 elif age >=20 and age<65:
11     print("He is an adult. ")
12 else :
13     print("He is an old man. ")

Output:

1 He is an adult.

5-7 Favorite Fruits: Create a list of your favorite fruits and write a series of independent if statements to check whether the list contains specific fruits.

# Name the list favorite_fruits and include three fruits.

# Write five if statements, each checking whether a fruit is included in the list, and if it is included in the list, print a message, such as "You really like bananas!".  

 1 favorite_fruits=['apple','banana','orange']
 2 if 'apple' in favorite_fruits:
 3     print('You really like apples!')
 4 if 'banana' in favorite_fruits:
 5     print('You really like bananas!')
 6 if 'orange' in favorite_fruits:
 7     print('You really like oranges!')
 8 if 'grape' in favorite_fruits:
 9     print("You really like grapes.")
10 if 'pear' in favorite_fruits:
11     print('You really like pears.')

Output:

1 You really like apples!
2 You really like bananas!
3 You really like oranges!

5-8 greets administrators in a special way: create a list of at least five user names, one of which is'admin'. Imagine writing code that prints a greeting message after each user logs on to the site. Traverse the list of usernames 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 a common greeting message, such as "Hello Eric, thank you for logging in again".

1 usernames=['admin','ada','ava','peter','Marry']
2 for username in usernames:
3     if username=='admin':
4         print("Hello admin,would you like to see a status report?")
5     else:
6         print('Hello '+username+',thank you for loging in again.')

Output:

1 Hello admin,would you like to see a status report?
2 Hello ada,thank you for loging in again.
3 Hello ava,thank you for loging in again.
4 Hello peter,thank you for loging in again.
5 Hello Marry,thank you for loging in again.

5-9 deals with the situation where there are no 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's empty, print the message "We need to find some users!".

# Delete all user names in the list to make sure that the correct message will be printed.

1 usernames=[]
2 if usernames:
3     for username in usernames:
4         if username=='admin':
5             print("Hello admin,would you like to see a status report?")
6         else:
7             print('Hello '+username+',thank you for loging in again.')
8 else:
9     print("We need some users.")

Output:

We need some users.

5-10 Check User Names: Write a program to simulate a website to ensure that each user's username is unique.

# Create a list of at least five user names and name it current_users.

# Create a list of five usernames, name it new_users, and make sure that one or two of them are also included in the list current_users.

# Traversing through the list of new_users, for each user name, checks whether it has been used. If so, print a message indicating that another username needs to be entered; otherwise, print a message indicating that the username has not been used. Make sure that big messages are not distinguished when comparing; in other words, if the username'John'has been used, the username'JOHN' should be rejected.

1 current_users=['a','b','c','d','e','h']
2 new_users=['A','b','f','g','p']
3 for new_user in new_users :
4     if new_user.lower() in current_users:
5         print("You should print other name.")
6     else :
7         print("This name can use.")

Output:

1 You should print other name.
2 You should print other name.
3 This name can use.
4 This name can use.
5 This name can use.

5-11 ordinals: ordinals denote positions, such as 1st and 2nd. Most ordinals end in th, with only 1, 2 and 3 exceptions.

# Store numbers 1 to 9 in a list.

# Travel through the list.  

# An if-elif-else structure is used in the loop to print the ordinal number corresponding to each number. The output should be 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th and 9th, but each ordinal number has its own line.

1 for value in range(1,10):
2     if  value ==1:
3         print("1st")
4     elif value==2:
5         print("2nd")
6     elif value==3:
7         print("3rd")
8     else :
9         print(str(value)+"th")

Output:

1st
2nd
3rd
4th
5th
6th
7th
8th
9th

Posted by hmogan on Sat, 18 May 2019 11:37:08 -0700