2015-10-16 66 views
0

我在這裏絕望。試圖爲我的一個課程做一個程序,並且遇到很多麻煩。我添加了一個輸入循環,因爲部分要求是用戶必須能夠輸入儘可能多的代碼行。問題是,現在我得到了索引超出範圍的錯誤,我認爲這是因爲我打破了停止循環。在python中,我可以在不使用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 == "": 
     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) 

我絕對是一個業餘的和可以使用的所有幫助/意見,我可以得到的。

非常感謝

+0

第一個建議:總是在你的文章中包含完整的錯誤信息。此外,總是說出你想要你的代碼做什麼,並解釋它目前的做法是不同的。 – BrenBarn

+0

「text」變量的定義在哪裏? – GingerPlusPlus

回答

0

你重新分配在每個循環迭代的TextInput變量。相反,你可以嘗試像:

textinput = "" 
while True: 
    current_input = (input("Please enter an English phrase: ")).lower() 
    if current_input == "": 
     break 
    else: 
     textinput += current_input 
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() 
2

在while循環,因爲你正在測試的TextInput ==「」後,你已經設置的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) 

(順便說一句,你沒有定義的文本或者當您寫了「在文本行」,你從來沒有真正使用「線」,用於循環只是小紙條看出來!對,運氣好的話)

0

可以繼續讀數據和處理它通過使用iter 2參數形式分開:

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)的做法相同。

所以上面的代碼打印他讀到的內容,直到用戶輸入空行。

相關問題