Python代码优化:实现输入非4位时支持重新输入的逻辑
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 Trueloop runs non-stop until we hit thebreakstatement. 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_listwith a list comprehension (cleaner than the for loop you had) and made it return the list instead of just printing it. Nowcode2will 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

