【问题标题】:Breaking out of while loop with specific input使用特定输入打破 while 循环
【发布时间】:2019-08-24 09:06:21
【问题描述】:

我目前正在尝试接受用户输入,而不是在满足条件时退出它(在这种情况下为 0)。当 if 语句设置为 inp == '' 时,我得到了循环工作。当输入一个空字符串时,它会中断。但是,如果我将条件更改为 '' 以外的任何内容,例如 0,则代码不会跳出循环。

while True:
    inp = input("Would you like to add a student name: ")
    if inp == 0:
        break
    student_name = input("Student name: ")
    student_id = input("Studend ID: ")
    add_student(student_name, student_id)

我尝试将 0 转换为 int 但出现了同样的问题...

编辑:上面的代码循环不中断。

FIX:输入接受一个字符串,我将它与一个 int 进行比较。我需要将我的 0 转换为字符串,以便类型匹配。

【问题讨论】:

  • input() 函数返回一个字符串,因此它永远不会等于整数 0。
  • 啊,我看到了我的问题。我将输入转换为 int 却没有意识到输入本身是一个字符串。泰

标签: python loops input while-loop


【解决方案1】:

正如你所说,input 总是给你一个字符串。两种方式

inp = int(input("Would you like to add a student name: "))
if inp == 0:

inp = input("Would you like to add a student name: ")
if inp == '0':

【讨论】:

    【解决方案2】:

    您需要inp 来存储整数输入,但input() 默认存储一个字符串

    while True:
        inp = int(input("Would you like to add a student name: "))
        if inp == 0:
            break
        student_name = input("Student name: ")
        student_id = input("Studend ID: ")
        add_student(student_name, student_id)
    

    不过,如果您要求他们指出某事,您可能应该使用distutils.util.strtobool(),它接受各种输入,例如0nno 来表示否。

    【讨论】:

      【解决方案3】:

      input() 返回一个string,并且永远不会是==0,这是一个int
      您可以在比较之前将(又名类型转换)inp 转换为 int 或将匹配的值(0)转换为 string'0'),即:

      if inp == str(0): # or simply inp == "0"
         ...
      

      inp 转换为int

      if int(inp) == 0:
          ...
      

      【讨论】:

      • str(0) 而不是"0"?
      【解决方案4】:
      while True:
          inp = input("Would you like to add a student name: ")
          if len(inp) == 0 or inp =="": #checking the if the the length of the input is equal to 0 or is an empty string 
              break
          student_name = input("Student name: ")
          student_id = input("Studend ID: ")
          add_student = (student_name, student_id)
      
      print ("The file list-{}.csv is created!".format("something"))
      

      如果这是你想要的,请告诉我。 您不能使用 int,因为如果长度不为 0,它将需要一个整数,这是因为“int”类型的对象没有 len。

      【讨论】:

        【解决方案5】:

        按照“如果你给某人一条鱼,他们将有一天的食物”,我们要求提供一个最小、完整、可验证的示例是有原因的。您将问题命名为“打破while循环”,但这并不是真正的问题。 break 语句没有被执行,这应该让您意识到if 条件正在评估为False,因此最小示例将是“为什么inp == 0 评估为False?”,而不是非最小的“为什么整个while循环没有达到我的预期?”简单地将问题缩减到最小的组件通常足以解决问题:如果您查看了 inp == 0 的值并看到它是 False,那么您应该检查 inp 的值并查看它是'0' 而不是0

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多