使用特定输入突破while循环

时间:2019-04-02 23:33:31

标签: python loops input while-loop

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

[ ]

我尝试将0强制转换为int,但出现相同的问题...

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

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

5 个答案:

答案 0 :(得分:0)

input()返回一个string,并且永远不会是==0的{​​{1}}的一个。
在比较之前,您可以将int强制转换为inpint,也可以将要匹配的值{0转换为string'0'),即:

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

inp广播到int

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

答案 1 :(得分:0)

如您所说,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 :(得分:0)

您需要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 :(得分:0)

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。

答案 4 :(得分:0)

“如果您给某人一条鱼,他们一天就会吃一顿饭”这句话,我们有理由要求提供一个最小,完整,可验证的示例。您将问题命名为“打破while循环”,但这并不是真正的问题。 break语句未执行,这会使您认识到if条件正在评估为False,因此最小示例为“为什么inp == 0评估为False?”,而不是非最小的“为什么整个while循环没有达到我的期望?”简单地将问题分解为最小的部分通常足以解决问题:如果您查看了inp == 0的值并且看到它的值为False,那么应该检查一下{ {1}},发现它是inp而不是'0'

相关问题