【问题标题】:Assign value in dictionary to a variable from input [closed]将字典中的值分配给输入中的变量[关闭]
【发布时间】:2021-05-31 22:58:31
【问题描述】:
membership_status = {
's_member' : ['amanda', 'peter', 'alice', 'samuel', 'daniella'],
'not_a_member' : ['micheal', 'thomas', 'victor', 'adrienne', 'limy'],
}
eligible = membership_status['s_member']
not_eligible = membership_status['not_a_member']

username = input("Enter your username")
if username == eligible['']:
     print(f'welcome back {username.title()}')
if username == not_eligible['']:
     print(f'Aww sorry {username.title()}, you are no longer eligible to login')
else:
    print(f'user {username.title()} not found!')

我尝试运行此代码,但没有成功。

该代码用于在输入其姓名后检查某些个人的会员状态。我怎样才能做到这一点?

【问题讨论】:

  • eligible 在我看来不像字典。 eligible[''] 还能做什么?
  • 你怎么知道它不起作用?了解如何创建minimal reproducible example

标签: python list dictionary input


【解决方案1】:

您可以使用in 运算符。例如:

membership_status = {
    "s_member": ["amanda", "peter", "alice", "samuel", "daniella"],
    "not_a_member": ["micheal", "thomas", "victor", "adrienne", "limy"],
}

username = input("Enter your username: ")

if username in membership_status["s_member"]:
    print(f"welcome back {username.title()}")
elif username in membership_status["not_a_member"]:
    print(f"Aww sorry {username.title()}, you are no longer eligible to login")
else:
    print(f"user {username.title()} not found!")

打印:

Enter your username: alice
welcome back Alice

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2013-03-27
    相关资源
    最近更新 更多