Python Pair Showcase

Python IO

import getpass # for getpass.getuser() to get username
import random # to randomize the order of the questions

print("Hi " + getpass.getuser()) 

correct = 0 # number of correct questions
i = 1 # used to iterate through the dictionary

# dictionary of questions
# key - question
# value - answer
questions = {
    "What python command will output to console?": "print",
    "What python command asks for input from the user?": "input",
    "What python command defines a function?": "def"
}

keys = list(questions.keys()) # sets the keys of a dictionary into a list
random.shuffle(keys) # shuffles the questions for funzies

letters = ['F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A', 'A']

# ask question
# input - the question and the question number
# output - the response to the question
def ask_question(question, i):
    print(f"Question{str(i)} : " + question) # asks Question (number): question
    msg = input() # sets msg as the response
    return msg

# compares the response to the answer
# input - the response and the answer
# output - 0 if incorrect, 1 if correct
def check_response(question, response):
    if questions[question] == response:
        print("correct")
        return 1
    else:
        print(f"incorrect, the answer was \"{questions[question]}\"") # gives user the answer
        return 0

for question in keys:
    response = ask_question(question, i)
    if check_response(question, response): # if correct
        correct += 1 # number of correct
    i += 1 # question number
    
print(f"score: {str(correct)}/{str(len(questions))} or {str(int(correct/len(questions)*100))}%") # correct / number of questions

print("letter grade: " + str(letters[int(correct/len(questions)*10)]))

Python Tricks

import statistics # used for mean, median, mode
import os # output the current directory name

print("Input numbers spaced by commas:", end=" ")

try: # in case of ValueError
    values = input().split(",") # inputted values
    for i in range(len(values)): # convert list fom string to float
        values[i] = float(values[i])

    print("Mean: " + str(statistics.mean(values)))
    print("Median: " + str(statistics.median(values)))
    print("Mode: " + str(statistics.mode(values)))
    print("Range: " + str(max(values) - min(values)))
    
except ValueError: # if the user inputted a non-number character
    print("Please enter a list of numbers seperated by commas")

print("current directory:", end=" ")
os.system("pwd") # output current directory name
Input numbers spaced by commas: 2, 5, 6
Mean: 4.333333333333333
Median: 5.0
Mode: 2.0
Range: 4.0
current directory: /home/arthurliu/vscode/csp/_notebooks





0