如何为我的python猜谜游戏添加一个循环?

时间:2015-02-12 17:15:06

标签: python

所以我对python很新,因为我花了大部分时间使用HTML和CSS。我正在创建一个小项目来帮助我练习这是一个数字猜谜游戏:

guess_number = (800)

guess = int(input('Please enter the correct number in order to win: '))

if guess != guess_number:
    print('Incorrect number, you have 2 more attempts..')

    guess2 = int(input('Please enter the correct number in order to win: '))

    if guess2 != guess_number:
        print('Incorrect number, you have 1 more attempts..')

        guess2 = int(input('Please enter the correct number in order to win: '))

    if guess2 != guess_number:
        print()
        print('Sorry you reached the maximum number of tries, please try again...')

    else:
        print('That is correct...')


elif guess == guess_number:
    print('That is correct...')

所以我的代码目前在运行时工作,但我更喜欢它,如果它循环而不是我必须放置多个if和else语句,这使得编码大块。我知道有大约一百万个其他问题和例子是相似的,但我需要一个遵循我的编码的解决方案。

感谢。

3 个答案:

答案 0 :(得分:0)

如果您不知道需要预先循环多少次,请使用while循环。

correct_guess = False
while not correct_guess:
    # get user input, set correct_guess as appropriate

如果您确实知道了多少次(或有上限),请使用for循环。

n_guesses = 3
correct_guess = False
for guess_num in range(n_guesses):
    # set correct_guess as appropriate

    if correct_guess:
        # terminate the loop
        print("You win!")
        break
else:
    # if the for loop does not break, the else block will run
    print("Out of guesses!")

答案 1 :(得分:0)

拥有一个包含额外允许答案数量的计数器:

guess_number = 800
tries_left = 3

while tries_left > 0:
    tries_left -= 1
    guess = int(input('Please enter the correct number in order to win: '))
    if guess == guess_number:
        print('That is correct...')
        break
    else:
        print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no')  + ' more attempts..')

答案 2 :(得分:0)

如果您选择了自己选择的答案,则会收到错误TypeError: Can't convert 'int' object to str implicitly。添加str()以将尝试转换为字符串。见下文:

guess_number = 800
tries_left = 3

while tries_left > 0:
    tries_left -= 1
    guess = int(input('Please enter the correct number in order to win: '))
    if guess == guess_number:
        print('That is correct...')
        break
    else:
        print('Incorrect number, you have ' + (str(tries_left) if tries_left > 0 else 'no')  + ' more attempts..')