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
767 views
in Technique[技术] by (71.8m points)

insert logic with while python

I have a bunch of list that contains some name who have access, if the name is true and on the list, then it will print welcome to that name, otherwise, if the user had more than 3 wrongs, then it will print sorry, you're more than 3 times wrong. for that logic, I use this

secret_word = ['Fachry', 'Amri', 'Hasbi']
word = ''
guess = 0
guess_limit = 3
out_of_guesses = False

while word != secret_word and not(out_of_guesses):
    if guess < guess_limit:
        word = input('What is your real name? ')
        guess += 1
    else:
        out_of_guesses = True
if out_of_guesses:
    print("Sorry, you're more than 3 times wrong")
else:
    print('Welcome mr ' + secret_word)

but when I input the name, no matter is true or not, it will repeat 3 times and will return "Sorry, you're more than 3 times wrong" even though the name is on the list

Expected results:

if I put one of the names inside the list, it will return welcome (the name itself), as long as the users didn't do 3 more times wrong names


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

1 Answer

0 votes
by (71.8m points)

You can use while-else and avoid initializing word and out_of_guesses outside while loop using below code

secret_word = ['Fachry', 'Amri', 'Hasbi']
guess_count = 0
guess_limit = 3

while guess_count < guess_limit:
    word = input('What is your real name? ')

    if word in secret_word:
        print('Welcome mr ' + word)
        break

    guess_count += 1

else:
    print("Sorry, you're more than 3 times wrong")

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

...