跳转到内容

Python 编程/决策控制/解答

来自 Wikibooks,一个开放世界的开放书籍

< 返回问题

编写一个程序,让用户猜测你的名字,但他们只有 3 次机会,否则程序将退出。

name = raw_input("What's my name? ")
answer = "Jack"
attempt = 0

if name == answer:
	print("That's correct!")
else:
	while name != answer and attempt < 2:
		attempt = attempt + 1
		name = raw_input("That's incorrect. Please try again: ")
		if name == answer:
			print("That's correct!")
		elif attempt == 2:
			print("You've exceeded your number of attempts.")

另一个使用 sys 库的解决方案。

import sys
count = 0
while count < 3:
        guess = raw_input("Guess my name: ")
 
        if guess == "joe":
                print ("Good guess!")
                sys.exit()
 
        elif count < 2:
                print ("\nTry again!\n")
 
        if count == 2:
                print ("Too many wrong guesses, terminating")
 
        count = count + 1


更好的方法

name = "roger"

x=0

while x < 3:
    guess = raw_input("What's my name?: ")
    if(guess != name):
        print "Wrong"
        x += 1
        if(x==3):
            print "You've reached the max attempt!"
    else:
        print "Correct"
        break
华夏公益教科书