Formatted Output
Task
Write a program that produces the following output with proper formatting:
Expected Output
2 2:00 - 6:00 a.m.
Solution Code
Key Concept
The \n escape sequence creates a new line. Spaces at the beginning of strings create indentation for proper formatting.
Input & Story Generation
Task
Read four values from input and use them to generate a short story.
Example Input
Solution Code
whole_number, 'different types of', plural_noun)
Key Concept
The input() function reads user input as strings. Multiple values can be printed in one print() statement separated by commas.
Currency Conversion
Task
Convert counts of quarters, dimes, nickels, and pennies to dollars and cents.
Coin Values
Solution Code
(nickels * 5) + pennies
Key Concepts
int(input())converts string input to integer- f-string formatting:
f'${dollars:.2f}'formats to 2 decimal places - Currency calculations require careful conversion between units
Gas Cost Calculator
Task
Calculate gas cost for 20, 75, and 500 miles given miles/gallon and dollars/gallon.
Formula
Solution Code
Key Concepts
float(input())reads decimal numbers- Multiple calculations with the same formula can be structured efficiently
:.2fformats floating-point numbers to two decimal places
Pattern Printing (Arrow)
Task
Print a right-facing arrow using two input characters for the body and head.
Example Input
Solution Code
Key Concepts
- String repetition:
'*' * 6creates****** - String concatenation:
'a' + 'b'createsab - Spaces for indentation: Spaces create the arrow shape by positioning the head
Phone Number Formatting
Task
Read a 10-digit phone number as a single integer and output it in formatted form: (area_code) prefix-line_number.
Example Input & Output
Solution Code
Key Concepts
- Integer division (//): Gets the quotient without remainder
- Modulus operator (%): Gets the remainder after division
- Combined operations: Use both to extract specific digits from a number
Find Smallest of Three
Task
Read three integers from input and output the smallest value using the min() function.
Test Cases
| Input | Output |
|---|---|
| 7, 15, 3 | 3 |
| 29, 6, 17 | 6 |
| 3, 2, 1 | 1 |
| 7, 7, 7 | 7 |
Solution Code
Key Concepts
- Built-in min() function: Returns the smallest of the given arguments
- Simple approach: Using min() is cleaner than nested if statements
- Works with any number of values: min() can handle 2, 3, or more values
Coin Change Calculator
Task
Convert total cents to the fewest number of coins (dollars, quarters, dimes, nickels, pennies) with proper pluralization.
Example: Input 45
2 Dimes
Solution Code
Key Concepts
- Greedy algorithm: Always use the largest coin possible first
- Compound assignment:
total_cents %= 25updates the remaining amount - Conditional pluralization: Add "s" only when count ≠ 1 (special case for "pennies")
Increment by 5
Task
Read two integers and output the first integer and all multiples of 5 from the first up to the second integer.
Example Input & Output
Solution Code
Key Concepts
- While loop: Continues while condition is true
- Loop variable:
currenttracks the current number - end parameter:
print(value, end=' ')prints with space instead of newline - Input validation: Check for invalid cases before processing
Reverse Text Lines
Task
Read lines of text from input until "done" or "d" is entered, then output each line in reverse order.
Example Input & Output
hey
done
yeh
Solution Code
Key Concepts
- Infinite loop:
while True:runs until break - String slicing:
[::-1]reverses a string - Case-insensitive comparison:
.lower()converts to lowercase - Break statement: Exits the loop when termination condition is met
Fibonacci Sequence
Task
The Fibonacci sequence begins with 0 and then 1 follows. All subsequent values are the sum of the previous two. Complete the fibonacci() function, which has an index n as parameter and returns the nth value in the sequence. Any negative index values should return -1.
Example Input & Output
Solution Code
Key Concepts
- Edge cases: Handle negative inputs (return -1) and base cases (n=0, n=1)
- For loop iteration: Use a loop to calculate Fibonacci numbers without recursion
- State tracking: Keep track of the previous two values to calculate the next one
- Space efficiency: O(1) space complexity using only two variables instead of storing all values
- Sequence shift: Update prev2 and prev1 after each calculation for the next iteration
List Average Calculator
Task
Complete the calc_average() function that has an integer list parameter and returns the average value of the elements in the list as a float. Handle the case of an empty list by returning 0.0.
Example Input & Output
Solution Code
Key Concepts
- List iteration: Use a for loop to access each element in the list
- Empty list check: Always handle edge cases like empty lists to avoid division by zero
- Float division: In Python 3, division (/) always returns a float, even with integer operands
- Sum calculation: Accumulate total using
total += numor use built-insum()function - List length: Use
len(nums)to get the number of elements - Input parsing: Convert space-separated string input to list using
input_str.split()andint(x)
Character Counter & Whitespace Remover
Task
(1) Prompt the user to enter a string of their choosing. Output the string.
(2) Complete the get_num_of_characters() function, which returns the number of characters in the user's string. Use a for loop.
(3) Extend the program by calling the get_num_of_characters() function and output the returned result.
(4) Extend the program further by implementing the output_without_whitespace() function. output_without_whitespace() outputs the string's characters except for whitespace (spaces, tabs). Note: A tab is '\t'.
Example Input & Output
Solution Code
Key Concepts
- String iteration: Use
for char in input_str:to process each character - Character counting: Initialize a counter variable and increment it for each character
- Whitespace detection: Check if character is space
' 'or tab'\t' - Output formatting: Use
print(..., end="")to print without newline - Precise formatting: The auto-grader requires exact whitespace formatting including blank lines
- Tab character: Represented as
'\t'in Python strings
Palindrome Checker
Task
A palindrome is a word or a phrase that is the same when read both forward and backward. Write a program whose input is a word or phrase, and that outputs whether the input is a palindrome. Ignore spaces in the comparison.
Example Input & Output
Solution Code
Key Concepts
- String cleaning: Remove spaces with
.replace(" ", "")and convert to lowercase with.lower() - String reversal: Use slicing
[::-1]to reverse a string - Palindrome logic: A string is a palindrome if it equals its reverse
- Case-insensitive comparison: Convert to lowercase before comparing to handle cases like "Race car"
- Space handling: Remove spaces before comparison to handle phrases like "never odd or even"
- Input trimming: Use
.strip()to remove leading/trailing whitespace
Car Wash Price Calculator
Task
Write a program to calculate the total price for car wash services. A base car wash is $10. A dictionary with each additional service and the corresponding cost has been provided. Two additional services can be selected. A '-' signifies an additional service was not selected.
Output all selected services, according to the input order, along with the corresponding costs and then the total price for all car wash services.
Note: The inputs are two separate lines. Each input() reads one line from the user.
Example Input & Output
Wax
Base car wash -- $10
Tire shine -- $2
Wax -- $3
----
Total price: $15
-
Base car wash -- $10
Rain repellent -- $2
----
Total price: $12
-
Base car wash -- $10
----
Total price: $10
Solution Code
Key Concepts
- Dictionary usage: Access service costs using
services[service_choice] - Multiple inputs: Read two separate lines with two
input()calls - Input validation: Check for '-' to determine if a service was selected
- Running total: Start with base price and add costs of selected services
- Formatted output: Print services in input order with costs and formatted total
- Edge cases: Handle cases where no services are selected (both inputs are '-')
- String formatting: Use f-strings for clean output formatting
- Dictionary syntax: Create and access dictionary values with key-value pairs
Integer Division with Exception Handling
Task
Write a program that reads integers user_num and div_num as input, and output the quotient (user_num divided by div_num).
Use a try block to perform all the statements. Use an except block to catch any ZeroDivisionError and output an exception message. Use another except block to catch any ValueError caused by invalid input and output an exception message.
Note: Do not include code to throw any exception in the program.
ZeroDivisionError is thrown when a division by zero happens.ValueError is thrown when a user enters a value of different data type than what is defined in the program.//) as shown in examples.Example Input & Output
3
0
5
abc
Solution Code
Key Concepts
- Try-except blocks: Use
tryto execute code that might raise exceptions - ZeroDivisionError: Exception raised when dividing by zero
- ValueError: Exception raised when input can't be converted to the expected type
- Integer division: Use
//operator for integer division (truncates decimal part) - Multiple except blocks: Handle different exception types separately
- Error message parsing: Extract the specific invalid value from ValueError message
- String manipulation: Use
.split()and.strip()to format error messages - Conditional extraction: Check if error message contains ": " before attempting to split
- Exception object: Use
as eto access the exception object and its message
Steps to Miles Converter
Task
A pedometer treats walking 2,000 steps as walking 1 mile. Write a steps_to_miles() function that takes the number of steps as a parameter and returns the miles walked.
The steps_to_miles() function throws a ValueError object with the message "Exception: Negative step count entered." when the number of steps is negative.
Complete the main() program that reads the number of steps from a user, calls the steps_to_miles() function, and outputs the returned value from the steps_to_miles() function. Use a try-except block to catch any ValueError object thrown by the steps_to_miles() function and output the exception message.
Output formatting: Each floating-point value with two digits after the decimal point using: print(f'{your_value:.2f}')
raise ValueError("Exception: Negative step count entered.") for negative stepsExample Input & Output
Solution Code
Key Concepts
- Custom exceptions: Use
raise ValueError("message")to throw exceptions - Function design: Create functions that validate input and raise exceptions for invalid data
- Floating-point formatting: Use
f'{value:.2f}'to format numbers with 2 decimal places - Exception propagation: Exceptions raised in functions propagate to calling code
- Input validation: Check for negative values before performing calculations
- Division operation: Use
/for floating-point division (not//) - Main guard: Use
if __name__ == '__main__':for executable code - Exception message: Pass custom message when raising ValueError
- Edge cases: Handle zero steps (not negative, returns 0.00)
Synonyms Dictionary from Text Files
Task
Given a set of text files containing synonyms for different words, complete the main program to output the synonyms for a specific word. Each text file contains synonyms for the word specified in the file's name, and each row within the file lists the word's synonyms that begin with the same letter, separated by a space.
The program reads a word and a letter from the user and opens the text file associated with the input word. The program then stores the contents of the text file into a dictionary predefined in the program. Finally the program searches the dictionary and outputs all the synonyms that begin with the input letter, one synonym per line, or a message if no synonyms that begin with the input letter are found.
Hints: Use the first letter of a synonym as the key when storing the synonym into the dictionary. Assume all letters are in lowercase.
Example Input & Output
c
coach
cultivate
a
j
joyous
jubilant
a
Solution Code
Key Concepts
- File I/O: Use
with open(filename, 'r') as file:for safe file handling - Dynamic filename generation: Concatenate word with '.txt' to create filename
- Dictionary initialization: Check if key exists before accessing:
if first_char not in synonyms: - String processing: Use
.strip()to remove whitespace and.split()to separate words - Character extraction: Get first character with
synonym[0] - Case normalization: Use
.lower()to ensure consistent lowercase keys - List operations: Use
.append()to add items to dictionary lists - Exception handling: Catch
FileNotFoundErrorfor missing files - Dictionary lookup: Check both key existence and non-empty list:
if letter in synonyms and synonyms[letter]: - Context manager: Files automatically close when exiting the
withblock - File reading:
.readlines()returns a list of all lines in the file - Input validation: Use
.strip()on user input to remove extra whitespace
Word Frequencies from CSV File
Task
Write a program that first reads in the name of an input file and then reads the file using the csv.reader() method.
The file contains a list of words separated by commas. Your program should output the words and their frequencies (the number of times each word appears in the file) without any duplicates.
Note: There is a newline at the end of the output.
Example Input & Output
cat 2
man 2
hey 2
dog 2
boy 2
Hello 1
woman 1
Cat 1
banana 2
orange 1
grape 1
Solution Code
Key Concepts
- CSV module: Import
csvfor structured file reading - csv.reader(): Method that automatically parses comma-separated values
- Dictionary for counting: Use dictionaries to track frequencies of unique items
- String cleaning: Use
.strip()to remove leading/trailing whitespace - Case sensitivity: Original case is preserved ("Hello" ≠ "hello")
- File handling: Use
with open() as file:for automatic file closure - Error handling: Catch
FileNotFoundErrorfor missing files - Dictionary iteration: Use
.items()to get key-value pairs - Frequency counting: Pattern:
if key in dict: dict[key] += 1 else: dict[key] = 1 - Alternative approach: Could use
dict.get(key, 0) + 1for cleaner code - CSV structure: File contains one row with all comma-separated words
- Nested loops: Outer loop for rows, inner loop for words in each row
- Output format: Word and count separated by space, each on new line
- Input validation: Use
.strip()on filename input
Thesaurus - Synonyms Dictionary
Task
Given a set of text files containing synonyms for different words, complete the main program to output the synonyms for a specific word. Each text file contains synonyms for the word specified in the file's name, and each row within the file lists the word's synonyms that begin with the same letter, separated by a space.
The program reads a word and a letter from the user and opens the text file associated with the input word. The program then stores the contents of the text file into a dictionary predefined in the program. Finally the program searches the dictionary and outputs all the synonyms that begin with the input letter, one synonym per line, or a message if no synonyms that begin with the input letter are found.
Hints: Use the first letter of a synonym as the key when storing the synonym into the dictionary. Assume all letters are in lowercase.
Example Input & Output
c
civilize coach cultivate
develop discipline drill
edify enlighten exercise explain
foster
improve indoctrinate inform instruct
mature
nurture
rear
school
train tutor
coach
cultivate
a
j
joyous
jubilant
o
aim
aspiration
Solution Code
Key Concepts
- File I/O: Use
with open(filename, 'r') as file:for safe file handling - Dynamic filename generation: Concatenate word with '.txt' to create filename
- Dictionary initialization: Check if key exists before accessing:
if first_char not in synonyms: - String processing: Use
.strip()to remove whitespace and.split()to separate words - Character extraction: Get first character with
synonym[0] - Case normalization: Use
.lower()to ensure consistent lowercase keys - List operations: Use
.append()to add items to dictionary lists - Exception handling: Catch
FileNotFoundErrorfor missing files - Dictionary lookup: Check both key existence and non-empty list:
if letter in synonyms and synonyms[letter]: - Context manager: Files automatically close when exiting the
withblock - File reading:
.readlines()returns a list of all lines in the file - Input validation: Use
.strip()on user input to remove extra whitespace - File format: Each line contains synonyms starting with same letter, space-separated
- Dictionary structure: First letter → List of synonyms starting with that letter
Python Playground
Try out Python code directly in your browser. Type your code below and click "Run Code" to see the output.
Code Editor
Quick Examples:
Output
Input
If your code uses input(), enter values here (one per line):
** This simulates the input() function. Each line will be used sequentially for input() calls.
Python Programs
List of all program files for each example problem