在python中,我可以在不使用break命令的情况下停止输入循环吗?

时间:2015-10-16 03:24:41

标签: python apache-pig latin

我在这里绝望。试着为我的一个班级做一个程序,并且遇到这么多麻烦。我添加了一个输入循环,因为部分要求是用户必须能够输入任意数量的代码行。问题是,现在我得到索引超出范围的错误,我认为那是因为我打破了停止循环。

这是我的代码:

print ("This program will convert standard English to Pig Latin.")
print("Enter as many lines as you want. To translate, enter a blank submission.")
while True:
    textinput = (input("Please enter an English phrase: ")).lower()
    if textinput == "":
        break

words = textinput.split()  
first = words[0]
way = 'way'
ay = 'ay'
vowels = ('a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U')
sentence = ""

for line in text:
    for words in text.split():
        if first in vowels:
            pig_words = word[0:] + way
            sentence = sentence + pig_words
        else:
            pig_words = first[1:] + first[0] + ay
            sentence = sentence + pig_words
print (sentence)

我绝对是一个业余爱好者,可以使用我能得到的所有帮助/建议。

非常感谢

4 个答案:

答案 0 :(得分:2)

在你的while循环中,因为你正在测试textinput ==""在你已经设置textinput = input()之后,这意味着当它中断时,textinput将永远是""!当您尝试访问单词[0]时,会出现索引超出范围错误; ""中没有元素,因此您将收到错误。

此外,由于您每次进行while循环时都会覆盖textinput的值,因此您无法实际跟踪用户输入的所有先前内容,因为textinput会不断变化。相反,您可以将while循环下的所有代码放入while循环中。尝试:

print("This program will convert standard English to Pig Latin.")
print("Enter as many lines as you want. To translate, enter a blank submission.")
while True:
    textinput = (input("Please enter an English phrase: ")).lower()
    if textinput == "":
        break
    words = textinput.split()  
    way = 'way'
    ay = 'ay'
    vowels = ('a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U')
    sentence = ""

    for word in words:
        for first in word:
            if first in vowels:
                pig_words = first[0:] + way
                sentence = sentence + pig_words
            else:
                pig_words = first[1:] + first[0] + ay
                sentence = sentence + pig_words
    print(sentence)

(顺便说一句,你没有定义文字,当你写#34; for line in text&#34 ;,你从来没有真正使用" line"在那个for循环中。只需要注意的小笔记,祝你好运!)

答案 1 :(得分:0)

您在每次循环迭代时重新分配textinput变量。相反,你可以尝试类似的东西:

textinput = ""
while True:
    current_input = (input("Please enter an English phrase: ")).lower()
    if current_input == "":
        break
    else:
        textinput += current_input

答案 2 :(得分:0)

您的问题之所以存在,是因为break语句只会突破while循环,然后会继续运行words = textinput.split()及以后。

要在收到空输入时停止播放,请使用quit()代替break

print ("This program will convert standard English to Pig Latin.")
print("Enter as many lines as you want. To translate, enter a blank submission.")
while True:
    textinput = (input("Please enter an English phrase: ")).lower()
    if textinput == "":
        quit()

答案 3 :(得分:0)

您可以使用2参数形式的iter

继续阅读数据并将其分开处理
from functools import partial

for line in iter(partial(input, "Eng pharse> "), ""):
    print(line) # instead of printing, process the line here

它比它看起来更简单:当你给iter 2个参数并迭代它返回的内容时,它将调用第一个参数并产生它返回的内容,直到它返回等于第二个参数的东西。

partial(f, arg)lambda: f(arg)的效果相同。

所以上面的代码打印了他读到的内容,直到用户输入空行。