2017-10-08 76 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