1

Formatted Output

print() function

Task

Write a program that produces the following output with proper formatting:

Expected Output

1 NO PARKING
2 2:00 - 6:00 a.m.

Solution Code

# Using escape sequences for formatting
print(' NO PARKING\n2:00 - 6:00 a.m.')

Key Concept

The \n escape sequence creates a new line. Spaces at the beginning of strings create indentation for proper formatting.

2

Input & Story Generation

input() function

Task

Read four values from input and use them to generate a short story.

Example Input

first_name
James
generic_location
store
whole_number
2
plural_noun
apples

Solution Code

# Read user input
first_name = input()
generic_location = input()
whole_number = input()
plural_noun = input()
# Output story with variables
print(first_name, 'went to', generic_location, 'to buy',
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.

3

Currency Conversion

Type Conversion

Task

Convert counts of quarters, dimes, nickels, and pennies to dollars and cents.

Coin Values

25¢
Quarter
10¢
Dime
Nickel
Penny

Solution Code

# Read coin counts
quarters = int(input())
dimes = int(input())
nickels = int(input())
pennies = int(input())
# Calculate total cents
total_cents = (quarters * 25) + (dimes * 10) +
(nickels * 5) + pennies
# Convert to dollars
dollars = total_cents / 100.0
# Format output
print(f'Amount: ${dollars:.2f}')

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
4

Gas Cost Calculator

Float Arithmetic

Task

Calculate gas cost for 20, 75, and 500 miles given miles/gallon and dollars/gallon.

Formula

Cost = (Distance ÷ MPG) × Price per gallon
Calculate gallons needed first, then multiply by price

Solution Code

# Read inputs
miles_per_gallon = float(input())
dollars_per_gallon = float(input())
# Calculate gallons needed
gallons_20 = 20 / miles_per_gallon
gallons_75 = 75 / miles_per_gallon
gallons_500 = 500 / miles_per_gallon
# Calculate costs
cost_20 = gallons_20 * dollars_per_gallon
cost_75 = gallons_75 * dollars_per_gallon
cost_500 = gallons_500 * dollars_per_gallon
# Output formatted results
print(f'{cost_20:.2f} {cost_75:.2f} {cost_500:.2f}')

Key Concepts

  • float(input()) reads decimal numbers
  • Multiple calculations with the same formula can be structured efficiently
  • :.2f formats floating-point numbers to two decimal places
5

Pattern Printing (Arrow)

String Manipulation

Task

Print a right-facing arrow using two input characters for the body and head.

Example Input

Body Character
*
base_char
Head Character
#
head_char

Solution Code

# Read character inputs
base_char = input()
head_char = input()
# Create each row of the arrow
row1 = ' ' + head_char
row2 = base_char * 6 + head_char * 2
row3 = base_char * 6 + head_char * 3
# Print the arrow
print(row1)
print(row2)
print(row3)
print(row2)
print(row1)

Key Concepts

  • String repetition: '*' * 6 creates ******
  • String concatenation: 'a' + 'b' creates ab
  • Spaces for indentation: Spaces create the arrow shape by positioning the head
6

Phone Number Formatting

Integer Division

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

Input (as single integer)
8005551212
Formatted Output
(800) 555-1212

Solution Code

# Read phone number as integer
phone_number = int(input())
# Extract components using integer division and modulus
area_code = phone_number // 10000000
prefix = (phone_number % 10000000) // 10000
line_number = phone_number % 10000
# Output formatted phone number
print(f'({area_code}) {prefix}-{line_number}')

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
7

Find Smallest of Three

Comparison Logic

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

# Read three integers from input
num1 = int(input())
num2 = int(input())
num3 = int(input())
# Find smallest using min() function
smallest = min(num1, num2, num3)
# Output the smallest value
print(smallest)

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
8

Coin Change Calculator

Conditional Logic

Task

Convert total cents to the fewest number of coins (dollars, quarters, dimes, nickels, pennies) with proper pluralization.

Example: Input 45

Input (total cents)
45
Output
1 Quarter
2 Dimes

Solution Code

# Read total cents
total_cents = int(input())
# Check for zero or negative input
if total_cents <= 0:
print("No change")
else:
# Calculate coins
dollars = total_cents // 100
total_cents %= 100
quarters = total_cents // 25
total_cents %= 25
dimes = total_cents // 10
total_cents %= 10
nickels = total_cents // 5
pennies = total_cents % 5
# Output coins with proper pluralization
if dollars > 0:
print(f"{dollars} Dollar" + ("s" if dollars != 1 else ""))

Key Concepts

  • Greedy algorithm: Always use the largest coin possible first
  • Compound assignment: total_cents %= 25 updates the remaining amount
  • Conditional pluralization: Add "s" only when count ≠ 1 (special case for "pennies")
9

Increment by 5

While Loop

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

Input: -5 10
-5 0 5 10
Input: 0 23
0 5 10 15 20
Input: 10 3
Second integer can't be less than the first.

Solution Code

# Read two integers
first = int(input())
second = int(input())
# Validate input
if second < first:
print("Second integer can't be less than the first.")
else:
current = first
# While loop to print multiples of 5
while current <= second:
print(current, end=' ')
current += 5
# Print newline after all numbers
print()

Key Concepts

  • While loop: Continues while condition is true
  • Loop variable: current tracks the current number
  • end parameter: print(value, end=' ') prints with space instead of newline
  • Input validation: Check for invalid cases before processing
10

Reverse Text Lines

String Slicing

Task

Read lines of text from input until "done" or "d" is entered, then output each line in reverse order.

Example Input & Output

Input lines:
hello
hey
done
Output:
olleh
yeh

Solution Code

# Infinite loop until "done" or "d" is entered
while True:
line = input()
# Check termination conditions
if line.lower() in ["done", "d"]:
break
# Reverse and output the line
print(line[::-1])

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
11

Fibonacci Sequence

Loops & Logic

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.

Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(7) = 13
fibonacci(-5) = -1

Example Input & Output

Input: 7
fibonacci(7) is 13
Input: 0
fibonacci(0) is 0
Input: -3
fibonacci(-3) is -1
Input: 10
fibonacci(10) is 55

Solution Code

# The Fibonacci sequence function
def fibonacci(n):
if n < 0:
return -1
if n == 0:
return 0
if n == 1:
return 1
# For n >= 2 - use a for loop (no recursion)
prev2 = 0 # F(n-2)
prev1 = 1 # F(n-1)
for i in range(2, n + 1):
current = prev1 + prev2
# Shift values for next iteration
prev2 = prev1
prev1 = current
return prev1
# Main program
if __name__ == '__main__':
start_num = int(input())
print(f'fibonacci({start_num}) is {fibonacci(start_num)}')

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
12

List Average Calculator

Lists & Loops

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.

Formula: average = sum of elements / number of elements
calc_average([1, 2, 3, 4, 5]) = 3.0
calc_average([10, 20, 30]) = 20.0
calc_average([]) = 0.0
calc_average([5]) = 5.0

Example Input & Output

Input: "1 2 3 4 5" (space-separated)
3.0
Input: "10 20 30 40"
25.0
Input: "" (empty string)
0.0
Input: "1 2 3 4 5 6"
3.5

Solution Code

# Function to calculate average of a list
def calc_average(nums):
# Handle empty list case
if not nums:
return 0.0
total = 0
for num in nums:
total += num
# Calculate and return average
return total / len(nums)
# Alternative solution using sum() function
def calc_average_alternative(nums):
if not nums:
return 0.0
return sum(nums) / len(nums)
# Main program with input handling
if __name__ == '__main__':
# Example with hardcoded list
nums = [1, 2, 3, 4, 5]
print(calc_average(nums)) # Should return 3.0
# For reading space-separated input from user:
# input_str = input()
# nums = [int(x) for x in input_str.split()]
# print(calc_average(nums))

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 += num or use built-in sum() 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() and int(x)
13

Character Counter & Whitespace Remover

String Functions

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

Input:
The only thing we have to fear is fear itself.
Output:
Enter a sentence or phrase: You entered: The only thing we have to fear is fear itself. Number of characters: 46 String with no whitespace: Theonlythingwehavetofearisfearitself.
Input:
The rain in Spain stays mainly in the plain.
Output:
Enter a sentence or phrase: You entered: The rain in Spain stays mainly in the plain. Number of characters: 44 String with no whitespace: TheraininSpainstaysmainlyintheplain.

Solution Code

# Character counting function with for loop
def get_num_of_characters(input_str):
count = 0
for char in input_str:
count += 1
return count
# Function to output string without whitespace
def output_without_whitespace(input_str):
print("String with no whitespace: ", end="")
for char in input_str:
if char != ' ' and char != '\t':
print(char, end="")
print()
# Main program
if __name__ == '__main__':
# (1) Prompt for input and output the string
print("Enter a sentence or phrase:")
print() # Blank line after prompt
user_input = input()
print(f"You entered: {user_input}")
print() # Blank line after "You entered:"
# (2 & 3) Get character count and output it
num_chars = get_num_of_characters(user_input)
print(f"Number of characters: {num_chars}")
# (4) Output string without whitespace
output_without_whitespace(user_input)

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
14

Palindrome Checker

String Reversal

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.

Examples:
"bob" → palindrome
"never odd or even" → palindrome (ignoring spaces)
"bobby" → not a palindrome
"Race car" → palindrome (case-insensitive)

Example Input & Output

Input: bob
bob is a palindrome
Input: bobby
bobby is not a palindrome
Input: never odd or even
never odd or even is a palindrome
Input: Race car
Race car is a palindrome

Solution Code

# Palindrome Checker
user_input = input().strip()
# Remove spaces and convert to lowercase for case-insensitive comparison
clean_string = user_input.replace(" ", "").lower()
# Check if the cleaned string is equal to its reverse
if clean_string == clean_string[::-1]:
print(f"{user_input} is a palindrome")
else:
print(f"{user_input} is not a palindrome")
# Test inputs:
# bob
# bobby
# never odd or even
# Race car

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
15

Car Wash Price Calculator

Dictionaries & Input

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.

Services Dictionary:
{ 'Air freshener': 1, 'Rain repellent': 2, 'Tire shine': 2, 'Wax': 3, 'Vacuum': 5 }
Base car wash: $10
Examples:
Input: "Tire shine" (line 1), "Wax" (line 2) → Total: $15
Input: "Rain repellent" (line 1), "-" (line 2) → Total: $12
Input: "-" (line 1), "-" (line 2) → Total: $10

Example Input & Output

Input (two lines):
Tire shine
Wax
Output:
ZyCar Wash
Base car wash -- $10
Tire shine -- $2
Wax -- $3
----
Total price: $15
Input (two lines):
Rain repellent
-
Output:
ZyCar Wash
Base car wash -- $10
Rain repellent -- $2
----
Total price: $12
Input (two lines):
-
-
Output:
ZyCar Wash
Base car wash -- $10
----
Total price: $10

Solution Code

# Car Wash Price Calculator
# Dictionary of additional services and their costs
services = { 'Air freshener' : 1 , 'Rain repellent': 2, 'Tire shine' : 2, 'Wax' : 3, 'Vacuum' : 5 }
base_wash = 10
total = base_wash # Start with base wash price
# Get user input for two additional services
service_choice1 = input()
service_choice2 = input()
print("ZyCar Wash")
print(f"Base car wash -- ${base_wash}")
# Process first service choice
if service_choice1 != '-':
cost1 = services[service_choice1]
print(f"{service_choice1} -- ${cost1}")
total += cost1
# Process second service choice
if service_choice2 != '-':
cost2 = services[service_choice2]
print(f"{service_choice2} -- ${cost2}")
total += cost2
print("----")
print(f"Total price: ${total}")

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
16

Integer Division with Exception Handling

Try/Except

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.

Error Handling:
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.
Division Type:
Use integer division (//) as shown in examples.

Example Input & Output

Input:
15
3
Output:
5
Input:
10
0
Output:
Zero Division Exception: integer division or modulo by zero
Input:
15.5
5
Output:
Input Exception: invalid literal for int() with base 10: '15.5'
Input:
20
abc
Output:
Input Exception: invalid literal for int() with base 10: 'abc'

Solution Code

# Integer Division with Exception Handling
try:
# Read two integers from user input
user_num = int(input())
div_num = int(input())
# Perform the division - using // for integer division as shown in examples
result = user_num // div_num
print(result)
except ZeroDivisionError:
# Handle division by zero
print("Zero Division Exception: integer division or modulo by zero")
except ValueError as e:
# Handle invalid input (non-integer values)
error_value = str(e).split(": ")[1].strip("'") if ": " in str(e) else str(e)
print(f"Input Exception: invalid literal for int() with base 10: '{error_value}'")

Key Concepts

  • Try-except blocks: Use try to 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 e to access the exception object and its message
17

Steps to Miles Converter

Functions & Exceptions

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}')

Conversion Formula:
miles = steps ÷ 2000
Exception Handling:
Function must raise ValueError("Exception: Negative step count entered.") for negative steps
Main program must use try-except to catch this exception

Example Input & Output

Input: 5345
2.67
5345 ÷ 2000 = 2.6725 → rounded to 2.67
Input: -3850
Exception: Negative step count entered.
Input: 10000
5.00
10000 ÷ 2000 = 5.00
Input: 0
0.00
0 ÷ 2000 = 0.00 (edge case: zero is not negative)

Solution Code

# Steps to Miles Converter
def steps_to_miles(steps):
if steps < 0:
raise ValueError("Exception: Negative step count entered.")
return steps / 2000
if __name__ == '__main__':
try:
user_steps = int(input())
miles = steps_to_miles(user_steps)
print(f'{miles:.2f}')
except ValueError as e:
print(str(e))

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)
18

