COS 100: Introduction to Programming
Interim 2022
Lab 2: Making decision
In-class practice labs will not directly impact your grade
(although you'll get your standard participation point for staying on task),
and will serve to help you with homework projects.
Lab 2A: Is my number divisible by 3?
-
Goal:
To start experimenting with
if
statements.
-
Task:
Follow the steps.
-
Prompt the user for an integer, and report whether it is divisible by 3.
Use an
if
-else
construction.
Sample runs:
Integer, please: 30
Divisible by 3, yay!
Integer, please: 23
Not divisible by 3, sad face.
-
Modify your program so if the number is not divisible by 3, you report the remainder.
Use an
if
-else
construction nested inside the "not divisible" case.
Sample runs:
Integer, please: 30
Divisible by 3, yay!
Integer, please: 23
The remainder is two.
Integer, please: 7
The remainder is one.
-
Modify your program to use
if
-elif
-else
construction instead of two nested if
-else
constructions.
Maintain the same program behavior.
-
Before moving on:
Take a moment to meditate upon the benefits of the third step above.
This is known as refactoring code:
even though no new functionality has been added to the program,
the code has been changed to make it easier to read/understand/maintain.
Lab 2B: What letter grade do I have in this class? (chained if
s)
-
Goal:
To get some practice with chained
if
statements (a special case of nested if
statements, reformatted).
-
Task:
-
Prompt the user to input the percentage they have in a class (as a
float
number between 0 and 100, without the percent sign).
-
Tell them what letter grade they are getting.
-
Use high school standard 90-80-70-60 cutoffs for A, B, C, and D, respectively.
-
Hints:
-
Use a chain of
if
... elif
... elif
... elif
... elif
... else
.
-
(I'm not telling you exactly how many
elif
s you need.)
-
Note that the last block is just
else
rather than
elif
; it catches all situations that don't match any of the previous
cases.
-
Once one of the
if
conditions is true, it will execute the
associated block of code and then skip all the way to after the entire
chain.
-
Before moving on:
Have the professor or TA look at your code for feedback on your formatting.
There are multiple legal ways to format this, but really only one standard way.
Get into the right habit now.
Challenge Lab 2C: Use if
only, or else!
-
Goal:
To think about the expressive power of
if
alone.
-
Task:
Make a copy of the files above and rewrite them to only use
if
,
without using elif
or else
.
-
Before moving on:
Promise yourself to not do this again.
Even though
elif
and else
are technically unnecessary
(i.e., you can accomplish your tasks without them),
these constructs do make code much more organized and understandable.