Problem 1
# median test grade of a class
classScores = [96,94,83,85,85,85,87,79,88,76,79,81,93,81,66,93,96,83,83,84,100,96,85,79,79,79,79,13,95,55]
n = len(classScores) # size of class
classScores.sort() # simple, default sorting algorithm
if n % 2 == 0:
median = (classScores[int(n/2)-1]+classScores[int(n/2)])/2 # average the middle two elements
else:
median = classScores[n//2] # n//2=(n-1)/2 here
print(f"The median score is {median}")
The median score is 83.5
Problem 2
# simple game using random numbers
# does not use global variables, but passes in guessCount every time it is called
import random
num = random.randint(1,1000)
def userGuess(guessCount): # guessCount will be initialized at 0 at the end
try:
guess = int(input("Enter a guess between 1 and 1000!"))
validate(guess,guessCount) # use the guess and pass in guessCount to see if user input is right
except ValueError: # when an integer is not entered
print("Please try again.")
userGuess(guessCount) # try it again
def validate(guess, guessCount): # arguments of user's guess and guessCount
guessCount += 1 # add one to the guessCount no matter what
if guess > num: # cases and recursion if the guess is not right
print("Too high.")
userGuess(guessCount)
elif guess < num:
print("Too low.")
userGuess(guessCount)
else:
print("Correct! Good job!")
print(f"You guessed {guessCount} times.") # print out how many guesses the user made
print("I'm thinking of a number between 1 and 1000. Can you guess it?")
userGuess(0)
I'm thinking of a number between 1 and 1000. Can you guess it?
Too high.
Too low.
Too high.
Too high.
Too low.
Too high.
Too high.
Too high.
Too high.
Too high.
Too high.
Too high.
Too low.
Too high.
Too high.
Correct! Good job!
You guessed 16 times.