Synonyms Dictionary from Text Files

File I/O & Dictionaries

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.

File Naming Convention:
Word "educate" → File "educate.txt"
Word "happy" → File "happy.txt"
Word "goal" → File "goal.txt"
File Format:
Each line contains synonyms starting with the same letter
Synonyms on same line are space-separated
Dictionary Structure:
Key: First letter of synonym (e.g., 'c')
Value: List of synonyms starting with that letter

Example Input & Output

Input:
educate
c
Output:
civilize
coach
cultivate
From educate.txt, synonyms starting with 'c': civilize, coach, cultivate
Input:
educate
a
Output:
No synonyms for educate begin with a.
Input:
happy
j
Output (from happy.txt):
joyful
joyous
jubilant
Input:
nonexistent
a
Output:
File nonexistent.txt not found.

Solution Code

# Synonyms Dictionary from Text Files
synonyms = {} # Define dictionary
# Read word and letter from user
word = input().strip()
letter = input().strip().lower()
# Open the text file associated with the input word
filename = word + '.txt'
try:
with open(filename, 'r') as file:
# Read all lines from the file
lines = file.readlines()
# Process each line
for line in lines:
# Split the line into individual synonyms
words_in_line = line.strip().split()
# Store each synonym in the dictionary using its first letter as key
for synonym in words_in_line:
first_char = synonym[0].lower()
# Initialize list for this letter if it doesn't exist
if first_char not in synonyms:
synonyms[first_char] = []
# Add synonym to the list for this letter
synonyms[first_char].append(synonym)
# Check if there are synonyms for the input letter
if letter in synonyms and synonyms[letter]:
# Output all synonyms that begin with the input letter
for synonym in synonyms[letter]:
print(synonym)
else:
print(f"No synonyms for {word} begin with {letter}.")
except FileNotFoundError:
print(f"File {filename} not found.")

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 FileNotFoundError for 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 with block
  • File reading: .readlines() returns a list of all lines in the file
  • Input validation: Use .strip() on user input to remove extra whitespace
