Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python if语句未在while循环中执行_Python_If Statement_Python 3.x - Fatal编程技术网

Python if语句未在while循环中执行

Python if语句未在while循环中执行,python,if-statement,python-3.x,Python,If Statement,Python 3.x,我必须编写一个程序,一个接一个地获取多个字符串,这些字符串由sentinel DONE终止,然后打印这个字符串列表,使其与最大字符串的长度对齐。这是我的密码: user = input("Enter strings (end with DONE):\n") totalString = "" while True: if user.lower() == 'done': break else: totalString = totalString +

我必须编写一个程序,一个接一个地获取多个字符串,这些字符串由sentinel DONE终止,然后打印这个字符串列表,使其与最大字符串的长度对齐。这是我的密码:

user = input("Enter strings (end with DONE):\n")
totalString = ""

while True:
    if user.lower() == 'done':
        break
    else:
        totalString = totalString + user + " "
        user = input("")

lst = totalString.split(" ")
max = 0

for i in range(len(lst)):
    if len(lst[i]) > max:
        max = len(lst[i])

for i in range(len(lst)):
    print("{:>{derp}}".format(lst[i],derp=max))

我遇到的问题是while循环中的if语句永远不会执行,因此它会卡在该循环中。

NB:假设代码是针对Python2.x的,但情况可能并非如此

首先,对于input(),您需要的是一个数值值,而不是字符串。 只是将您的输入()更改为原始输入()就帮了我的忙。 正如评论中指出的,OP可能使用的是Python 3


关于SO的问题解释了Python 2.x和3.x wrt input()与raw_input()之间的区别。

当您使用cmd运行代码时,
input
返回的字符串也包含返回字符(
\r

因此,当用户输入
“done”
时,
input()
实际上返回
“done\r”

一个简单的解决方案是在此处使用:


user=input(“”).strip(“\r”)

尝试在
while
循环之前打印
user
的值,因为它的末尾可能有一个
\n
。使用
user=user.strip()
修复该问题。它在我的系统上运行良好。我添加了python3x标记,因为您正在使用
input()
从用户那里获取字符串。@AshwiniChaudhary这是怎么回事?存在于
2.X
。。。哦,是印刷品()。没关系。@thegrinner是的,但在py2x中,输入充当
eval(raw_input())
,因此您不能使用它从用户那里获取字符串。还有几件事:1)使用
而1
而不是
而True
-在Python中,True只是一个变量,其值可以更改为任何值,因此,它需要额外检查
,而
循环2)在user.lower()中使用
如果“完成”;
-这是一种更具python风格的方法3),除非您需要
范围(len(lst))
的结果,否则使用
xrange
,这会更快,并且使用更少的内存光。编辑我的答案,大意是“首先使用input(),您需要的是一个数值而不是字符串。”-->wat这仍然不能回答为什么
if
条件没有执行。