在几次错误的猜测之后,如何添加提示以显示?

2024-09-27 00:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

print("\t \t \t What's the password?")
print("\t you have 5 chances to get it right! \n")

secret_word = "green"
guess = ""
guess_count = 0
guess_limit = 5
out_of_guesses = False
hintA = "Ashtons' favorite color"
print("Here is a hint: "+ hintA)
#while loop
while guess != secret_word and not (out_of_guesses):
  if guess_count < guess_limit:
    guess = input("Enter guess: ")
    guess_count += 1
  #elif guess_count == 2:
    #print("Here is a hint: "+ hintA)
  
  else:
    out_of_guesses = True

if out_of_guesses:
  print("You have been locked out!")
else:
  print("Correct password!")

我不知道如何在2到3次猜测之后添加提示,因为没有它就不可能做到。另外#中的内容是我的尝试


Tags: ofsecrethereishavecountpasswordout
3条回答
secret_word, guess_limit, hintA = "green", 5, "Here is a hint: Ashtons' favorite color"

print("\t\t\tWhat's the password?\n\tyou have " + str(guess_limit) + " chances to get it right!\n")

for i in range(guess_limit):
    if i > guess_limit // 2:  # more than half of the attempts are exhausted
        print(hintA)
    if input("Enter guess: ") == secret_word:
        print("Correct password!")
        break
else:
    print("You have been locked out!")

您可以尝试以下方法:

print("\t \t \t What's the password?")
print("\t you have 5 chances to get it right! \n")

secret_word = "green"
guess = ""
guess_count = 0
guess_limit = 5
out_of_guesses = False
hintA = "Ashtons' favorite color"
#while loop
while guess != secret_word and not (out_of_guesses):
  if guess_count < guess_limit:
    if guess_count == 2:
      print("Here is a hint: "+ hintA)
    guess = input("Enter guess: ")
    guess_count += 1
  #elif guess_count == 2:
    #print("Here is a hint: "+ hintA)
  
  else:
    out_of_guesses = True

if out_of_guesses:
  print("You have been locked out!")
else:
  print("Correct password!")

将输入移到if...else语句之外,并更改if...else语句的位置

print("\t \t \t What's the password?")
print("\t you have 5 chances to get it right! \n")

secret_word = "green"
guess = ""
guess_count = 0
guess_limit = 5
out_of_guesses = False
hintA = "Ashtons' favorite color"
#while loop
while guess != secret_word and not (out_of_guesses):
  guess = input("Enter guess: ")
    
  if guess_count == 2:
    print("Here is a hint: "+ hintA)
    guess_count+=1
  
  elif guess_count != guess_limit:
    guess_count += 1
  
  else:
    out_of_guesses = True

if out_of_guesses:
  print("You have been locked out!")
else:
  print("Correct password!")

输出:

What's the password?
         you have 5 chances to get it right! 


Enter guess: red
Enter guess: blue
Enter guess: yellow
Here is a hint: Ashtons' favorite color
Enter guess: purple
Enter guess: beige
Enter guess: light green
You have been locked out!

相关问题 更多 >

    热门问题