Python - 如何使IF语句依赖于用户的尝试?

时间:2014-11-02 18:45:20

标签: python if-statement

所以我正在创建一个代码,如果用户猜到了数字,他们就赢了。现在,如果他们在一次尝试中猜出这个数字,我想要“哇!你在第一次尝试时猜到了这个数字!”打印。但是,如果用户超过一次尝试猜测数字,我想要“Welldone你已经猜到了这个数字!”要显示。关于如何做到这一点的任何想法?

import random
n=random.randint(1,50)
playing = True
while playing:
   guess=int(input("Guess the number!"))
   if guess == n:
       print("Wow! You've guessed the number at the first attempt!")
       playing = False
   elif guess == n:
       print("Welldone, you have guessed the number!")

1 个答案:

答案 0 :(得分:0)

你可以只有一个新的变量来跟踪用户出错的次数,并将其包含在你的if / else语句中。像

这样的东西
attempts = 1
在你的while循环之外

。然后里面就像是

if guess == n and attempts == 1:
    print "WOW"
    playing = False
elif guess == n and attempts > 1:
    print "Well done"
    playing = False
attempts += 1 # increment attempts variable bc they guessed wrong. Go back to while loop