我的代码不理解列表中的字母,我希望有人帮我修复这个
usernames = (BTP, btp, Btp, BTp)
def username(usernames2):
if usernames == input('whats your username? : ')这是一个简单的用户名系统,我计划使用一个接口im制作。
发布于 2022-11-17 17:31:37
如果您没有声明BTP、btp、Btp和BTp,您将得到一个NameError
如果要使用字符串,则需要单引号或双引号:
usernames = ("BTP", "btp", "Btp", "BTp")这样您就可以创建一个包含四个字符串元素的元组。
下一个问题是您的if条件,因为您比较tuple是否等于一个字符串。
尝试将用户提供的输入存储在变量中:
def username(usernames):
user_input = input('whats your username?: ')
if user_input in usernames:
# Do something when username is found发布于 2022-11-17 17:30:56
usernames被定义为由4个项组成的元组,名称为BTP、btp、Btp和BTp。您在标题中说了“列表”,但是您的代码没有实际的列表。列表使用括号,元组使用括号。
无论如何,我假设您实际上希望检查用户的输入实际上是否等于字母"btp",并且希望检查不区分大小写,因此需要包含大写和小写的所有组合。
主要问题是,您没有在字符串周围放置引号,所以在代码中只有4个裸名,解释器希望前面已经定义了这些名称。但是,实际上您不必首先定义大写和小写的所有可能组合--有一种更简单的方法来进行不区分大小写的字符串比较,这里。
因此,您的代码只需如下所示:
usename = "btp"
def username(usernames2):
if input('whats your username? : ').lower() == username或者,如果要检查多个用户名,可以使用in操作符:
usenames = ["btp", "abc", "foo", "bar"]
def username(usernames2):
if input('whats your username? : ').lower() in usernameshttps://stackoverflow.com/questions/74479654
复制相似问题