2017-10-08 40 views
0

我正在嘗試編寫一個函數,稍後在我的程序中調用該函數,現在不重要。第一步是一個函數,提示用戶輸入,直到用戶返回。它也只允許一次輸入一個字符,我已經計算出來但沒有麻煩,因爲只有提供一個字符時它纔會循環。 例如,現在如果輸入'hi',它將提示用戶您一次只能輸入一個字符,但是如果輸入'h',它將不再請求並且將結束循環。當輸入鍵是輸入時停止的功能

def get_ch(): 
    string = '' 
    ch = input('Enter a character or press the Return key to finish: ') 
    while len(ch) == 1: 
     return ch 
     string += ch 
     ch = input('Enter a character or press the Return key to finish: ') 
     if ch == '': 
      break 
    while len(ch) > 1: 
     print("Invalid input, please try again.") 
     ch = input('Enter a character or press the Return key to finish: ') 

print(get_ch())  

回答

1

你似乎越來越混在一起returnbreakcontinue語句。 return ch將結束該功能的執行,這意味着第一個while只能執行一次。 下面的函數應該不斷循環並建立一個字符串,直到按下回車鍵而沒有輸入。

def get_ch(): 
    string = '' 
    while (True): 
     ch = input('Enter a character or press the Return key to finish: ') 
     if (len(ch) == 1): # single char inputed 
      string += ch 
      continue 
     if (len(ch) == 0): # "enter" pressed with no input 
      return string 
     # if (len(ch) > 1) 
     print('Invalid input, please try again.') 
+2

括號中'if's和'while's是多餘的 – nutmeg64

+1

消化道出血太感謝你了,我想我需要查看更多。 – manoman181