Python Fundamentals Practice
Practice Exercises - Python 3 Fundamentals
Practice Exercises: Python 3 Fundamentals
This practice guide is structured to reinforce the concepts covered in Step 1: Python Fundamentals. Solving these exercises will help you develop procedural logic, gain experience reading traceback logs, and understand how state is manipulated in program code without relying on complex control flow structures.
Guidelines for Effective Learning:
- Solve Individually First: Always write out your own logical code before reviewing the provided answers.
- Execute Locally: Run each code block in your local terminal. Modifying inputs and observing outcomes is the most effective way to understand logic systems.
- Analyze Errors: If a snippet crashes, read the terminal's traceback log—it tells you the exact line and classification of the error.
Practice Questions Index
- Section 1: Getting Started (Questions 1-10) — Standard output, input capturing, comments, and syntax execution.
- Section 2: Variables & Memory (Questions 11-20) — Creating, updating, and tracking variable state.
- Section 3: Information Types & Casting (Questions 21-30) — String, integer, float, and boolean classifications and casting.
- Section 4: Mathematical Calculations (Questions 31-40) — Arithmetic operator logic, floor division, modulus, and exponents.
- Section 5: Comparison & Boolean Logic (Questions 41-50) — Boolean evaluations, direct comparisons, and multi-gate logical expressions.
Section 1: Getting Started (Questions 1-10)
Question 1: System Command Check
Which system command do you run in your terminal to check the currently active and configured version of Python?
Answer: python --version
Question 2: Simple Output Execution
Write a single line of Python code that outputs the message "Console initialization complete." to the terminal screen.
Answer:
main.pyRunnableprint("Console initialization complete.")
Question 3: Print Syntax Check
What error does the Python interpreter raise if you run print "Hello" without parentheses? Explain why.
Answer: It raises a SyntaxError. In Python 3, print() is a built-in function, which strictly requires parentheses to enclose its arguments.
Question 4: Inline Code Documentation
Write a code snippet that prints "Starting analysis..." and includes an inline comment explaining that this line prints a status update.
Answer:
main.pyRunnableprint("Starting analysis...") # Prints the primary system status update
Question 5: Multiline Code Documentation
Write a multiline comment that contains your name, date, and description for a script, ensuring it spans exactly three lines.
Answer:
main.pyRunnable""" Author: Marcus Vance Date: May 2026 Description: This script calculates credit distributions. """
Question 6: Fixing Quote Typology
Explain why the following code line crashes during execution, and show how to fix it:
main.pyRunnableprint("Terminal online.)
Answer: It crashes because the string literal has an unmatched opening double quote but lacks a closing double quote. This raises a SyntaxError: EOL while scanning string literal.
Correct Code:
main.pyRunnableprint("Terminal online.")
Question 7: Command Case Validation
Will running the command Print("Execution initialized.") work in Python? Explain why or why not.
Answer: No. Python is strictly case-sensitive. The command name is defined as lowercase print(). Running Print() will raise a NameError because the interpreter does not recognize the capitalized identifier.
Question 8: Multiple Argument Printing
How do you print a string label and a numeric value on a single line using a single print command, without doing manual conversion?
Answer: Pass them as separate arguments to the print() function, separated by a comma. The print function will automatically output them on the same line with a space in between:
main.pyRunnableprint("Active Level:", 4)
Question 9: Capture String Input
Write a code line that prompts the user to enter their home city and stores the result in a variable named user_city.
Answer:
main.pyRunnableuser_city = input("Enter your home city: ")
Question 10: Print Multiple Variables
Given variables first_name = "Marcus" and last_name = "Vance", print them both on a single line separated by a space using a single print statement.
Answer:
main.pyRunnablefirst_name = "Marcus" last_name = "Vance" print(first_name, last_name)
Section Checkup
Section 2: Variables & Memory (Questions 11-20)
Question 11: Memory Allocation
Assign the integer value 100 to a variable named network_bandwidth. What does this tell the computer to do in memory?
Answer:
main.pyRunnablenetwork_bandwidth = 100
This tells the computer to allocate a slot in its memory, label it network_bandwidth, and store the integer value 100 in that slot.
Question 12: Spaces in Identifiers
Why will the variable declaration system status = "active" raise an error, and how do you resolve it to meet standard naming guidelines?
Answer: It raises a SyntaxError because variable names (identifiers) cannot contain spaces. To resolve this, standard Snake Case must be used.
Correct Code:
main.pyRunnablesystem_status = "active"
Question 13: Validating Naming Constraints
Look at the following list of variable names. Which ones are invalid under Python syntax rules?
first_name, 1st_parameter, processing-charge, while
Answer:
1st_parameteris invalid because variable names cannot begin with a number.processing-chargeis invalid because hyphens are interpreted as subtraction operators.whileis invalid because it is a reserved language keyword.
Question 14: Overwriting State
What is displayed in the console when this script runs? Explain the behavior.
main.pyRunnableuser_id = 4502 user_id = 8911 print(user_id)
Answer: It prints 8911. Variables store only one value at a time. The second assignment overrides the original value in that variable's memory address.
Question 15: Mathematical Operations with Variables
Declare two variables: inbound_connections = 12 and outbound_connections = 8. Add them together and store the result in a variable named total_traffic. Print the value.
Answer:
main.pyRunnableinbound_connections = 12 outbound_connections = 8 total_traffic = inbound_connections + outbound_connections print("Total Active Connections:", total_traffic)
Question 16: Restricting Keywords
What happens if you try to declare a variable named elif?
Answer: Python will raise a SyntaxError: invalid syntax immediately. elif is a reserved language keyword that controls conditional logic routing and cannot be used as an identifier.
Question 17: Variable Calculations
You have original_budget = 50.00 and charge_amount = 12.50. Subtract charge_amount from original_budget and store the result in remaining_balance. Print the balance.
Answer:
main.pyRunnableoriginal_budget = 50.00 charge_amount = 12.50 remaining_balance = original_budget - charge_amount print("Remaining Balance: $", remaining_balance)
Question 18: Tracing Arithmetic Operations
Track the value of the variable credits as this script runs. What is its final value?
main.pyRunnablecredits = 5 credits = credits + 10 credits = credits * 3
Answer: 45.
creditsis initialized to5.credits + 10evaluates to15, which is assigned back tocredits.credits * 3evaluates to45(15 * 3), which is assigned tocredits.
Question 19: Unassigned Variable Crash
Why does running the line print(total_score) crash if total_score was never declared? What error classification is raised?
Answer: It raises a NameError: name 'total_score' is not defined. Python cannot retrieve data from a container that has not been initialized in memory.
Question 20: Self-Increment Operator Logic
Explain what the code statement counter += 1 means and write its expanded equivalent.
Answer: The += operator is a self-increment shortcut. It adds 1 to the current value of counter and re-assigns the result back to counter.
Expanded Equivalent:
main.pyRunnablecounter = counter + 1
Section Checkup
Section 3: Information Types & Casting (Questions 21-30)
Question 21: Whole Count Classification
What Python data type is designed to represent whole numbers, such as a count of servers (24) or the number of questions in a test (50)?
Answer: The Integer (int) type.
Question 22: Decimal Classification
What Python data type is used to store decimal values, such as a temperature reading of 98.6 or a credit percentage of 0.85?
Answer: The Float (float) type.
Question 23: Characters Classification
What Python data type represents text data like "Alice Smith" or "System Offline"?
Answer: The String (str) type.
Question 24: Switch State Classification
What Python data type is limited to storing binary true or false values?
Answer: The Boolean (bool) type.
Question 25: Runtime Type Checking
Which built-in function allows you to inspect what data type a variable is holding at runtime? Write a line of code demonstrating its use.
Answer: The type() function.
main.pyRunnablerate = 5.25 print(type(rate)) # Outputs: <class 'float'>
Question 26: Processing Inputs
When capturing data using input(), Python returns it as a string. How do you convert this captured string into an integer to perform calculations?
Answer: Pass the string to the int() casting function:
main.pyRunnableraw_input = input("Enter capacity: ") capacity = int(raw_input) # Safe for mathematical computations
Question 27: Casting Decimal Strings
You have the text string "2.99". How do you convert it into a numeric decimal variable?
Answer: Pass the string to the float() casting function:
main.pyRunnableprice_text = "2.99" price_numeric = float(price_text)
Question 28: Concatenation Type Mismatch
Why does the following script crash during execution, and how do you resolve it?
main.pyRunnableactive_users = 8 print("Active users: " + active_users)
Answer: It crashes because you cannot concatenate a String and an Integer directly using the + operator. This raises a TypeError. You must convert the integer to a string using str().
Correct Code:
main.pyRunnableactive_users = 8 print("Active users: " + str(active_users))
Question 29: Convert Float to Int
What happens to a float variable like pi = 3.99 if you cast it to an integer using int(pi)? Print the resulting value.
Answer: The value is truncated (the decimal portion is dropped entirely). The value becomes the integer 3 (it does not round to the nearest whole number).
main.pyRunnablepi = 3.99 pi_int = int(pi) print(pi_int) # Outputs: 3
Question 30: Convert Number to Boolean
What boolean value is returned when you cast the integer 0 to a boolean using bool(0)? What does any non-zero number return?
Answer: bool(0) returns False. Any non-zero integer or float returns True.
Section Checkup
Section 4: Mathematical Calculations (Questions 31-40)
Question 31: Calculating Division Remainders
Write a line of code that uses an operator to calculate the remainder when 15 is divided by 4.
Answer: Use the Modulus operator (%):
main.pyRunnableremainder = 15 % 4 # Remainder evaluates to 3
Question 32: Truncated Division
Which operator divides two numbers and discards the decimal remainder? Show how it evaluates when dividing 15 by 4.
Answer: The Floor Division operator (//).
main.pyRunnableresult = 15 // 4 # Evaluates to 3
Question 33: Exponent Logic
Write an expression in Python that raises 5 to the power of 3 ().
Answer: Use the Exponent operator (**):
main.pyRunnableresult = 5 ** 3 # Evaluates to 125
Question 34: Fahrenheit Conversion Calculator
Write a procedural script that captures a temperature in Celsius from the user, casts it to a float, and calculates the equivalent Fahrenheit using . Print the result.
Answer:
main.pyRunnablecelsius_input = input("Enter temperature in Celsius: ") celsius = float(celsius_input) fahrenheit = (celsius * 1.8) + 32 print("Fahrenheit equivalent:", fahrenheit)
Question 35: Standard Invoice Calculations
A service invoice has subtotal = 80.00 and tax_rate = 0.08. Calculate the numeric tax charge and the final total bill. Print them both.
Answer:
main.pyRunnablesubtotal = 80.00 tax_rate = 0.08 tax_charge = subtotal * tax_rate total_bill = subtotal + tax_charge print("Tax Charged: $", tax_charge) print("Total Bill: $", total_bill)
Question 36: Group Bill Splitter
Capture the total restaurant bill amount from the terminal (cast to float) and the total number of diners (cast to integer). Compute the exact split cost per person and print it.
Answer:
main.pyRunnabletotal_bill = float(input("Enter total bill amount: $")) diners = int(input("Enter number of diners: ")) cost_per_person = total_bill / diners print("Cost per person: $", cost_per_person)
Question 37: Van Allocation leftovers
A transport van holds exactly 12 passengers. Capture the total number of travelers from the terminal. Compute how many full vans are filled and how many passengers are left over.
Answer:
main.pyRunnabletravelers = int(input("Enter number of travelers: ")) van_capacity = 12 full_vans = travelers // van_capacity leftovers = travelers % van_capacity print("Full vans completed:", full_vans) print("Passengers left over:", leftovers)
Question 38: Weekly Wages Calculator
Capture hourly wage rate (float) and total hours worked in a week (float). Calculate the gross pay amount and print it.
Answer:
main.pyRunnablehourly_rate = float(input("Enter hourly rate: $")) hours_worked = float(input("Enter hours worked: ")) gross_pay = hourly_rate * hours_worked print("Weekly gross pay: $", gross_pay)
Question 39: Area of a Rectangle
Capture the width and height of a plot of land as floats. Calculate the total square area and print it.
Answer:
main.pyRunnablewidth = float(input("Enter width (meters): ")) height = float(input("Enter height (meters): ")) area = width * height print("Total Area:", area, "square meters")
Question 40: Circle Area Calculation
A circle's area is calculated using . Using pi = 3.14159, capture the radius from the terminal as a float, calculate the area, and print the result.
Answer:
main.pyRunnablepi = 3.14159 radius = float(input("Enter circle radius: ")) area = pi * (radius ** 2) print("Circle Area:", area)
Section Checkup
Section 5: Comparison & Boolean Logic (Questions 41-50)
Question 41: Assignment vs. Equality
Explain the structural difference in behavior between the = operator and the == operator in Python.
Answer:
=is the Assignment Operator. It stores a value inside a memory location (e.g.,x = 10).==is the Comparison Operator. It checks if two values are equal and returns a BooleanTrueorFalse(e.g.,x == 10).
Question 42: Equal-to Check
Capture a user password guess from the terminal. Evaluate directly if it matches the system password "security2026" by printing the resulting boolean flag.
Answer:
main.pyRunnablecorrect_password = "security2026" guess = input("Enter password guess: ") is_match = guess == correct_password print("Password validation result:", is_match)
Question 43: Logical AND Gate
What boolean value does this logical expression return?
main.pyRunnableprint(True and False)
Answer: False. The and operator only returns True if both operands are True.
Question 44: Logical OR Gate
What boolean value does this logical expression return?
main.pyRunnableprint(True or False)
Answer: True. The or operator returns True if at least one operand is True.
Question 45: Boolean Negation
Evaluate the outcome of the following logical statement:
main.pyRunnableprint(not (10 < 2))
Answer: True.
10 < 2evaluates toFalse.not Falseevaluates toTrue.
Question 46: Grade Passing Check
Capture a student's numeric test score as an integer. Print the boolean output indicating whether they passed (scored 75 or higher).
Answer:
main.pyRunnablescore = int(input("Enter numeric score: ")) is_passing = score >= 75 print("Student passing status:", is_passing)
Question 47: Limit Warning Check
An account has balance = 50.00. Capture a transaction charge amount. Calculate the remaining balance, and print a boolean status indicating whether the account has gone into a deficit (balance below 0.00).
Answer:
main.pyRunnablebalance = 50.00 charge = float(input("Enter transaction charge: $")) remaining_balance = balance - charge is_overdrawn = remaining_balance < 0.00 print("Account balance is in deficit:", is_overdrawn)
Question 48: Age Eligibility Verification
A voter must be 18 years or older. Capture the voter's age from the terminal and print a boolean indicating if they are eligible.
Answer:
main.pyRunnablevoter_age = int(input("Enter voter age: ")) is_eligible = voter_age >= 18 print("Voter eligibility status:", is_eligible)
Question 49: Combined Academic Honor Roll Check
To make the Honor Roll, a student must have a GPA of 3.8 or higher and have zero suspensions. Initialize gpa = 3.9 and suspensions = 0. Compute their honor roll status as a boolean and print it.
Answer:
main.pyRunnablegpa = 3.9 suspensions = 0 is_eligible_honor_roll = (gpa >= 3.8) and (suspensions == 0) print("Honor Roll Eligibility Status:", is_eligible_honor_roll)
Question 50: Attendance Criteria Warning
An attendance rate must be 92.0% or higher. Capture the days absent out of a 90-day semester as an integer. Calculate the attendance rate percentage: . Print the rate and a boolean indicating whether the warning criteria is triggered (rate is strictly below 92.0%).
Answer:
main.pyRunnabletotal_days = 90 absences = int(input("Enter days absent: ")) days_attended = total_days - absences attendance_rate = (days_attended / total_days) * 100 warning_triggered = attendance_rate < 92.0 print(f"Calculated Attendance Rate: {attendance_rate:.1f}%") print("Mandatory warning triggered:", warning_triggered)
Congratulations! 🎓
You have completed the entire Python Fundamentals Practice companion. You are now fully prepared to build procedural mathematical applications. Keep practicing and happy coding!
Finished this lesson?
Mark it complete to advance your curriculum progress.