2017-06-14 153 views
1

我的循环似乎工作正常,直到我离开输入空。我希望它只是为了循环“输入新的单词或整数”,但它正在经历循环并输出else语句“多个字符类型”。如果任何人可以建议,我将不胜感激。虽然循环打印else语句

#hard code number 
number=90 


#whileloop 
while True: 
    enter_text = input("enter word or integer): ") 
     print()#loop if empty 


    #check if all alpha 
    if enter_text.isalpha(): 
     print(enter_text, "is all alphabetical characters! ") 
     break 


    #check<90>90 
    elif enter_text.isdigit(): 
     if int(enter_text) > number: 
      print(enter_text, "is a large number") 

     if int(enter_text) <= number: 
       print(enter_text,"Is smaller than expected") 
     break 


    #if conditions are not meet, multiple characters  
    else: 
     print(enter_text,'multiple character types') 
+0

是的,如果输入是全部字母,打印输出,停止代码。如果所有的数字都按照数字打印输出进行评估,则停止代码,如果输入空白打印(“输入文字或整数”),则如果bot alpha和数字打印“多字符类型”重新运行代码。希望这是明确的。 – john

回答

1

你可以这样说:

#hard code number 
number=90 


#whileloop 
while True: 
    enter_text = raw_input("enter word or integer): ") 
    print()#loop if empty 


    #check if all alpha 
    if enter_text: 
     if enter_text.isalpha(): 
      print(enter_text, "is all alphabetical characters! ") 
      break 


     #check<90>90 
     elif enter_text.isdigit(): 
      if int(enter_text) > number: 
       print(enter_text, "is a large number") 

      if int(enter_text) <= number: 
        print(enter_text,"Is smaller than expected") 
      break 


     #if conditions are not meet, multiple characters  
     else: 
      print(enter_text,'multiple character types') 
    else: 
     print('You didn\'t write anything') 
1

因为enter_text是不是因而isalpha(),而不是ISDIGIT(),所以这跳入其他部分。行为完全正确。

您应该首先检查它是否为无。你可以这样做,例如像这样:

if not enter_text: # will check if enter_text exists and is not a empty string e.g. "" 
    continue 
elif enter_text.isalpha(): 
    print(enter_text, "is all alphabetical characters! ") 
    break 
#check<90>90 
elif enter_text.isdigit(): 
    if int(enter_text) > number: 
     print(enter_text, "is a large number") 

    if int(enter_text) <= number: 
      print(enter_text,"Is smaller than expected") 
    break 
#if conditions are not meet, multiple characters  
else: 
    print(enter_text,'multiple character types')