而循环打印其他声明

时间:2017-06-14 09:28:12

标签: python-3.x

我的循环似乎正常工作,直到我将输入留空。我希望它只是循环到“输入新单词或整数”,但它正在循环并输出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')

2 个答案:

答案 0 :(得分: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 :(得分:1)

因为enter_text不是isalpha()而不是isdigit(),所以这会跳转到else部分。行为是完全正确的。

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

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')