COMP1701-004
fall 2023
lec-06
The Fooooture




any A2 questions?
A2 - hints
-
Don't skip the "understand the problem" step.
-
At the very least, be able to figure out how the results in the screenshot were obtained.
-
Let's take a run through the rubric.
-
Take a look at the coding guidelines.
-
The big hint is a big hint, especially taken in context of lab-05....
questions from last time
none!
onlinequestions.org
202304170106RECALL
connections
string
type
operator
input
output
syntax
variable
f-string

Generate a reasonable sentence in your head that connects at least 2 of the terms.
Do as many sentences as you can in 1 minute.
let's talk about these things today:
⦾ citing stuffs
⦾ back to f-strings
⦾ constants
⦾ comments
citing stuffs
The following content is from Patrick Perri's slides on the topic, provided with his consent.
citing stuffs
Why Cite?
It's about Academic Integrity & Intellectual Property
Citing (also called referencing) is a way to acknowledge the work (ideas, images, code etc.) of others [1].
[2] “Academic Misconduct”, Office of Student Community Standards, MRU, 2022. [Online.] Available: https://www.mtroyal.ca/CampusServices/CampusResources/StudentCommunityStandards/academic-misconduct/index.htm
We cite:
- To show respect to the creators (which we hope to deserve ourselves!)
- To support the credibility of our work
- To support the reputation of MRU and its graduates
- "Without integrity, academic qualifications cannot be relied upon, research cannot be trusted, and degrees, diplomas, and certificates lose their value" [2].
[1] “Citations Styles and Resources” Mount Royal University Library, 2020, [Online.] Available: https://library.mtroyal.ca/citations
citing stuffs
Academic Integrity
“MRU students are expected to consistently submit original work, give credit to other peoples' ideas and work and complete all submissions independently and honestly”[1].
[1] “Academic Misconduct”, Office of Student Community Standards, MRU, 2022. [Online.] Available: https://www.mtroyal.ca/CampusServices/CampusResources/StudentCommunityStandards/academic-misconduct/index.htm
- Plagiarism
- Any and all uses of another’s idea, data, image, words or code presented as one’s own. Including re-submitting previously assessed work!
- Cheating
- Using unauthorized materials (e.g. prohibited programming structures, cheat sheets etc.)
- Outsourcing (people, services or AI)
- Unapproved collaboration.
What counts as misconduct?
citing stuffs
Example of what to do
# Finds the median of some numbers.
# Developed in conversation with S Wright (Oct 2022)
# and using ideas from:
# “Finding Mean, Median, Mode in Python without libraries”
# https://www.geeksforgeeks.org/finding-mean-median-mode-in-python-without-libraries/
theNumbers= [1, 2, 3, 4, 5]
n = len(theNumbers)
theNumbers.sort()
if n % 2 == 0:
median1 = theNumbers[n//2]
median2 = theNumbers[n//2 - 1]
median = (median1 + median2)/2
else:
median = theNumbers[n//2]
# End of S Wright and geeksforgeeks inspired code
print("My median is: " + str(median))Things I don't expect you to cite
- Documentation
- The current assignment
citing stuffs
What NOT to do
from collections import Counter
# list of elements to calculate mode
n_num = [1, 2, 3, 4, 5, 5]
n = len(n_num)
data = Counter(n_num)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
if len(mode) == n:
get_mode = "No mode found"
else:
get_mode = "Mode is / are: " + ', '.join(map(str, mode))
print(get_mode)
Say you were tasked to create a function to find the mode (lowest value if more than one) of a list of values, and to NOT use dictionaries, outside modules, nor list comprehensions.
Then you hand in this...
Without citation, this is 0% and a write-up.
With citation, it's "just" a 0%.
Oh look, a dictionary.
Oh look, a list comprehension.
Oh look, an outside module.
Your code must not use any Python techniques that have not yet been covered in class.
This means it cannot use:
-
older style string formatting (% or .format)
-
if/else
-
loops
-
lists, tuples, dictionaries, or other data types beyond int, float, and str
-
try/except
-
custom classes
-
modules aside from the math module
-
This is not a complete list!
|
Why not? There are many Python solutions to problems such as these out there in the wild, and if I see advanced concepts in your code, I have no way of knowing that you understand what you are writing. If you have prior Python experience, consider it a challenge to solve the problem using a limited set of tools. |
A2
Again, without citation, doing any of these means 0% and a write-up.
With citation, it's just 0%.
This has changed - you don't need the math module.
back to f-strings
they produce strings
this is syntactically ok, but goofy as all get-out
print(f'Why are you doing this? Stop it immediately, ya goof.')# assume we have these variables
width = 6
height = 5
area = width * heightLet's print the following 3 different ways:
The area of a 6 x 5 rectangle is 30.
One way to use them
print("The area of a", width, "x", height, "rectangle is", area, "\b.")🙋🏻♂️❓🙋🏻♀️How would you do it with just print()?
print("The area of a " + str(width) + " x " + str(height) + " rectangle is " + str(area) + ".")🙋🏻♂️❓🙋🏻♀️How would you do it with print() and concatenation?
print(f"The area of a {width} x {height} rectangle is {area}.")🙋🏻♂️❓🙋🏻♀️How would you do it with print() and an f-string?
JP! Show the reverse engineering method!
Yikes. Easy to make make mistakes with this mess!
So beautiful! Expressive! Life-altering!
Why? And ew.
They're great for tables
p1_name = 'luX0R'
p1_score = 4
p2_name = 'MizKittyKitty'
p2_score = 12
print("12345678901231234567")
print(f"{'nickname':<13}{'score':>7}")
print("-" * 20)
print(f"{p1_name:<13}{p1_score:>7}")
print(f"{p2_name:<13}{p2_score:>7}")nickname score
--------------------
luX0R 4
MizKittyKitty 12
12345678901231234567
13 characters wide
7 chars wide
note everything adds up to 20
what if we remove the > here?
how about here?
YOUDO
Now YOU make a table that looks like this:
flight gate status -------------------------- AC203 C50 DEPARTED WS105 D75 FINAL CALL Y90153 C58 PREBOARDING
These dashes come in handy....
room_width_ft = 10
room_length_ft = 20
COST_PER_SQ_FT = 2
print(f'It will cost {room_width_ft * room_length_ft * COST_PER_SQ_FT} for that room.')In f-strings, things in { } are evaluated, then turned into strings.
Not a fan.
room_width_ft = 10
room_length_ft = 20
COST_PER_SQ_FT = 2
total_cost = room_width_ft * room_length_ft * COST_PER_SQ_FT
print(f'It will cost {total_cost} for that room.')We'll talk about this kind of CONSTANT later in the lecture.
Much better.
🙋🏻♂️❓🙋🏻♀️How could we improve the readability?
This is convenient, but can lead to hard-to-read code.
The f stands for frustrating format.
One of the more common things you can format is numbers.
Insert Fascinating Demo Here
pro tip
find (or better yet, build) cheat sheets for stuff like this
This one seems pretty good:
https://cheatography.com/brianallan/cheat-sheets/python-f-strings-basics/


Code is meant to be run.
But it's also meant to be read.
Comments and constants help make our code more expressive.
comments
comments
A comment is some text that we place in source code to communicate something useful to the reader.
Comments are ignored by the interpreter/compiler - they don't "run".
comments
Python comment syntax
# need to do this, or things explode
safety_valve_reading = 0
# legal department says we must do this
list_of_guarantees = ""
# uses Triangle Numbers
# https://en.wikipedia.org/wiki/Triangular_number
score = (n * (n + 1)) / 2Pro Tip
use ctrl+/ to comment and uncomment lines quickly in VS Code
num_gems_as_text = input("Enter the number of gems: ")
num_gems = int(num_gems_as_text)
num_players_as_text = input("Enter the number of players: ")
num_players = int(num_players_as_text)Another Pro Tip
Use "comments" to temporarily disable lines of code
num_gems_as_text = "23" # input("Enter the number of gems: ")
num_gems = int(num_gems_as_text)
num_players_as_text = "3" # input("Enter the number of players: ")
num_players = int(num_players_as_text)Do you REALLY like to type THAT MUCH?!?
🙋🏻♂️❓🙋🏻♀️Why did I put in the quotes ("23")?
🙋🏻♂️❓🙋🏻♀️What happens when I run this?
comments
You can also use comments to temporarily sketch out an algorithm before you start writing code
# get first name
# get last name
# get weight in kg
# calculate weight on Jupiter
# display results# get first name
first_name = input("What's your first name? ")
# get last name
last_name = input("What's your last name? ")
# get weight in kg on Earth
earth_weight_in_kg = float(input("How much do you weigh, in kg? "))
# calculate weight on Jupiter
# use gravity multiplier
# https://nssdc.gsfc.nasa.gov/planetary/factsheet/planet_table_ratio.html
jup_weight_in_kg = earth_weight_in_kg * 2.36
# display results
print("Hi,", first_name, last_name, "!")
print("You would weigh", jup_weight_in_kg, "kg on Jupiter!")...but delete unneeded comments when you're done!
examples of
bad comment habits
# sets sum to 0
sum = 0
# print message
print("Hello - welcome to the jungle.")
# add 2 numbers to get sum
sum = first_num + second_num
# I was SOOOO drunk when I wrote this
arglebargle = fart_factor ** 3
# -----------------------------------
# -----------------------------------
# we don't use this any more
# flight = ""
# crew = 0
What's wrong with these?
What's wrong with this?
What's wrong with this?
What's wrong with this?
constants
constants
A constant is a variable whose little box in memory location should NOT be changed.
// JS - try this in a browser console
const PI = 3.14;
PI = -1; // say WHAAAAT?!?!🙋🏻♂️❓🙋🏻♀️What does this look like in memory?
In most languages you'll encounter (like C++, JavaScript, and Java), the language will enforce this "no changes, dude" policy.
constants
# in Python SCREAMING_SNAKE_CASE means
# this variable should be considered
# a constant
PI = 3.14
diameter = 12
circumference = PI * diameter
# buuuuuuuuut...
PI = -1
# so much for followin' the rules
# madness!
circumference = PI * diameter In fact, you can't label a variable as constant in Python!
But Python...doesn't roll that way.
Instead, we rely on convention to visually indicate that a variable shouldn't be changed - but folks can totally ignore that convention and do the unthinkable.
constants
Despite this, constants are worth their weight in gold for communication purposes.
balance = 1.04 * balancebalance = (ANNUAL_INTEREST_RATE) * balancesips_available = 4.3 * 17sips_available = AVG_SIPS_PER_ML * ML_PER_CUP🙋🏻♂️❓🙋🏻♀️What memorable term did we use for THIS_KIND_OF_CASE?
constants
In the name of all that is holy, do NOT do this:
triangle_base = 5
triangle_height = 7
ONE = 1
TWO = 2
area = (ONE / TWO) * (triangle_base * triangle_height)If you cannot provide a MEANINGFUL name to a magic number, do NOT make it a constant. Please. I beg of you.
Spot the magic numbers - and give them names, if you feel they should be turned into a constant
YOUDO
base = 12
height = 3
area = (1/2) * base * heightplaylist_duration_in_minutes = 14.3
playlist_duration_in_seconds = 60 * playlist_duration_in_minutes
num_songs_on_playlist = 5
avg_duration_per_song_in_seconds = playlist_duration_in_seconds / num_songs_on_playlistnum_full_cartons = 4
num_loose_eggs = 2
total_num_eggs = (12 * num_full_cartons) + 2weighted_avg_earth_radius = (1/3) * (2 * 1378137) + 6356752print(f"{'nickname':<13}{'score':>7}")
print("-" * 20)A Gotcha
If you want to use constants in an f-string, you can...but you have to wrap them in curly braces, so that the constants are evaluated!
COL_1_WIDTH = 14
print(f'''{'Name':COL_1_WIDTH} ''')COL_1_WIDTH = 14
print(f'''{'Name':{COL_1_WIDTH}} ''')RECAP RECAP
What did we talk about?
lec-06
By Jordan Pratt
lec-06
f-strings | comments | constants
- 302