如何编写代码实现对age的整数格式校验、空值校验及非正整数校验并返回对应重试提示
Fixing Age Input Validation in Python
Let's walk through fixing your code step by step. First, let's break down the key issues in the original code, then build a clean, functional version that meets all your validation requirements.
Key Issues in the Original Code
- Broken variable logic: Lines like
age = int(age) and int(age) <=0assign a boolean value toageinstead of properly checking the condition. - Unnecessary resets: Multiple
tryblocks overwriteagewithout meaningful validation, leading to lost input. - Confusing loop behavior: The
whileloop callsinput()multiple times in its condition, which creates messy user interactions. - Undefined
namevariable: The final print statement usesnamebut never collects that input from the user. - Vague error feedback: No distinct messages for empty input, non-integer values, or non-positive ages.
Corrected Code Implementation
Here's a robust version that handles all your validation needs with clear user prompts:
# First, collect the user's name (since it's used in the welcome message) name = input("Lütfen adınızı girin: ") # Initialize a flag to track valid age input valid_age = False age = None # Loop until we get a valid age while not valid_age: age_input = input("Lütfen yaşınızı girin: ").strip() # Check for empty input (including whitespace-only entries) if not age_input: print("Hata: Boş bir değer girdiniz. Lütfen geçerli bir yaş girin.") continue # Try converting input to an integer try: age = int(age_input) except ValueError: print("Hata: Geçerli bir sayı girmediniz. Lütfen tam sayı bir yaş girin.") continue # Ensure age is a positive number if age <= 0: print("Hata: Yaşınız pozitif bir tam sayı olmalıdır. Lütfen tekrar deneyin.") continue # If all checks pass, mark age as valid valid_age = True # Print the final welcome message print(f"Merhaba {name}, hoşgeldiniz!") print(f"Siz {age} yaşındasınız.")
How This Works
Let's break down the core functionality:
- Name Collection: We first get the user's name to use in the final greeting (since your original code references it).
- Loop Until Valid: The
whileloop keeps running until a valid age is entered, ensuring the user can't proceed without correct input. - Empty Input Handling: Using
strip()removes leading/trailing spaces, so even whitespace-only entries are treated as empty, with a specific error message. - Integer Validation: A
try-exceptblock catches cases where the input can't be converted to an integer, letting the user know they need to enter a number. - Positive Age Check: After confirming it's an integer, we check if it's greater than 0—if not, we prompt the user to enter a positive value.
- Clean Exit: Once all validation passes, we set
valid_agetoTrueto exit the loop and display the welcome message.
This approach gives clear, targeted feedback for every type of invalid input, making the user experience intuitive and straightforward.
内容的提问来源于stack exchange,提问作者Ahmet Uzunçayır
相关产品推荐
相关产品推荐

