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

Python入门:如何限制通讯录姓名输入仅为纯字母字符串

通讯录管理程序:纯字母姓名输入验证解决方案

问题描述

我是Python初学者,正在开发一个通讯录管理程序,希望实现添加联系人时,姓名输入仅接受纯字母组成的字符串,禁止输入数字或其他字符。我尝试编写了输入验证代码但无法生效,程序仍能接受包含数字的输入,请求提供简单易懂的解决方案,不要使用复杂的高级代码。

原程序代码

contact = {}

def display_contact():
    for name, number in sorted((k,v) for k, v in contact.items()):
        print(f'Name: {name}, Number: {number}')

while True:
  try:
    choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Print \n 7. Exit \n Enter "))
  except ValueError:
    print("请输入1-7之间的数字")
    continue
  
  if choice == 1:
    # 原无效验证代码
    while True:
      try:
        name = str(input("Enter the contact name "))
        if name != str:
      except ValueError:
        continue
      else:
        break

    while True:
      try:
        phone = int(input("Enter number "))
      except ValueError:
        print("Sorry you can only enter a phone number")
        continue
      else:
        break
    contact[name] = phone
    
  elif choice == 2:
    search_name = input("Enter contact name ")
    if search_name in contact:
      print(search_name, "'s contact number is ", contact[search_name])
    else: 
      print("Name is not found in contact book")
      
  elif choice == 3:
    if not contact:
      print("Empty Phonebook")
    else: 
      display_contact()
      
  elif choice == 4:
    edit_contact = input("Enter the contact to be edited ")
    if edit_contact in contact:
      phone = input("Enter number")
      contact[edit_contact]=phone
      print("Contact Updated")
      display_contact()
    else:
      print("Name is not found in contact book")
      
  elif choice == 5:
    del_contact = input("Enter the contact to be deleted ")
    if del_contact in contact:
      confirm = input("Do you want to delete this contact Yes or No? ")
      if confirm == 'Yes' or confirm == 'yes':
        contact.pop(del_contact)
      display_contact()
    else:
      print("Name is not found in phone book")

  elif choice == 6:
    sort_contact = input("Enter yes to print your contact")
    if sort_contact.lower() == 'yes':
      print("通讯录内容:")
      display_contact()
    else:
      print("Phone book is printed.")
  elif choice ==7:
    break
  else:
    print("请输入1-7之间的有效选项")

尝试的无效验证代码片段

if choice == 1:
    while True:
      try:
        name = str(input("Enter the contact name "))
        if name != str:
      except ValueError:
        continue
      else:
        break

问题分析

你原来的验证逻辑完全错误:name != str是拿字符串对象和str类型做比较,这永远为True,而且根本没检查输入的字符是否都是字母,同时代码还存在语法错误(if语句未闭合)。

简单解决方案

使用Python字符串内置的isalpha()方法,这个方法会返回True当且仅当字符串中的所有字符都是字母,并且字符串不为空。

修改添加联系人时的姓名验证循环如下:

if choice == 1:
    # 修正后的姓名验证逻辑
    while True:
        name = input("Enter the contact name ").strip()  # 去除首尾空格
        if name.isalpha():
            break  # 输入符合要求,跳出循环
        else:
            print("姓名只能包含纯字母,请重新输入!")

    # 电话号码验证(优化提示为中文)
    while True:
      try:
        phone = int(input("Enter number "))
      except ValueError:
        print("抱歉,只能输入数字电话号码,请重新输入!")
        continue
      else:
        break
    contact[name] = phone

额外优化建议

  1. 给主菜单输入添加try-except,防止用户输入非数字导致程序崩溃(已在代码中添加)
  2. 修正第6个选项的逻辑,改为判断输入是否为yes后直接展示通讯录(已修正)
  3. 修复第5个选项中display_contact缺少括号的问题(已修正)
  4. 可将所有提示信息改为中文,提升使用友好度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:31:11