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

Python 3.4中如何实现用户输入自定义列表值?

Fixing User Input for Custom List/Tuple in Python

Hey there! Let's sort out this input issue for you. The problem with your current code is that you're trying to use variables a1, a2, a3 before you've defined them—Python has no idea what those values are when you create lst = (a1, a2, a3), so it throws a NameError.

Simple Fix: Reorder Your Code

Just swap the order: first get the user inputs, then create your list/tuple with those values. Here's how:

# First collect the user's inputs
a1 = int(input("number 1: "))
a2 = int(input("number 2: "))
a3 = int(input("number 3: "))

# Now create your tuple (use [] instead of () if you want a list)
lst = (a1, a2, a3)

More Flexible Options

If you want to avoid hardcoding the number of inputs, here are two better approaches:

1. Input Multiple Numbers at Once

Let the user enter all numbers in one line, separated by spaces:

input_text = input("Enter numbers separated by spaces: ")
# Split the input string into parts, convert each to integer
lst = [int(num) for num in input_text.split()]
# Convert to tuple if needed: lst = tuple(lst)

Example input: 14 1 6 8 → gives you [14, 1, 6, 8]

2. Ask How Many Numbers to Enter

Let the user specify the count first, then loop to collect each value:

num_count = int(input("How many numbers do you want to add? "))
lst = []
for i in range(num_count):
    number = int(input(f"Enter number {i+1}: "))
    lst.append(number)
# Again, use tuple(lst) if you need a tuple instead of a list

All these methods will work perfectly for letting users define the values in your list/tuple.

内容的提问来源于stack exchange,提问作者Hassan Ait Bihi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:21:41