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

wpcxdonn  于 2021-06-24  发布在  Pig
关注(0)|答案(4)|浏览(340)

我很绝望。试着为我的一个班做一个程序却遇到了很多麻烦。我添加了一个输入循环,因为部分要求是用户必须能够输入任意多行代码。问题是,现在我得到了一个错误,索引超出了范围,我想这是因为我正在中断以停止循环。
这是我的密码:

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)

我绝对是个业余爱好者,我需要所有能得到的帮助/建议。
非常感谢

6yoyoihd

6yoyoihd1#

你的问题存在是因为 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()
ppcbkaq5

ppcbkaq52#

在每次循环迭代中重新分配textinput变量。相反,您可以尝试以下方法:

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

ivqmmu1c3#

在while循环中,因为在设置textinput=input()之后正在测试textinput==“”,这意味着当它中断时,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)

(顺便说一句,在编写“for line in text”时也没有定义文本,而且在for循环中也从未实际使用过“line”)。只是需要注意的小纸条,祝你好运!)

cygmwpex

cygmwpex4#

通过使用2参数形式的 iter :

from functools import partial

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

这比看上去要简单:当你付出时 iter 它将调用第一个参数并返回它所返回的内容,直到它返回与第二个参数相等的内容。
以及 partial(f, arg)lambda: f(arg) .
所以上面的代码打印他读到的内容,直到用户输入空行。

相关问题