0
0
Pythonprogramming~5 mins

Environment variables usage in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an environment variable?
An environment variable is a named value stored outside a program that can affect how the program runs. It is like a setting or secret stored in the computer's system that programs can read.
Click to reveal answer
beginner
How do you access environment variables in Python?
You use the os module and call os.getenv('VARIABLE_NAME') to get the value of an environment variable.
Click to reveal answer
intermediate
Why should sensitive information like passwords be stored in environment variables?
Storing sensitive info in environment variables keeps secrets out of the code. This helps keep passwords safe and makes it easier to change them without changing the program.
Click to reveal answer
beginner
What happens if you try to get an environment variable that does not exist using os.getenv?
If the environment variable does not exist, os.getenv returns None by default, or a default value if you provide one.
Click to reveal answer
beginner
How can you set an environment variable in a Unix-like terminal before running a Python script?
You can set it by typing export VARIABLE_NAME=value in the terminal. Then when you run the Python script, it can read that variable.
Click to reveal answer
Which Python module is commonly used to access environment variables?
Aos
Bsys
Cmath
Drandom
What does os.getenv('API_KEY') return if 'API_KEY' is not set?
AAn error is raised
BNone
CZero
DAn empty string
Why is it better to store passwords in environment variables rather than hardcoding them?
AIt allows passwords to be printed easily
BIt makes the program run faster
CIt uses less memory
DIt keeps passwords secret and separate from code
How do you set an environment variable named 'TOKEN' to 'abc123' in a Unix terminal?
Aexport TOKEN=abc123
BTOKEN=abc123
Cset TOKEN=abc123
Denv TOKEN abc123
Which of these is a safe way to provide a default value when reading an environment variable in Python?
Aos.getenv('VAR', 'default')
Bos.getenv('VAR') or 'default'
CBoth B and C
DNone of the above
Explain how to read an environment variable in Python and why it is useful.
Think about how programs get settings from outside.
You got /5 concepts.
    Describe how to set an environment variable in a terminal and how a Python script can use it.
    Consider the steps before running the Python script.
    You got /5 concepts.