Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

python 3.x - cant get my while loops working the way i want it to

i am trying to get this code to work properly where if you input a number it will revert you back to the name=input prompt and once you enter alphabetical characters and not numerical characters it will allow you to move on to the next set of code but it keeps returning you to the name = input and doesnt let you through the rest of the code

def setup():
    global name
    global HP
    global SP
    global MP
    while True:
        try:
            name = input('can you please tell me your name?  ')
            name2=int(name)
            if  not name.isalpha==True and not name2.isdigit==False:
                break
                
                
        except Exception:
                print('please input your name')
                continue
    
    HP = randint(17,20)
    SP = randint(17,20)
    MP = randint(17,20)
    print('welcome ['+name+':]:  to the moon landing expedition')
question from:https://stackoverflow.com/questions/65598889/cant-get-my-while-loops-working-the-way-i-want-it-to

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a problem at name2=int(name) This causes an exception unless you type all numbers. In turn, this triggers the Exception and loops it forever. Your while loop seems fine.

What i think you should do:

while True:
    name = input('What is your name')
    isnum = False
    for i in name:
        if i.isnumeric():
            isnum = True
            break
    
    if isnum:
        print('Please type your name.')
        continue
    
    break

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...