Conditionals Practice
Let’s try some simple practice problems. These problems are not graded - they are just for you to practice before doing the real exercises in the lab itself. You can find the answers below each question by clicking the button below each question.
4.5 Reading Code
Consider the following Python program:
a = int(input("Enter a whole number: "))
b = int(input("Enter a whole number: "))
if (a + b) % 3 == 0:
print("Branch 1")
else:
print("Branch 2")
a = a * 2
b = b * 3
if (a + b) % 3 == 0:
print("Branch 3")
else:
print("Branch 4")
What output is printed when the user inputs the values $ 2 $ and $ 4 $?
4.6 Testing Code
Consider the program in the previous question. Write a set of possible inputs to the program that will achieve path coverage. For each set of inputs, identify which branches will be executed when that input is provided to the program.
Think carefully! The same if statement is executed twice with different values, but those values are related to each other.
4.7 Reading Code
Consider the following Python program:
x = int(input("Enter an integer: "))
y = int(input("Enter an integer: "))
if x * 5 > y:
print("Branch 1")
else:
print("Branch 2")
if y % 5 == x:
print("Branch 3")
else:
print("Branch 4")
What output is displayed when the user inputs the values $ 4 $ and $ 29 $?
4.8 Testing Code
Consider the program in the previous question. Write a set of possible inputs to the program that will achieve path coverage. For each set of inputs, identify which branches will be executed when that input is provided to the program.
4.9 Writing Code
Write a complete Python that performs the following actions:
- Accept a single input from the user and convert it to an integer
- If the number is even, display “That is an even number”. If it is odd, display “That is an odd number”.
- If the number is negative, display “That is a negative number”. If it is zero or positive, display “That is a positive number”.
Your program should include at least two conditional statements.
4.10 Writing Code
Write a complete Python program in that file that performs the following actions:
- Accept a single string as input from the user
- If the string comes before the string “First” in lexicographic order, print “That comes before First”. If not, print “That comes after First”.
- If the string comes after the string “last” in lexicographic order, print “That comes after last”. If not, print “That comes before last”.
Recall that you can use Boolean comparators such as <
and >
to compare two strings in Python. Also, pay special attention to the capitalization of the words “First” and “last” in the description above.
Your program should include at least two conditional statements.
Bonus food for thought: look at your completed answer - is there a path that is not possible to actually test? Why is that?