You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python技术问询:如何打印变量名而非变量值(含列表场景)

How to Print Variable Names Instead of Values in Python

First off, let’s tackle your core question—printing variable names like a and b alongside their values. Here are a few practical methods tailored for a school assignment, starting with the simplest approaches:

The most straightforward way is to create a dictionary where keys are your variable names (as strings) and values are the actual variables. This makes it easy to access both the name and value in one go:

a = 42
b = "Hello Python"

# Map variable names to their values
variable_dict = {"a": a, "b": b}

# Loop through to print names and values
for var_name, var_value in variable_dict.items():
    print(f"Variable: {var_name}, Value: {var_value}")

Output:

Variable: a, Value: 42
Variable: b, Value: Hello Python

This method is simple to understand and implement—ideal for school work where clarity matters.

Method 2: Handle Variables in a List

If you need to work with variables stored in a list, just adding the variables to the list won’t preserve their names (since lists hold values, not references to variable names). Instead, store tuples of (name string, variable) in the list:

a = 10
b = 20
c = 30

# List of (variable name, variable value) pairs
variable_list = [("a", a), ("b", b), ("c", c)]

for var_name, var_value in variable_list:
    print(f"{var_name} = {var_value}")

Output:

a = 10
b = 20
c = 30

Advanced: Dynamically Retrieve Variable Names (Using inspect)

For more dynamic scenarios (like getting the name of a variable passed to a function), you can use Python’s inspect module to parse the source code. This is a bit more complex, but useful for specific cases:

import inspect

def print_var_details(var):
    # Get the context where the function was called
    caller_frame = inspect.currentframe().f_back
    # Check local variables to find a match for the passed value
    for name, value in caller_frame.f_locals.items():
        if value is var:
            print(f"Variable Name: {name}, Value: {var}")
            return

a = 5
print_var_details(a)

Output:

Variable Name: a, Value: 5

Note: This method isn’t foolproof (it may fail with complex expressions or nested variables), so stick to the dictionary/tuple list methods for most school assignments.


内容的提问来源于stack exchange,提问作者jst kiko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:33:17