19

Word Frequencies from CSV File

CSV Processing

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.

File Format:
CSV file with words separated by commas
All words are in a single row
Case Sensitivity:
Words are case-sensitive ("hello", "Hello", "cat", "Cat" are different)
Output Format:
Each word and its frequency on separate lines
Alphabetical order not required (dictionary iteration order)

Example Input & Output

Input:
input1.csv
File contents (input1.csv):
hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy
Output:
hello 1
cat 2
man 2
hey 2
dog 2
boy 2
Hello 1
woman 1
Cat 1
Input:
words.csv
File contents (words.csv):
apple,banana,apple,orange,banana,apple,grape
Output:
apple 3
banana 2
orange 1
grape 1
Input:
nonexistent.csv
Output:
File nonexistent.csv not found.

Solution Code

# Word Frequencies from CSV File
import csv
# Read the filename from user input
filename = input().strip()
# Create a dictionary to store word frequencies
word_counts = {}
try:
# Open and read the CSV file
with open(filename, 'r') as file:
# Create a CSV reader
csv_reader = csv.reader(file)
# Process each row in the CSV file
for row in csv_reader:
# Each row contains words separated by commas
for word in row:
# Clean up the word (remove extra whitespace)
cleaned_word = word.strip()
# Update the frequency count
if cleaned_word in word_counts:
word_counts[cleaned_word] += 1
else:
word_counts[cleaned_word] = 1
# Output the words and their frequencies
for word, count in word_counts.items():
print(f"{word} {count}")
except FileNotFoundError:
print(f"File {filename} not found.")
except Exception as e:
print(f"Error reading file: {e}")

