0
0
Pythonprogramming~15 mins

Raising exceptions in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Raising Exceptions in Python
📖 Scenario: You are building a simple program that checks user input for age eligibility to enter a club. If the age is below the allowed limit, the program should raise an exception to stop the process and inform the user.
🎯 Goal: Create a program that raises an exception when the user's age is below 18, using Python's raise statement.
📋 What You'll Learn
Create a variable called age with a specific integer value.
Create a variable called minimum_age set to 18.
Use an if statement to check if age is less than minimum_age.
Raise a ValueError with the message 'Age is below the minimum allowed.' when the condition is true.
Print 'Access granted.' if the age is valid.
💡 Why This Matters
🌍 Real World
Programs often need to check if input values are valid and stop running if they are not. Raising exceptions helps catch errors early.
💼 Career
Understanding how to raise exceptions is important for writing safe and reliable code in software development jobs.
Progress0 / 4 steps
1
Create the age variable
Create a variable called age and set it to the integer 16.
Python
Need a hint?

Use age = 16 to store the user's age.

2
Set the minimum age
Create a variable called minimum_age and set it to the integer 18.
Python
Need a hint?

Use minimum_age = 18 to set the allowed age limit.

3
Raise an exception if age is too low
Write an if statement that checks if age is less than minimum_age. Inside the if, use raise ValueError('Age is below the minimum allowed.') to stop the program with an error.
Python
Need a hint?

Use if age < minimum_age: and then raise ValueError('Age is below the minimum allowed.').

4
Print access granted if age is valid
After the if statement, write print('Access granted.') to show a success message when no exception is raised.
Python
Need a hint?

Use print('Access granted.') after the if block.

Note: Because age is 16, the program will raise an error and not print 'Access granted.'