【问题标题】:I am having problems combining input functions, for-loops and if-statements on my code [closed]我在我的代码中组合输入函数、for循环和if语句时遇到问题[关闭]
【发布时间】:2019-12-27 02:32:07
【问题描述】:

希望你们一切都好。我的代码有点情况。我正在尝试创建一个程序,用户可以在其中创建自己的用户名,然后将此用户名与现有用户列表进行比较。问题是当用户尝试输入他们自己的用户名时,程序会继续并在现有列表中循环每个字母,然后给你一个提示。我真正想让程序做的是评估整个输入(用户名单词)并将其与我现有的列表进行比较。

current_users=['gin','obi','joe','chris','ralph']

new_users=input('enter user name:')

for new_user in new_users:

    if new_user in current_users:

        print(f"{new_user} is already taken, please choose another username")

    else:

        print('username succesfully created')

我猜有一个我还没有理解的理论概念。如果您能帮我修复代码,我将不胜感激。

【问题讨论】:

  • new_user 不是一个列表。当你循环它时,你只会得到字母。你可以这样做:if new_user in current_users:
  • 循环 string 会逐字母循环 - 您不必要地在 for 结构中循环它。
  • 你的意思是允许用户输入多个用户名吗?

标签: python input


【解决方案1】:

您正在迭代新用户名(逐个字符),实际上,您不需要迭代,只需使用in:

if new_users in current_users:
    print(f"{new_users} is already taken, please choose another username")
else:
    print('username succesfully created')

如果用户名不区分大小写,您也可以使用if new_users.lower() in map(str.lower, current_users)。

【讨论】:

    【解决方案2】:

    new_users 是一个字符串,因此 for new_user in new_users 循环遍历字符串的字符,而不是单词...如果您希望有多个用户,您可以拆分字符串并循环遍历结果数组。

    即用空格分隔的用户名

    new_users = 'bob bill jim tod'  # result of an input let's say
    new_users = new_users.split()   # default splits by ' '
    # current code
    

    或如@MrGreek 所述。你可以跳过循环直接进入in 语句。

    【讨论】:

      【解决方案3】:

      您的“for”循环正在遍历输入中的字母。消除“for”循环,它应该可以工作。

      current_users=['gin','obi','joe','chris','ralph']
      
      new_users=input('enter user name:') 
      
      for new_user in new_users: #note that new_users is the string you just asked for, you're looping through each character. 
      
          if new_user in current_users:
      
              print(f"{new_user} is already taken, please choose another username")
      
          else:
      
              print('username succesfully created')
      

      【讨论】:

      • 这是来自 OP 的代码。我复制了它并添加了一条评论,解释了哪里出错以及如何出错。这不是我的代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-16
      • 2017-07-19
      • 2021-02-02
      • 1970-01-01
      相关资源
      最近更新 更多