Key Concepts

  • CSV module: Import csv for 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 FileNotFoundError for 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) + 1 for 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
20

Thesaurus - Synonyms Dictionary

File I/O & Dictionaries

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.

File Naming Convention:
Word "educate" → File "educate.txt"
Word "happy" → File "happy.txt"
Word "goal" → File "goal.txt"
File Format:
Each line contains synonyms starting with the same letter
Synonyms on same line are space-separated
Dictionary Structure:
Key: First letter of synonym (e.g., 'c')
Value: List of synonyms starting with that letter

Example Input & Output

Input:
educate
c
File contents (educate.txt):
brainwash brief
civilize coach cultivate
develop discipline drill
edify enlighten exercise explain
foster
improve indoctrinate inform instruct
mature
nurture
rear
school
train tutor
Output:
civilize
coach
cultivate
From educate.txt, synonyms starting with 'c': civilize, coach, cultivate
Input:
educate
a
Output:
No synonyms for educate begin with a.
Input:
happy
j
Output (from happy.txt):
joyful
joyous
jubilant
Input:
goal
o
Output (from goal.txt):
objective
aim
aspiration

Solution Code

# Thesaurus - Synonyms Dictionary
synonyms = {} # Define dictionary
# Read word and letter from user
word = input().strip()
letter = input().strip().lower()
# Open the text file associated with the input word
filename = word + '.txt'
try:
with open(filename, 'r') as file:
# Read all lines from the file
lines = file.readlines()
# Process each line
for line in lines:
# Split the line into individual synonyms
words_in_line = line.strip().split()
# Store each synonym in the dictionary using its first letter as key
for synonym in words_in_line:
first_char = synonym[0].lower()
# Initialize list for this letter if it doesn't exist
if first_char not in synonyms:
synonyms[first_char] = []
# Add synonym to the list for this letter
synonyms[first_char].append(synonym)
# Check if there are synonyms for the input letter
if letter in synonyms and synonyms[letter]:
# Output all synonyms that begin with the input letter
for synonym in synonyms[letter]:
print(synonym)
else:
print(f"No synonyms for {word} begin with {letter}.")
except FileNotFoundError:
print(f"File {filename} not found.")

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 FileNotFoundError for 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 with block
  • 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

python_code.py

Quick Examples:

Output

Console Output
output
Output will appear here after running code...
Click "Run Code" to execute your Python code.

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