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

Python双条件循环输入验证脚本开发需求:用户名与数量校验

Python Script for Username and Quantity Validation with Regex

Got it, let's put together a Python script that checks all your boxes—with clear validation, user-friendly prompts, and proper exit logic. Here's a step-by-step implementation:

Breakdown of the Solution

First, let's map out what we need to handle:

  • Prompt for username; exit immediately if the user presses Enter without input
  • Validate username is exactly 5-10 alphabetic characters (no numbers, symbols, or extra spaces)
  • Prompt for quantity only if the username is valid
  • Validate quantity is a numeric value (integer or float) between 0 and 100 inclusive
  • Print success details if both inputs pass, or specific error messages if not

Complete Script with Explanations

import re

def validate_username(username):
    # Regex: matches 5-10 uppercase/lowercase letters, no extra characters
    username_pattern = r'^[a-zA-Z]{5,10}$'
    return re.fullmatch(username_pattern, username) is not None

def validate_quantity(quantity_input):
    # First check if input is a valid numeric string (int or float)
    numeric_pattern = r'^\d+(\.\d+)?$'
    if not re.fullmatch(numeric_pattern, quantity_input):
        return False
    # Convert to float and verify it's within 0-100 range
    quantity = float(quantity_input)
    return 0 <= quantity <= 100

def main():
    while True:
        # Get username input (strip extra whitespace)
        username = input("Enter your username (press Enter to exit): ").strip()
        
        # Exit program if user submits empty input
        if not username:
            print("Exiting program...")
            break
        
        # Validate username and show error if invalid
        if not validate_username(username):
            print("❌ Error: Username must be 5-10 alphabetic characters only (no numbers/symbols).")
            continue
        
        # Get quantity input if username is valid
        quantity_str = input("Enter the quantity: ").strip()
        
        # Validate quantity and show error if invalid
        if not validate_quantity(quantity_str):
            print("❌ Error: Quantity must be a numeric value between 0 and 100 (inclusive).")
            continue
        
        # All checks passed—print results
        print(f"\n✅ Success! Username: {username}, Quantity: {quantity_str}\n")

if __name__ == "__main__":
    main()

Key Details

  • Username Validation: The regex ^[a-zA-Z]{5,10}$ ensures the entire input is 5-10 letters (uppercase or lowercase). re.fullmatch guarantees no extra characters slip through (like spaces or numbers).
  • Quantity Validation: We first confirm the input is a valid number (using ^\d+(\.\d+)?$ for integers like 42 or floats like 75.5), then convert it to a float to check it falls within the 0-100 range.
  • User Experience: The loop repeats until the user chooses to exit, and error messages are specific so the user knows exactly what went wrong.

Test Cases to Try

  • Valid flow: Username JaneDoe (6 letters) + Quantity 80 → Success message
  • Invalid username: JD (too short), John123 (has numbers), SuperLongName (12 letters) → Error prompts
  • Invalid quantity: abc (non-numeric), -10 (negative), 101 (over 100) → Error prompts
  • Exit: Press Enter at the username prompt → Program exits cleanly

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:34:52