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

Python干洗店服务程序:如何处理用户姓名输入首字母大写需求

Solution for Auto-Capitalizing Customer Names in Smiths Cleaners Program

Looking at your code, I'll help you fix both the name validation logic (which has a small bug) and implement automatic proper capitalization for customer names—even for multi-word names like "mary ann" or "JOHN DOE".

Modified Code

# Welcome message to the user
print("Welcome to Smiths Cleaners, offering the best dry-cleaning service around!\n")

# Loop to get valid customer name and auto-format it
while True:
    name_input = input("What is the customer's name? ").strip()
    # Validate: ensure every word in the name is alphabetic (allows spaces between names)
    if all(word.isalpha() for word in name_input.split()):
        # Auto-format to proper case (each word's first letter capitalized)
        formatted_name = name_input.title()
        break
    print("Invalid input: please enter a name using only letters and spaces.")

print(f"\nBelow is the price table for the services available for {formatted_name}")

Key Changes Explained

  • Fixed Name Validation: Your original check name.isalpha() or name.split() would accept invalid inputs like "123 " (numbers plus spaces). The new check all(word.isalpha() for word in name_input.split()) ensures every part of the name is made up of letters, while still allowing multi-word names (like first + last name).
  • Automatic Proper Capitalization: Instead of only using capitalize() when printing (which only capitalizes the first word and lowercases the rest), we use title() to format the name as soon as it's validated. This handles all cases:
    • Input john doe → Output John Doe
    • Input JOHN DOE → Output John Doe
    • Input jOhN sMiTh → Output John Smith
  • Added .strip(): This removes any accidental leading/trailing spaces from the user's input, so names like " jane " get cleaned up to "Jane".

内容的提问来源于stack exchange,提问作者Lauren.M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:53:08