← Back to Chapter 4 Chapter 4 Practical Exam: Functions
30:00

Chapter 4 Practical Exam

Demonstrate your function mastery by solving these coding challenges.

Problems
3
Difficulty
Medium
Time Limit
30 min
Solved
0/3

Problem 1: Temperature Converter

Medium

Description

Create two functions to convert temperatures between Celsius and Fahrenheit:

  • celsius_to_fahrenheit(celsius) - Convert Celsius to Fahrenheit
  • fahrenheit_to_celsius(fahrenheit) - Convert Fahrenheit to Celsius

Formulas:

  • F = C × 9/5 + 32
  • C = (F - 32) × 5/9

Both functions should return the converted value rounded to 1 decimal place.

Example

celsius_to_fahrenheit(0) # Returns: 32.0 celsius_to_fahrenheit(100) # Returns: 212.0 fahrenheit_to_celsius(32) # Returns: 0.0 fahrenheit_to_celsius(98.6) # Returns: 37.0
Your Solution
Test Results
Click "Run Tests" to check your solution...

Hint

Remember to use round(value, 1) to round to 1 decimal place. Make sure you're applying the formulas correctly - pay attention to the order of operations!

Problem 2: Factorial Calculator

Medium

Description

Create a function factorial(n) that calculates the factorial of a non-negative integer.

The factorial of n (written as n!) is the product of all positive integers from 1 to n.

Special case: 0! = 1

Error handling: If n is negative, return None.

Example

factorial(0) # Returns: 1 factorial(1) # Returns: 1 factorial(5) # Returns: 120 (5×4×3×2×1) factorial(7) # Returns: 5040 factorial(-1) # Returns: None
Your Solution
Test Results
Click "Run Tests" to check your solution...

Hint

Start by handling the edge cases: negative numbers (return None) and 0 (return 1). Then use a loop to multiply from 1 to n. You can also use recursion: n! = n × (n-1)!

Problem 3: Smart Calculator

Medium

Description

Create a function calculate(a, b, operation="add") that performs basic math operations.

Parameters:

  • a - First number
  • b - Second number
  • operation - Operation to perform (default: "add")

Supported operations:

  • "add" - Returns a + b
  • "subtract" - Returns a - b
  • "multiply" - Returns a × b
  • "divide" - Returns a ÷ b (return "Error" if b is 0)
  • "power" - Returns a raised to the power of b

If an unknown operation is provided, return "Unknown operation".

Example

calculate(5, 3) # Returns: 8 (default is add) calculate(10, 4, "subtract") # Returns: 6 calculate(6, 7, "multiply") # Returns: 42 calculate(20, 4, "divide") # Returns: 5.0 calculate(10, 0, "divide") # Returns: "Error" calculate(2, 8, "power") # Returns: 256 calculate(5, 3, "modulo") # Returns: "Unknown operation"
Your Solution
Test Results
Click "Run Tests" to check your solution...

Hint

Use if/elif/else to check the operation parameter. For "divide", check if b is 0 before dividing. Don't forget the default parameter value! Use ** for power.