我如何在这个程序上使用while循环?

时间:2014-08-21 06:36:05

标签: python python-3.x

我需要知道如何在输出上使用while循环,以便继续输出“Line:”。 我想要做的是反转一个字符串中的每个单词,但是一旦我使用一个输入它就会停止,我需要使用while循环来继续获得输出,而while循环必须在空输入上停止。

我的解决方法:

a =input("Line: ")
b=a.split()
ans=''
while a != '':
  for word in b:
    word = word[::-1]
    ans=ans+word+' '
    a =input("Line: ")
    print(ans.rstrip())

我想要的输出:

Line: hello world
olleh dlrow
Line: extra
artxe
Line:

我得到的输出:

Line: hello world
olleh
Line: extra
olleh dlrow
Line: 

2 个答案:

答案 0 :(得分:0)

你可以这样试试

a=input('input:')
while a.strip()!='': 

    b=a.split()
    ans=''
    while len(b) >0 :
       word=b[0][::-1]
       ans+=word+" "
       b.pop(0)
    print ans
    a=input('input:')

#output i ma hsejar !aloH

答案 1 :(得分:0)

最简单的方法是使用while True循环和break

while True:
    line = input("Line: ")
    if not line:
        break
    ...

这是有效的,因为空字符串""评估False - y。您还可以使用列表提高代码效率:

words = []
while True:
    line = input("Line: ")
    if not line:
        break
    for word in line.split():
        words.append(word[::-1])
print(" ".join(words))

这避免了与+的常量字符串连接。