2017-06-14 99 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')