首页 > 解决方案 > 如何将我的输入与多个可能的值进行比较?

问题描述

names = set()
emails = set()

print('-=-=- Menu -=-=-\n')

v = print('V. View Contacts')
a = print('A. Add New Contact')
c = print('C. Change Contact')
d = print('D. Delete Contact')
q = print('Q. Quit\n')

choice = str(input('Enter your choice: '))

if choice =='A' or 'a':
    print('-=-=- Enter the New Contact Name and Email -=-=-\n')
    
    add_name = str(input('Enter Contact Name: '))
    add_email = str(input('Enter Contact Email: '))
    names.add(add_name)
    emails.add(add_email)

    choice = str(input('Enter your choice: '))
    
elif choice == 'V' or 'v':
    print('-=-=-=-=-=-=-=-=-=-=-=-\n')
    print('-=-=-=- Name, Email -=-=-=-')
    print(names, emails, '\n')
    
    choice = str(input('Enter your choice: '))
    
elif choice == 'C' or 'c':
    print('-=-=-=-=-=-=-=-=-=-=-=-\n')
    changed_name = str(input('Enter Contact Name:'))
    changed_email = str(input('Enter Contact Email: '))

    names.update(changed_name)
    emails.update(changed_email)
    
elif choice == 'D' or 'd':
    print('-=-=-=-=-=-=-=-=-=-=-=-\n')
    delete_name = str(input('Enter Contact Name You Wish to Delete: '))
    delete_email = str(input('Enter the Email of the Contact Name: '))
    
    names.discard(delete_name)
    emails.discard(delete_email)
        
elif choice =='Q' or 'q':
    print('Goodbye')
    exit()    

即使我选择了不同的选项(例如查看联系人或更改联系人),它也会自动尝试添加新联系人。如果您能详细说明我的错误是什么以及我如何解决这些错误,我们将不胜感激。

标签: python

解决方案


你的条件是错误的。

if choice == 'A' or 'a':

被评估为if (choice == 'A') or ('a')并且'a'总是真实的。这就是为什么其他elif分支都没有被选中的原因。

任何一个

if choice == 'A' or choice == 'a':

或者更 Pythonic

if choice in ('a', 'A'):

甚至可能

if choice.lower() == 'a':

推荐阅读