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

如何编写代码实现对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) <=0 assign a boolean value to age instead of properly checking the condition.
  • Unnecessary resets: Multiple try blocks overwrite age without meaningful validation, leading to lost input.
  • Confusing loop behavior: The while loop calls input() multiple times in its condition, which creates messy user interactions.
  • Undefined name variable: The final print statement uses name but 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:

  1. Name Collection: We first get the user's name to use in the final greeting (since your original code references it).
  2. Loop Until Valid: The while loop keeps running until a valid age is entered, ensuring the user can't proceed without correct input.
  3. Empty Input Handling: Using strip() removes leading/trailing spaces, so even whitespace-only entries are treated as empty, with a specific error message.
  4. Integer Validation: A try-except block catches cases where the input can't be converted to an integer, letting the user know they need to enter a number.
  5. 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.
  6. Clean Exit: Once all validation passes, we set valid_age to True to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 09:42:42