CS 111 f21 — Functions and Conditionals part 3
Table of Contents
1 Practice
- Write an
average_grade
function that takes three numeric grades as parameters and returns their average1 - Function mysteries
- Write an absolute value function: takes one number as a parameter, returns the positive version of that number (hint: if
x
is negative,-x
is the positive version).4 What will be printed?5
def km_to_miles(km): miles = km * 1.61 print(miles) running = 10 if km_to_miles(running) < 26.2: print("not a marathon")
- Given a player's guess and a secret number, print
"cold"
"warm"
or"lava"
(or"WINNER"
if the guess is correct)6- Assume you have a variable
guess
with the player's guess and a variablesecret
with the secret number - Up to you to choose how close
"lava"
is, etc. - Make sure to only print one hint
- Assume you have a variable
2 User Input
built-in input function, takes a string argument to use as the prompt
name = input("What is your name? ")
input
returns a string (text), so if we need it as a number (e.g., a player guessing a number), we have to convert it- Python distinguishes between integers (whole numbers) and floating point (real or decimal numbers)
- Why? The computer has to represent and interact with these two types of data very differently
- Take CS 208 to find out more!
- Named
int
andfloat
in Python float
can be treacherous!(2.5*0.1)*1.5 == 2.5*(0.1*1.5)
isFalse
0.1*1.5*2.5 == 2.5*0.1*1.5
isFalse
- computer can only approximate
We can use the built-in functions
int
andfloat
to convert text to a number:guess = int(input("Enter your guess: "))
3 Randomness
- As you've seen in Lab 1, use Python's
random
module- pseudo-random number generator (deterministic, repeats eventually)
- series of numbers based on initial seed
- will eventually repeat: period of \(2^{19937}-1\)
To get a random number between
lowest
andhighest
:import random number = random.randint(lowest, highest)
Footnotes:
1
def average_grade(grade1, grade2, grade3): return (grade1 + grade2 + grade3) / 3
2
8 12
3
20
4
def abs(x): if x < 0: return -x else: return x
5
It will print 16.1
and then encounter a TypeError
6
difference = abs(secret - guess) if difference == 0: print("WINNER") elif difference < 5: print("lava") elif difference < 10: print("warm") else: print("cold")