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

Python用户输入数据类型验证问题:判断字符串或数字

问题分析与修复方案

Hey there! Let's break down why your current code isn't behaving as expected, then fix it to meet your requirements.

Why your code isn't working

The core issue here is that input() always returns a string in Python—so wrapping it in str() doesn't do anything useful, and it will never throw a TypeError. That means your except block never runs, even when someone enters a number (since the input is still a string like "123").

Fixed Code

Here's a revised version that properly checks if the input is a number (integer or decimal) and prompts the user accordingly:

while True:
    member = input('Are you a child or adult member? ')
    # Check if the input is a number
    try:
        # Try converting the input to a float—if it works, it's a number
        float(member)
        print('Please input letters')
    except ValueError:
        # Conversion failed: input is non-numeric
        # Optional: Add validation for "child" or "adult" here
        if member.lower() in ['child', 'adult']:
            print(f"Got it, you're a {member} member!")
            break  # Exit the loop once valid input is received
        else:
            print("Oops, please enter either 'child' or 'adult' (letters only).")

How this works

  • Skip unnecessary str() conversion: Since input() already gives a string, we don't need to wrap it.
  • Number check via type conversion: We try converting the input to a float—this works for both integers (like "10") and decimals (like "12.5"). If it succeeds, we know the input is numeric and show the "Please input letters" message.
  • Non-numeric input handling: If the conversion fails (throws a ValueError), we then check if the input is one of the expected values (child/adult). You can adjust this part to fit your exact needs.

Alternative: Check for integers only

If you only need to block whole numbers (not decimals), you can use the isdigit() method instead (note: this won't catch negative numbers like "-5"):

while True:
    member = input('Are you a child or adult member? ')
    if member.isdigit():
        print('Please input letters')
    elif member.lower() in ['child', 'adult']:
        print(f"Got it, you're a {member} member!")
        break
    else:
        print("Please enter either 'child' or 'adult'.")

内容的提问来源于stack exchange,提问作者R.Edwin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:04:56