【问题标题】:How can i use a while loop on this program?我如何在这个程序上使用 while 循环?
【发布时间】:2014-10-14 16:41:03
【问题描述】:

我需要知道如何在输出中使用 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: 

【问题讨论】:

  • 你有没有尝试在上面写while
  • 还是不知道怎么办?我试图做一个while循环和东西,但我得到一个不正确的输出:(
  • @jonrsharpe 认为Python 3 教程在这里更合适。
  • 那么,您的带有 while 循环的代码在哪里,到底有什么问题?

标签: python python-3.x


【解决方案1】:

你可以这样试试

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

【讨论】:

    【解决方案2】:

    最简单的方法是使用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))
    

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

    【讨论】:

    • 感谢您的回复!每次他们输入颠倒的东西时,我都需要打印出来。当没有检测到输入时,您的程序会打印出所有反转的输入。你能帮我把每一行的输入打印出来吗?
    • 您可以自己更改代码:将空列表的分配移至words,并在while 循环内调用print
    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多