Before writing your conditionals, it can be helpful to make your own flowchart that will plot out the flow of each condition. By writing out the flow, you can better determine how complex the set of conditionals will be as well as check to see if any condition is not taken care of before you begin writing it out.
To make sure that your code covers all of the conditions that you intend for it to cover, you should add comments for each clause that explains what that clause is meant to do. Then, you should add tests for each possible path that the program could go though. What leads to certain conditional statements being executed? Is that what you intended?
Subsection6.11.1Choosing your type of Conditional
When adding conditionals to your program, you should also consider the kinds of conditionals that are at your disposal and what would fit best.
Though youβll use them often, remember that conditional statements donβt always need an else clause. When deciding the flow, ask yourself what you want to have happen under a certain condition. For example, if you wanted to find all of the words that have the letter βnβ in them. If thereβs nothing that needs to happen when a word does not contain the letter βnβ then you wonβt need an else clause. The program should just continue onward!
Checkpoint6.11.1.
What is the best set of conditonal statements provided based on the following prompt? You want to keep track of all the words that have the letter βtβ and in a separate variable you want to keep track of all the words that have the letter βzβ in them.
If statement - Else statement
Using if/else either uses an unnecessary else statement or would improperly keep track of one of the accumulator variables.
If statement - Elif statement
Using if/elif means that words that have both a "t" and a "z" would not be propperly counted by the two variables.
If statement - If statement
Yes, two if statements will keep track of - and properly update - the two different accumulator variables.
If statement - Elif statement - Else statement
Using if/elif/else here will provide an unnecessary else statement and improperly update one of the accumulator variables in the case where a word has both a "t" and a "z".
Checkpoint6.11.2.
Select the most appropriate set of conditonal statements for the situation described: You want to keep track of all the words that contain both βtβ and βzβ.
If statement - Elif statement - Else statement
The elif and else statements are both unnecessary.
If statement - Else statement
The else statement is unnecessary.
If statement - Nested If statement
Though you could write a set of conditional statements like this and answer the prompt, there is a more concise way.
If statement
Yes, this is the most concise way of writing a conditional for that prompt.
If statement - Nested If statement - Else statement