Extra suplemental materials dedicated to Code in Place Spring 2025 with Stanford University
Topics to be covered:
None
1. User Input Prompt: remember all data types are still in string
def main():
user_name = input("Enter your name: ")
print("Good morning " + user_name)
2. Using Google's Gemini AI
from google import genai
from google.genai import types
########################################################
# Store your API KEY in a text file (gemini_keys.txt) #
# Do not expose or reveal it #
########################################################
def main():
user_question = input("Enter your question here: ")
with open('gemini_keys.txt', 'r') as file:
content = file.read()
GEMINI_API_KEY = content.replace('\n', '')
client = genai.Client(api_key=GEMINI_API_KEY)
response = client.models.generate_content(
model='gemini-2.0-flash-001',
contents=user_question
)
print(f"Response from Gemini: {response.text}")
1. IF-ELIF-ELSE Statement
def main():
MERCURY_GRAVITY = (37.6 / 100)
VENUS_GRAVITY = (88.9 / 100)
MARS_GRAVITY = (37.8 / 100)
JUPITER_GRAVITY = (236 / 100)
SATURN_GRAVITY = (108.1 / 100)
URANUS_GRAVITY = (81.5 / 100)
NEPTUNE_GRAVITY = (114 / 100)
earthWeight = float(input("Enter the object weight: "))
planetName = input("Enter a planet name: ")
if (planetName == "Mercury"):
planetWeight = float(earthWeight) * MERCURY_GRAVITY
elif (planetName == "Venus"):
planetWeight = float(earthWeight) * VENUS_GRAVITY
elif (planetName == "Mars"):
planetWeight = float(earthWeight) * MARS_GRAVITY
elif (planetName == "Jupiter"):
planetWeight = float(earthWeight) * JUPITER_GRAVITY
elif (planetName == "Saturn"):
planetWeight = float(earthWeight) * SATURN_GRAVITY
elif (planetName == "Uranus"):
planetWeight = float(earthWeight) * URANUS_GRAVITY
elif (planetName == "Neptune"):
planetWeight = float(earthWeight) * NEPTUNE_GRAVITY
else:
planetWeight = -1.0 # Why put a negative value here?
2. IF Statement
def main():
MERCURY_GRAVITY = (37.6 / 100)
VENUS_GRAVITY = (88.9 / 100)
MARS_GRAVITY = (37.8 / 100)
JUPITER_GRAVITY = (236 / 100)
SATURN_GRAVITY = (108.1 / 100)
URANUS_GRAVITY = (81.5 / 100)
NEPTUNE_GRAVITY = (114 / 100)
earthWeight = float(input("Enter the object weight: "))
planetName = input("Enter a planet name: ")
planetWeight = -1 # Why put a negative value here?
if (planetName == "Mercury"):
planetWeight = float(earthWeight) * MERCURY_GRAVITY
if (planetName == "Venus"):
planetWeight = float(earthWeight) * VENUS_GRAVITY
if (planetName == "Mars"):
planetWeight = float(earthWeight) * MARS_GRAVITY
if (planetName == "Jupiter"):
planetWeight = float(earthWeight) * JUPITER_GRAVITY
if (planetName == "Saturn"):
planetWeight = float(earthWeight) * SATURN_GRAVITY
if (planetName == "Uranus"):
planetWeight = float(earthWeight) * URANUS_GRAVITY
if (planetName == "Neptune"):
planetWeight = float(earthWeight) * NEPTUNE_GRAVITY
3. MATCH-CASE Statement (Require Python 3.10 or above)
def main():
MERCURY_GRAVITY = (37.6 / 100)
VENUS_GRAVITY = (88.9 / 100)
MARS_GRAVITY = (37.8 / 100)
JUPITER_GRAVITY = (236 / 100)
SATURN_GRAVITY = (108.1 / 100)
URANUS_GRAVITY = (81.5 / 100)
NEPTUNE_GRAVITY = (114 / 100)
earthWeight = float(input("Enter the object weight: "))
planetName = input("Enter a planet name: ")
match planetName:
case "Mercury":
planetWeight = float(earthWeight) * MERCURY_GRAVITY
case "Venus":
planetWeight = float(earthWeight) * VENUS_GRAVITY
case "Mars":
planetWeight = float(earthWeight) * MARS_GRAVITY
case "Jupiter":
planetWeight = float(earthWeight) * JUPITER_GRAVITY
case "Saturn":
planetWeight = float(earthWeight) * SATURN_GRAVITY
case "Uranus":
planetWeight = float(earthWeight) * URANUS_GRAVITY
case "Neptune":
planetWeight = float(earthWeight) * NEPTUNE_GRAVITY
case other:
planetWeight = -1.0 # Why put a negative value here?
1. String Concatenation
- Notice that both "+" and "," can be used interchangably
- Concatenate multiple strings with + (plus) or , (comma)
- All concatenated items have to be converted to the same data type (string)
Examples
planetName = "Mars"; planetWeight = 175.26
print("The weight on " + planetName + ": " + str(marsWeight))
print("The weight on " , planetName + ": " , str(marsWeight))
2. Reference
- Notice the
.format(,)
patten - Unlike concatenation method, this method requires no string conversion
- Use the {} (curly brackets) to place your variable
Examples
planetName = "Mars"; planetWeight = 175.26
print("The weight on {}: {}".format(planetName, planetWeight))
3. F-word
- Notice the f letter inside print()
- Similar to method 2 (reference), but now variable name is placed inside the curly brackets
- Likewise, no variable casting (conversion) is needed
Examples
planetName = "Mars"; planetWeight = 175.26
print(f"The weight on {planetName}: {planetWeight}")
1. Returning a Single Output
Example:
import random
def get_random_number():
return random.randint(1, 100)
def main():
user_number = get_random_number()
print(f"What is user random number? {user_number}")
2. Returning More than One Output
Example:
import random
def get_two_different_random_numbers():
user = 0; comp = 0;
while (user == comp):
user = random.randint(1, 100)
comp = random.randint(1, 100)
if (user != comp):
return user, comp
def main():
user_number, comp_number = get_two_different_random_numbers()
print(f"What is user number: {user_number}. What is computer number: {comp_number}")
3. Accepting Input(s) and Returning Output(s)
Example:
import random
def get_two_different_random_numbers():
user = 0; comp = 0;
while (user == comp):
user = random.randint(1, 100)
comp = random.randint(1, 100)
if (user != comp):
return user, comp
def is_user_guess_correct(user_number, comp_number, user_guess):
if (user_number > comp_number and user_guess == "high"):
return True
elif (user_number < comp_number and user_guess == "low"):
return True
else:
return False
def main():
user_number, comp_number = get_two_different_random_numbers()
print(f"User number is {user_number}")
user_guess = input("Do you think user number is higher or lower (high / low)?")
is_user_win = is_user_guess_correct(user_number, comp_number, user_guess)
if (is_user_win == True):
print("You guessed correctly")
else:
print("Sorry! Your guess is wrong")
None
Visit: 2024_05_31_DataStructures
1. Calculating Factorial
Using Recursion
def factorial_recursion(n):
if (n==0 or n==1):
return 1
return n * factorial_recursion(n-1)
Using Iteration
def factorial_iteration(n):
result = 1;
for i in range(n, 1, -1):
result = i*result
return result
Using Dynamic Programming (List)
def factorial_dynamic_programming(n):
factorial_list = [-1] * (n+1)
factorial_list[0] = 1
for i in range(1, n+1, 1):
factorial_list[i] = factorial_list[i-1] * i
return factorial_list[n]
2. Revisiting Planetary Weight
- Becoming familiar with JSON file format
- Storing, hashing, and accessing dictionary value elements using its key
- List of dictionary vs Dictionary
Using Enumeration and match-case for (planet_conditional.py)
from enum import Enum
class Planet(Enum):
Mercury = "Mercury"
Venus = "Venus"
Mars = "Mars"
Jupiter = "Jupiter"
Saturn = "Saturn"
Uranus = "Uranus"
Neptune = "Neptune"
MERCURY_GRAVITY = (37.6 / 100)
VENUS_GRAVITY = (88.9 / 100)
MARS_GRAVITY = (37.8 / 100)
JUPITER_GRAVITY = (236 / 100)
SATURN_GRAVITY = (108.1 / 100)
URANUS_GRAVITY = (81.5 / 100)
NEPTUNE_GRAVITY = (114 / 100)
def calculate_weight(planetName, earthWeight):
match planetName:
case Planet.Mercury.value:
planetWeight = earthWeight * MERCURY_GRAVITY
case Planet.Venus.value:
planetWeight = earthWeight * VENUS_GRAVITY
case Planet.Mars.value:
planetWeight = earthWeight * MARS_GRAVITY
case Planet.Jupiter.value:
planetWeight = earthWeight * JUPITER_GRAVITY
case Planet.Saturn.value:
planetWeight = earthWeight * SATURN_GRAVITY
case Planet.Uranus.value:
planetWeight = earthWeight * URANUS_GRAVITY
case Planet.Neptune.value:
planetWeight = earthWeight * NEPTUNE_GRAVITY
case _:
planetWeight = -1.0
return planetWeight
def main():
earthWeight = float(input("Enter the object weight: "))
planetName = input("Enter a planet name: ")
planetWeight = calculate_weight(planetName, earthWeight)
print("The name of the planet: " + planetName + " with weight: " + str(planetWeight))
Using Dictionary (planet_dictionary.py)
planet_dict = {
"mercury": 0.376,
"venus": 0.889,
"earth": 1.0,
"mars": 0.378,
"jupiter": 2.36,
"saturn": 1.081,
"uranus": 0.815,
"neptune": 1.14
}
def calculate_weight_alternative(target_planet, earth_weight):
planet_name = target_planet.lower()
planet_constant = -1.0
if planet_dict[ planet_name ] is not None:
planet_constant = planet_dict[planet_name]
planet_weight = planet_constant * earth_weight
return planet_weight
def main():
earth_weight = float(input("Enter the object weight: "))
planet_name = input("Enter a planet name: ")
planet_weight = calculate_weight_alternative(planet_name, earth_weight)
print("The name of the planet: " + planet_name + " with weight: " + str(planet_weight))
3. Plotting Regression Line
Using List of Dictionary (snow_plot.py)
from matplotlib import pyplot as plt
snow_yield_dictionary =
[{"Snow":
[23.1, 32.8, 31.8, 32.0, 30.4, 24.0, 39.5, 24.2, 52.5, 37.9, 30.5, 25.1, 12.4, 35.1, 31.5, 21.1, 27.6]
},
{"Yield":
[10.5, 16.7, 18.2, 17.0, 16.3, 10.5, 23.1, 12.4, 24.9, 22.8, 14.1, 12.9, 8.8, 17.4, 14.9, 10.5, 16.1]
}]
def plot_the_curve():
snow_dictionary = snow_yield_dictionary[0]
yield_dictionary = snow_yield_dictionary[1]
snow_list = snow_dictionary["Snow"]
yield_list = yield_dictionary["Yield"]
plt.title("Plot of Snow vs Yield"); plt.xlabel("Snow"); plt.ylabel("Yield")
plt.scatter(snow_list, yield_list, c='blue', marker='H')
plt.show()
plt.savefig('plot_of_snow_vs_yield.png')
def main():
plot_the_curve()