【问题标题】:How to remove certain types of code from loop如何从循环中删除某些类型的代码
【发布时间】:2020-05-12 07:21:42
【问题描述】:

您好,有人可以帮忙做一些相当简单的事情。在输入姓名 john 或 John 之前,我有以下代码可以输入姓名。然后它将打印一个字符串,列出输入的错误名称。我遇到的问题是它要求用户在打印字符串后再次输入名称。 任何帮助都会很棒。

我的代码如下:

user_input=""
c = []
while user_input != "John" or user_input != "john":
    a = (input("Please enter your name:"))
    b = c.append(a)
    if a == "John" or a == "john":
        print ("Incorrect names are:" + str(c[0:-1]))

谢谢

【问题讨论】:

  • while user_input != "John" or user_input != "john" 应该是 while user_input != "John" and user_input != "john"。每个字符串都与一个 不同,因为它不能同时等于它们。
  • 你永远不会改变user_input 所以它总是"" 并且总是!= "John"
  • 使用while user_input.lower() != "john":可以轻松避免与条件混淆

标签: python list while-loop append


【解决方案1】:

你永远不会更新user_input,而且你有两次相同的条件,你可能会问直到你有john,然后打印,同样b没有用append修改当前列表:

user_input=""
wrong = []

while user_input != "John" and user_input != "john": # and use an 'and'
    user_input = input("Please enter your name:")
    wrong.append(user_input )

print ("Incorrect names are:", c[:-1])

【讨论】:

    【解决方案2】:

    打破它!

    user_input=""
    c = []
    while user_input != "John" or user_input != "john":
      a = (input("Please enter your name:"))
      b = c.append(a)
      if a == "John" or a == "john":
          print ("Incorrect names are:" + str(c[0:-1]))
          break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多