This is the “first” week of Harvard’s online and free CS50 course. This week’s topic is Conditionals. In the lecture and notes, David Milan covered functions like if
. elif
. else
. or
. and
. bool
. match
. If anyone has ever tinkered with coding, including scratch, they’ve heard of if then or if-else statements. They’re the foundation of software engineering. If this happens, then do that. This was essentially what was covered in this unit. Here are some of the example problems from the lecture:
compare.py:
x = int(input("What's x?"))
y = int(input("What's y? "))
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else :
print("x is equal to y")
You have the user define integers x and y, and then you compare their values. If x is less than y, say so. Elif (aka else if) means that if the first is not true but this is, then print this. Else means that if neither of the preceding conditions are met, then do this.
grade.py:
score = int(input("Score: "))
if score >= 90:
print("grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70 :
print("Grade: C")
elif score>= 60:
print("Grade: D")
else:
print("Grade: F")
Super similar to compare.py, grade.py uses if, Elif, and else loops to verify a score from 1 to 100. If the score is not greater than 90, push it to Elif. If the score is greater than 80, it must be grade B. This code is dependent on the Elif functions; if all the functions were ifs, then, for example, any score greater than 90 would output every grade possible.
parity.py:
def main():
x = int(input("What's x? "))
if is_even(x):
print("Even")
else:
print("Odd")
def is_even(n):
return True if n % 2 == 0 else False
main()
This one is pretty cool. Basically, we are verifying any number x to see if it is odd or even. We define main, and then define a secondary function is_even. We use a super cool function, %, which in this case is not percent but signifying division and outputting the remainder. So any number divided by 2 that doesn’t have a remainder (ie. 0) is even. Also, we denote equals as == instead of just one = because one = denotes assignment. Then we use a boolean statement to print if the number is even. A boolean statement or value means True or False.
house.py:
name = input("what's your name? ")
match name:
case "Harry" | "Hermione" | "Ron":
print("Gryffindor")
case "Draco":
print("Slytherin")
case _:
print("Who?")
Here, we are using a match function to output assignments to different names. This is basically a simpler and more efficient way to output assignments for various inputs in comparison to if and elif functions.
And now, onto the problem sets.
Problem 1: Deep Thoughts
Inspired by the Hitchhiker’s Guide to the Galaxy, Deep Thoughts asks the user what the great question is, and if the user inputs any variation of the answer 42, to answer yes, and if not, answer no. At first, this seemed like a very simple if else problem, and if not, a simpler match problem for different cases. However, I realized that the prompt was asking for any input of varying cases; for example, ” foRTy-TwO” would be a correct answer. Instead of doing what my original guess was, I decided to use concepts from the previous week to strip the string value of its extra whitespace and casefold it so that all the answers were lowercase. This eliminated most of the variations for the match function.
userInput = input("What is the Answer to the Great Question of Life, the Universe, and Everything? ")
userInput = userInput.strip().casefold()
match userInput:
case "42" | "forty two" | "forty-two":
print("yes")
case _:
print("No")
Problem 2: Home Federal Savings Bank
This problem was inspired by an episode of Seinfeld. Essentially, the user will input a greeting; if the greeting begins with hello, they get paid $0; if it starts with an h, they get paid $20; and if it begins with neither, then they get paid $100. In my solution I began with using the .startswith() function to check if the greeting either started with “hello” or “h”. However, in the future, I could’ve simplified the code because I did not need to define new variables for checkHello and check. I could’ve included the strip() and lower() functions in the original input.
userInput = input("Greeting: ")
#strip whitespace and caps
userInput = userInput.strip().lower()
#check if userInput starts with hello
checkHello = userInput.startswith("hello")
#check if the userInput starts with h
checkH = userInput.startswith("h")
if checkHello:
print("$0")
elif checkH:
print("$20")
else:
print("$100")
Problem 3: Extensions
This problem was very straightforward; all you have to do is make an elif for every type of file and print the appropriate media type. I decided to challenge myself. Instead, I used a match case function and wanted to condense all the image file types into one case. To do this, first, I had to split the user input after the “.” to isolate the file type. Then I ran the match case and printed “image/” (I altered it so it produced on the same line. Then it printed the remaining file type from the stripped user input. I ran into a problem where “jpg” file types were outputting “image/jpg” instead of “image/jpeg” so I had to replace that in the original user input. Then I just did regular match cases for the rest of the file types.
userInput = input("File name: ").lower().strip()
userInput = userInput.split('.')[-1].replace("jpg", "jpeg")
match userInput:
case "gif" | "jpg" | "jpeg" | "png":
print("image/", end='', sep='')
print(userInput)
case "pdf":
print("application/pdf")
case "txt":
print("text/plain")
case "zip":
print("application/zip")
case _:
print("application/octet-stream")
Problem 4: Math Interpreter
Math Interpreter was a pretty easy problem. Learning the split function was a little tricky, but once I did, assigning values for x, y, and z was easy. My only issue was that I couldn’t input y as a value and calculate the answer easily. Instead, I had to create match cases for the different variations of y.
userInput = input("Expression: ").split(' ')
#assing x y z to the input. note: x and z are integers(floats because of decimals) and y is the math symbol
x = float(userInput[0])
y = userInput[1]
z = float(userInput[2])
#match case for possible values of y
match y:
case "+":
print(round(x+z, 1))
case "/":
print(round(x/z, 1))
case "-":
print(round(x-z, 1))
case "*":
print(round(x*z, 1))
Problem 5: Meal Time
This one was the most fun of the bunch. Essentially, the user should input a time in the ##:## format, and then the program will tell them if it is breakfast, lunch, or dinner time. The prompt also wants you to define the function as main and a function called convert(). The convert function is the tricky part. Basically, I used a .split() function to split the time into hours and minutes. Then I took the minutes and divided it by 60 to yield a decimal that I could add back to the hours and return it. For example, 7:30 turns into 7.5, and 8:15 turns into 8.25. Then I used if elif functions and equality notation to determine if the time fell in the appropriate ranges.
The problem has an optional challenge (which I did not do) to use standard a.m. p.m. time instead of military time. To do this in the convert function I would create if elif options for a.m. and p.m.. Then I would do all the same to convert from minutes to decimals but for the p.m. times I would add 12 hours.
def main():
userInput = input("What time is it? ")
timeInput = convert(userInput)
if 7.00 <= timeInput <= 8.00:
print("breakfast time")
elif 12.00 <= timeInput <= 13.00:
print("lunch time")
elif 18.00 <= timeInput <= 19.00:
print("dinner time")
def convert(time):
hour, mins = time.split(':', maxsplit=1)
fracMins = round(float(int(mins) / 60), 2)
return int(hour) + fracMins
if __name__ == "__main__":
main()
And well that wraps up my challenge problems for week 1. Looking forward to taking on week 2. Wish me luck. If you have any questions, leave a comment, and I will do my best to answer them.