Python Study Guide
Complete Reference: From Basic Concepts to Advanced Exercises
WGU D335 - Chapters 2.3 & 34 Practice
Table of Contents
Part 1: Basic Text Output & Input
Part 2: Chapter 34 Practice Exercises
Part 1: Basic Text Output and Input
Fundamental Python concepts for printing output and reading input
Basic Text Output
The print() Function
The primary way to print output in Python is using the built-in print() function.
print('hello world')
String literals: Text enclosed in quotes is called a string literal. String literals can contain letters, numbers, spaces, or symbols.
Key Point
Each print() statement starts output on a new line.
Quote Types
A string literal can be surrounded by matching single or double quotes:
print("Python rocks!")
print("Don't eat that!")
Select the statement that prints: Welcome!
print('Welcome!')
Formatting Output
Keeping Output on the Same Line
By default, each print() outputs on a new line. Use end=' ' to keep output on the same line.
print('Hello there.', end=' ')
print('My name is...', end=' ')
print('Carl?')
Outputting Multiple Items
Separate items with commas to print multiple items with a single print() statement.
print('Wage:', wage) # Comma separates multiple items
print('Name' user_name) will cause an error.
Which pair of statements print output on the same line?
print('Halt!', end=' ')
print('Who goes there?')
Variables and Output
Printing Variable Values
Print a variable's value by using the variable name without quotes in print().
print('Wage is', end=' ')
print(wage) # print variable's value
Given: num_cars = 9, which statement prints 9?
print(num_cars)
Newline Characters
Use \n (newline character) to move output to the next line.
2
3
print() automatically adds a newline character after output unless end=' ' is specified. An empty print() prints only a newline.
Write the simplest statement that prints:
Solution:
Basic Input
The input() Function
Use input() to read text entered by the user.
best_friend = input()
print('My best friend is', best_friend)
My best friend is Marty McFly
Strings: Input from input() is always a string - a sequence of characters.
Which statement reads a user-entered string into variable num_cars?
num_cars = input()
Converting Input Types
String vs. Integer
The string '123' (with quotes) is different from the integer 123 (without quotes).
| Type | Example | Description |
|---|---|---|
| String | '123' |
Sequence of characters '1', '2', '3' |
| Integer | 123 |
Numerical value one hundred twenty-three |
The int() Function
Use int() to convert a string containing only numbers to an integer.
my_string = '123'
my_int = int('123')
print(my_string)
print(my_int)
123
print('Enter wage:', end=' ')
wage = int(input()) # Convert input to integer
new_wage = wage + 10
print('New wage:', new_wage)
Type a statement that converts the string '15' to an integer:
my_var = int('15')
Input Prompts
Prompt in input()
Add a string inside input() to display a prompt to the user.
weeks = 52
hourly_wage = int(input('Enter hourly wage: '))
print('Salary is', hourly_wage * hours * weeks)
Salary is 41600
input() is a shortcut to adding a separate print() statement.
Read two numbers and output their sum:
num2 = int(input())
print(num1 + num2)
Read three numbers and output their product:
user_num2 = int(input())
user_num3 = int(input()) # Complete this line
print(user_num1 * user_num2 * user_num3)
Summary & Examples
Quick Reference Table
| Function | Description | Example |
|---|---|---|
print() |
Outputs text/variables | print('Hello') |
print(x, end=' ') |
Keeps output on same line | print('Hi', end=' ') |
\n |
Newline character | print('Line1\nLine2') |
input() |
Reads user input as string | name = input() |
int() |
Converts string to integer | num = int('5') |
input('prompt') |
Displays prompt before input | age = input('Enter age: ') |
Complete Example Program
name = input('Enter your name: ')
age = int(input('Enter your age: '))
# Output with formatting
print('\n--- User Profile ---')
print('Name:', name)
print('Age:', age)
print('Next year you will be', age + 1)
# Multi-line output
print('\nCounting down:')
print('3\n2\n1\nGo!')
Enter your age: 25
--- User Profile ---
Name: Alex
Age: 25
Next year you will be 26
Counting down:
3
2
1
Go!
Remember!
print()automatically adds a newline unless you specifyend=' 'input()always returns a string - useint()to convert to integer- Whitespace (spaces, newlines) in output must match exactly in graded activities
- Use commas in
print()to separate multiple items
Part 2: Chapter 34 Practice Exercises
Comprehensive Python programming practice problems with solutions
34.1: Assign Variables & Mathematical Operations
Task
Create a solution that accepts three integer inputs representing the number of times an employee travels to a job site. Output the total distance traveled to two decimal places given the following miles per employee commute to the job site:
- Employee A: 15.62 miles
- Employee B: 41.85 miles
- Employee C: 32.67 miles
Output Format
Distance: total_miles_traveled miles
Sample Input/Output
Input:
1 2 3
Output:
Distance: 197.33 miles
# Employee commute distances
A = 15.62
B = 41.85
C = 32.67
# Read inputs
a_trips = int(input())
b_trips = int(input())
c_trips = int(input())
# Calculate total distance
total = (a_trips * A) + (b_trips * B) + (c_trips * C)
# Output in required format
print(f"Distance: {total:.2f} miles")
34.2: Assign Variables & Modulus Operator
Task
Create a solution that accepts an integer input representing any number of ounces. Output the converted total number of tons, pounds, and remaining ounces based on the input ounces value. There are 16 ounces in a pound and 2,000 pounds in a ton.
Output Format
Tons: value_1 Pounds: value_2 Ounces: value_3
Sample Input/Output
Input:
32035
Output:
Tons: 1 Pounds: 2 Ounces: 3
# Read input ounces
total_ounces = int(input())
# Conversion constants
OUNCES_PER_POUND = 16
POUNDS_PER_TON = 2000
# Calculate tons
tons = total_ounces // (POUNDS_PER_TON * OUNCES_PER_POUND)
# Remaining ounces after tons
remaining_ounces = total_ounces % (POUNDS_PER_TON * OUNCES_PER_POUND)
# Calculate pounds
pounds = remaining_ounces // OUNCES_PER_POUND
# Remaining ounces after pounds
ounces = remaining_ounces % OUNCES_PER_POUND
# Output in required format
print(f"Tons: {tons}")
print(f"Pounds: {pounds}")
print(f"Ounces: {ounces}")
34.3: Formatted Output of Data Type
Task
Create a solution that accepts an integer input representing the index value for any of the five elements in the following list:
various_data_types = [516, 112.49, True, "meow", ("Western", "Governors", "University"), {"apple": 1, "pear": 5}]
Using the built-in function type() and getting its name by using the .__name__ attribute, output data type (e.g., "int", "float", "bool", "str") based on the input index value of the list element.
Output Format
Element index_value: data_type
Sample Input/Output
Input:
4
Output:
Element 4: tuple
# List of various data types
various_data_types = [
516,
112.49,
True,
"meow",
("Western", "Governors", "University"),
{"apple": 1, "pear": 5}
]
# Read input index
index = int(input())
# Get type name of the element at the input index
data_type = type(various_data_types[index]).__name__
# Output in required format
print(f"Element {index}: {data_type}")
34.4: Data Types in Formulas
Task
Create a solution that accepts any three integer inputs representing the base (b1, b2) and height (h) measurements of a trapezoid in meters. Output the exact area of the trapezoid in square meters as a float value. The exact area of a trapezoid can be calculated by finding the average of the two base measurements, then multiplying by the height measurement.
Trapezoid Area Formula: A = [(b1 + b2) / 2] * h
Output Format
Trapezoid area: area_value square meters
Sample Input/Output
Input:
3 4 5
Output:
Trapezoid area: 17.5 square meters
Alternative Input:
3 5 7
Output:
Trapezoid area: 28.0 square meters
# Read inputs for the trapezoid bases and height
b1 = int(input())
b2 = int(input())
h = int(input())
# Calculate trapezoid area
area = ((b1 + b2) / 2) * h
# Output in required format
print(f"Trapezoid area: {area} square meters")
34.5: Data Type Conversions
Task
Create a solution that accepts five integer inputs. Output the sum of the five inputs three times, converting the inputs to the requested data type prior to finding the sum.
- First output: sum of five inputs maintained as integer values
- Second output: sum of five inputs converted to float values
- Third output: sum of five inputs converted to string values (concatenate)
Output Format
Integer: integer_sum_value Float: float_sum_value String: string_sum_value
Sample Input/Output
Input:
1 3 6 2 7
Output:
Integer: 19 Float: 19.0 String: 13627
# Read five integer inputs
nums = [int(input()) for _ in range(5)]
# Sum as integer
int_sum = sum(nums)
# Sum as float
float_sum = float(int_sum)
# Concatenate as string
str_sum = ''.join(str(num) for num in nums)
# Output in required format
print(f"Integer: {int_sum}")
print(f"Float: {float_sum}")
print(f"String: {str_sum}")
34.6: Convert Integer to Formatted String
Task
Create a solution that accepts an integer input representing a 9-digit unformatted student identification number. Output the identification number as a string with dashes in the format XXX-XX-XXXX.
Output Format
111-22-3333
Sample Input/Output
Input:
154175430
Output:
154-17-5430
# Read 9-digit student ID as integer
student_id = int(input())
# Convert to string
s = str(student_id)
# Format as XXX-XX-XXXX
formatted_id = f"{s[:3]}-{s[3:5]}-{s[5:]}"
# Output in required format
print(formatted_id)
34.7: Comparison Operations with Boolean Values
Task
Create a solution that accepts an integer input to compare against the following list:
predef_list = [4, -27, 15, 33, -10]
Output a Boolean value indicating whether the input value is greater than the maximum value from predef_list.
Output Format
Greater Than Max? Boolean_value
Sample Input/Output
Input:
20
Output:
Greater Than Max? False
# Predefined list
predef_list = [4, -27, 15, 33, -10]
# Read integer input
num = int(input())
# Compare to maximum of the list
result = num > max(predef_list)
# Output in required format
print(f"Greater Than Max? {result}")
34.8: Try Block with Exception Error
Task
Create a solution that accepts one integer input representing the index value for any of the string elements in the following list:
frameworks = ["Django", "Flask", "CherryPy", "Bottle", "Web2Py", "TurboGears"]
Output the string element of the index value entered. The solution should be placed in a try block and implement an exception of "Error" if an incompatible integer input is provided.
Output Format
frameworks_element
Sample Input/Output
Input:
2
Output:
CherryPy
Alternative Input:
7
Output:
Error
# List of frameworks
frameworks = ["Django", "Flask", "CherryPy", "Bottle", "Web2Py", "TurboGears"]
try:
# Read integer input for index
index = int(input())
# Print the element at the given index
print(frameworks[index])
except:
# Print Error for invalid index
print("Error")
34.9: Branching Conditional Logic
Task
Create a solution that accepts an integer input representing water temperature in degrees Fahrenheit. Output a description of the water state based on the following scale:
- If the temperature is below 33° F, the water is "Frozen".
- If the water is between 33° F and 80° F (including 33), the water is "Cold".
- If the water is between 80° F and 115° F (including 80), the water is "Warm".
- If the water is between 115° F and 211° F (including 115), the water is "Hot".
- If the water is greater than or equal to 212° F, the water is "Boiling".
Additionally, output a safety comment only during the following circumstances:
- If the water is exactly 212° F, the safety comment is "Caution: Hot!"
- If the water temperature is less than 33° F, the safety comment is "Watch out for ice!"
Output Format
water_state optional_safety_comment
Sample Input/Output
Input:
118
Output:
Hot
Alternative Input:
32
Output:
Frozen Watch out for ice!
# Read water temperature in Fahrenheit
temp = int(input())
# Determine water state
if temp < 33:
state = "Frozen"
safety = "Watch out for ice!"
elif 33 <= temp < 80:
state = "Cold"
safety = ""
elif 80 <= temp < 115:
state = "Warm"
safety = ""
elif 115 <= temp < 212:
state = "Hot"
safety = ""
else: # temp >= 212
state = "Boiling"
safety = "Caution: Hot!" if temp == 212 else ""
# Output water state
print(state)
# Output safety comment if applicable
if safety:
print(safety)
34.10: Dictionary Key Search
Task
Create a solution that accepts an integer input identifying how many shares of stock are to be purchased from the Old Town Stock Exchange, followed by an equivalent number of string inputs representing the stock selections. The following dictionary stock lists available stock selections as the key with the cost per selection as the value:
stocks = {'TSLA': 912.86, 'BBBY': 24.84, 'AAPL': 174.26, 'SOFI': 6.92, 'KIRK': 8.72, 'AURA': 22.12, 'AMZN': 141.28, 'EMBK': 12.29, 'LVLU': 2.33}
Output the total cost of the purchased shares of stock to two decimal places.
Output Format
Total price: $cost_of_stocks
Sample Input/Output
Input:
3 SOFI AMZN LVLU
Output:
Total price: $150.53
# Dictionary of available stocks with their prices
stocks = {
'TSLA': 912.86,
'BBBY': 24.84,
'AAPL': 174.26,
'SOFI': 6.92,
'KIRK': 8.72,
'AURA': 22.12,
'AMZN': 141.28,
'EMBK': 12.29,
'LVLU': 2.33
}
# Read number of shares to purchase
n = int(input())
# Read n stock selections
selections = [input() for _ in range(n)]
# Calculate total cost
total = sum(stocks[stock] for stock in selections)
# Output in required format
print(f"Total price: ${total:.2f}")
34.11: Dictionary Conditional Logic
Task
Create a solution that accepts a string input representing a grocery store item and an integer input identifying the number of items purchased on a recent visit. The following dictionary purchase lists available items as the key with the cost per item as the value:
purchase = {"bananas": 1.85, "steak": 19.99, "cookies": 4.52, "celery": 2.81, "milk": 4.34}
Additionally:
- If fewer than ten items are purchased, the price is the full cost per item.
- If between ten and twenty items (inclusive) are purchased, the purchase gets a 5% discount.
- If twenty-one or more items are purchased, the purchase gets a 10% discount.
Output the chosen item and total cost of the purchase to two decimal places.
Output Format
item_purchased $total_purchase_cost
Sample Input/Output
Input:
bananas 12
Output:
bananas $21.09
Alternative Input:
cookies 144
Output:
cookies $585.79
# Dictionary of items with prices
purchase = {"bananas": 1.85, "steak": 19.99, "cookies": 4.52, "celery": 2.81, "milk": 4.34}
# Read inputs
item = input()
quantity = int(input())
# Get base price
base_price = purchase[item]
# Apply discounts based on quantity
if quantity < 10:
total = base_price * quantity
elif 10 <= quantity <= 20:
total = base_price * quantity * 0.95 # 5% discount
else: # quantity >= 21
total = base_price * quantity * 0.90 # 10% discount
# Output in required format
print(f"{item} ${total:.2f}")
34.12: Manipulate Text Files
Task
Create a solution that accepts an input identifying the name of a text file, for example, "WordTextFile1.txt". Each text file contains three rows with one word per row. Using the open() function and write() and read() methods, interact with the input text file to write a new sentence string composed of the three existing words to the end of the file contents on a new line. Output the new file contents.
Output Format
word1 word2 word3 sentence
Sample Input/Output
Input:
WordTextFile1.txt
Output:
cat chases dog cat chases dog
# Read filename from input
filename = input()
# Open file for reading and appending (creates file if it doesn't exist)
with open(filename, "a+") as file:
file.seek(0) # Move cursor to start to read existing lines
words = [line.strip() for line in file.readlines()]
# Only create sentence if there are exactly 3 words
if len(words) >= 3:
sentence = " ".join(words[:3])
file.write("\n" + sentence)
# Open file again to read and output all contents
with open(filename, "r") as file:
contents = file.read()
print(contents)
34.13: Manipulate CSV Files
Task
Create a solution that accepts an input identifying the name of a CSV file, for example, "input1.csv". Each file contains two rows of comma-separated values. Import the built-in module csv and use its open() function and reader() method to create a dictionary of key:value pairs for each row of comma-separated values in the specified file. Output the file contents as two dictionaries.
Output Format
{'key': 'value', 'key': 'value', 'key': 'value'}
{'key': 'value', 'key': 'value', 'key': 'value'}
Sample Input/Output
Input:
input1.csv
Output:
{'a': '100', 'b': '200', 'c': '300'}
{'bananas': '1.85', 'steak': '19.99', 'cookies': '4.52'}
Alternative Input:
input2.csv
Output:
{'d': '400', 'e': '500', 'f': '600'}
{'celery': '2.81', 'milk': '4.34', 'bread': '5.63'}
import csv
# Read CSV filename from input
filename = input()
# Open the CSV file and read its contents
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile) # default delimiter is comma
for row in reader:
it = iter(row)
# Strip whitespace from keys and values
row_dict = {k.strip(): v.strip() for k, v in zip(it, it)}
print(row_dict)
34.14: Math Module
Task
Create a solution that accepts an integer input. Import the built-in module math and use its factorial() method to calculate the factorial of the integer input. Output the value of the factorial, as well as a Boolean value identifying whether the factorial output is greater than 100.
Output Format
factorial_value Boolean_value
Sample Input/Output
Input:
10
Output:
3628800 True
Alternative Input:
3
Output:
6 False
import math # Read integer input n = int(input()) # Calculate factorial fact = math.factorial(n) # Check if factorial is greater than 100 is_gt_100 = fact > 100 # Output in required format print(fact) print(is_gt_100)
34.15: Import Custom Module
Task
Create a solution that accepts an integer input representing the age of a pig. Import the existing module pigAge and use its pre-built pigAge_converter() function to calculate the human equivalent age of a pig. A year in a pig's life is equivalent to five years in a human's life. Output the human-equivalent age of the pig.
Output Format
input_pig_age is converted_pig_age in human years
Sample Input/Output
Input:
8
Output:
8 is 40 in human years
# Import the existing module
import pigAge
# Read pig age from input
pig_age = int(input())
# Convert pig age to human-equivalent age
human_age = pigAge.pigAge_converter(pig_age)
# Output in required format
print(f"{pig_age} is {human_age} in human years")