Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...