Last modified: Sep 20, 2023 By Alexander Williams
Python: Print Variable Name and Value (Examples)
Example 1: Using f-strings (Python 3.8+)
# Define a variable
variable_name = "age"
variable_value = 30
# Print variable name and value using f-string
print(f"Variable name: {variable_name}, Variable value: {variable_value}")
Output:
Variable name: age, Variable value: 30
Example 2: Using locals() dictionary
# Define variables
variable_name = "name"
variable_value = "Alice"
# Create a dictionary of local variables
variables = locals()
# Print variable names and values
for var_name, var_value in variables.items():
print(f"Variable name: {var_name}, Variable value: {var_value}")
Output:
Variable name: variable_name, Variable value: name
Variable name: variable_value, Variable value: Alice
Example 3: Using globals() dictionary
# Define global variables
global_variable = "global_var"
global_value = 42
# Create a dictionary of global variables
variables = globals()
# Print variable names and values
for var_name, var_value in variables.items():
print(f"Variable name: {var_name}, Variable value: {var_value}")
Output:
Variable name: global_variable, Variable value: global_var
Variable name: global_value, Variable value: 42
Example 4: Printing Variable Names from a List
# Define variables
name = "Alice"
age = 30
# Create a list of variable names
variables_list = ["name", "age", "city"]
# Print variable names and values from the list
for var_name in variables_list:
var_value = locals().get(var_name)
print(f"Variable name: {var_name}, Variable value: {var_value}")
Output:
Variable name: name, Variable value: Alice
Variable name: age, Variable value: 30
Variable name: city, Variable value: None
Example 5: Printing All Variable Names in a Function
# Define variables
name = "Alice"
age = 30
# Define a function to print variable names and values
def print_variable_names():
local_vars = locals()
for var_name, var_value in local_vars.items():
print(f"Variable name: {var_name}, Variable value: {var_value}")
# Call the function
print_variable_names()
Output:
Variable name: name, Variable value: Alice
Variable name: age, Variable value: 30
Example 6: Printing Variable Names with Specific Prefix
# Define variables with a specific prefix
user_name = "John"
user_age = 25
user_email = "john@example.com"
# Define a prefix
prefix = "user_"
# Print variable names and values with the specified prefix
for var_name, var_value in globals().items():
if var_name.startswith(prefix):
print(f"Variable name: {var_name}, Variable value: {var_value}")
Output:
Variable name: user_name, Variable value: John
Variable name: user_age, Variable value: 25
Variable name: user_email, Variable value: john@example.com