[英]Breaking out of while loop with specific input
我目前正在尝试接受用户输入,而不是在满足条件时中断输入(在这种情况下为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()
返回一个string
并且永远不会==
到0
,这是一个int
。
您可以铸造(又名类型转换) inp
到int
或值以匹配( 0
)到string
( '0'
的比较,即,前):
if inp == str(0): # or simply inp == "0"
...
将inp
转换为int
:
if int(inp) == 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':
您需要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()
,该方法接受各种输入,例如0
或n
或no
来表示否。
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。
按照“如果您给某人一条鱼,他们会吃一天的食物”的思路,我们就有理由要求一个最小,完整,可验证的示例。 您将问题命名为“打破while循环”,但这并不是真正的问题。 break
语句未在执行,这应该使您意识到if
条件的计算结果为False
,因此最小示例将为“为什么inp == 0
结果为False
?”,而不是非最小的“为什么整个while循环都没有达到我的期望?” 简单地将问题分解为最小的部分通常足以解决问题:如果您查看了inp == 0
值并且发现它为False
,那应该导致您检查inp
的值并查看它为'0'
而不是0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.