0
0
Pythonprogramming~15 mins

Environment variables usage in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Environment variables usage
📖 Scenario: Imagine you are creating a simple program that needs to use a secret key to access a service. Instead of writing the secret key directly in your code, you will use environment variables to keep it safe and separate.
🎯 Goal: You will learn how to read environment variables in Python and use them in your program.
📋 What You'll Learn
Create an environment variable named SECRET_KEY with the value abc123 in your system before running the program.
Use the os module to access environment variables.
Store the environment variable value in a variable called secret_key.
Print the value of secret_key.
💡 Why This Matters
🌍 Real World
Environment variables are used to keep sensitive information like keys and passwords out of the code, making programs safer and easier to manage.
💼 Career
Many jobs require working with environment variables to configure applications securely, especially in web development and cloud computing.
Progress0 / 4 steps
1
Import the os module
Write import os to import the module needed to access environment variables.
Python
Need a hint?

The os module helps you work with environment variables.

2
Read the environment variable
Create a variable called secret_key and set it to the value of the environment variable SECRET_KEY using os.getenv.
Python
Need a hint?

Use os.getenv('SECRET_KEY') to get the value of the environment variable.

3
Check if the environment variable is set
Write an if statement to check if secret_key is None. If it is, set secret_key to the string 'No key found'.
Python
Need a hint?

This helps your program handle the case when the environment variable is not set.

4
Print the secret key
Write print(secret_key) to display the value of the secret_key variable.
Python
Need a hint?

This will show the secret key if it is set, or the message if not.