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

Python代码优化:实现输入非4位时支持重新输入的逻辑

How to Force 4-Digit Input Until Valid in Python

Got it, let's tweak your code so it keeps asking the user for input until they provide a valid 4-digit value. First, let's look at your original code to understand where we need changes:

a = input()
def word_to_list(a):
    b = str(a)
    code2 = []
    for digit in b:
        code2.append(int(digit))
    if len(code2) != 4:
        print("no right amount")
    else:
        print(code2)
code2 = word_to_list(a)

The main issue here is that after printing an error for invalid input, the code stops instead of asking again. Plus, your function doesn't return the converted list (it just prints it), so code2 ends up as None even when input is valid.

Here's the fixed version that handles repeated input properly:

def word_to_list(input_str):
    # Convert the 4-digit string into a list of integers
    return [int(digit) for digit in input_str]

# Loop forever until we get valid input
while True:
    user_input = input("Enter a 4-digit number: ")
    # Check two things: length is 4, and all characters are digits
    if len(user_input) == 4 and user_input.isdigit():
        code2 = word_to_list(user_input)
        print(f"Success! Your converted list: {code2}")
        break  # Exit the loop since we have valid input
    else:
        print("Invalid input! Please enter exactly 4 digits (no letters or symbols).")

Key changes explained:

  • Repeating input with a loop: The while True loop runs non-stop until we hit the break statement. This ensures we keep asking for input until it's valid.
  • Better input validation: Added user_input.isdigit() to make sure the input is actually a number (not something like "abcd" or "12a3"). This prevents errors when we try to convert characters to integers.
  • Improved function: Rewrote word_to_list with a list comprehension (cleaner than the for loop you had) and made it return the list instead of just printing it. Now code2 will hold the actual converted value for you to use later.
  • Clearer prompts: Added a friendly input prompt and descriptive error messages so the user knows exactly what's expected.

If you don't care about checking for non-digit characters (though I recommend you do), you can simplify the condition to just len(user_input) == 4—but be aware that this will cause an error if the user enters non-numeric characters.

内容的提问来源于stack exchange,提问作者Darnell Winchester

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:23:37