在python中编写正确函数的正确方法

时间:2020-09-05 20:05:06

标签: python-3.x function recursion

因此,我是python的新手,我尝试制作一个随机数游戏生成器作为练习。您需要在有限的尝试次数中猜测随机数。这是我的代码。

import random

rand_num  = random.randint(1,6)

print("\nNUMBER GUESSING GAME")
lives = 5

def guess():
    guess = int(input("Input guess: "))
    return guess

print(rand_num) #to see the correct answer

x = guess()
if x == rand_num:
    print("Good job! YOU WIN.\n")

else:
    while x != rand_num:
        
        if x == rand_num:
            print("Good job! YOU WIN.\n")
            break

        lives -= 1
        print("Incorrect. Please try again")
        guess()

        if lives == 0:
            print("YOU LOSE.\n")
            break

因此,如果您的第一个猜测是错误的,并且在随后的尝试中找到了正确的答案,则游戏将无法识别它。

谢谢。

1 个答案:

答案 0 :(得分:2)

您在正确的轨道上。将来,请逐步通过程序来思考每行的工作以及该顺序是否具有逻辑意义。

您的代码中只有一个实际错误:在while循环中调用x时,您没有在代码中收集新的guess值。其他元素是正确的,只是顺序混乱。这是一个更合乎逻辑的顺序,已修复了收集问题,

import random

rand_num  = random.randint(1,6)

print("\nNUMBER GUESSING GAME")
lives = 5

def guess():
    guess = int(input("Input guess: "))
    return guess

print(rand_num) #to see the correct answer

x = guess()
if x == rand_num:
    print("Good job! YOU WIN.\n")
else:
    while x != rand_num:
        # 1) Notify the user
        print("Incorrect. Please try again")
        # 2) Decrement remaining guesses
        lives -= 1
        # 3) Check if maximum number of guesses
        # reached - end if yes
        if lives == 0:
            print("YOU LOSE.\n")
            break
        # 4) Get a new guess 
        x = guess()
        # 5) Compare            
        if x == rand_num:
            print("Good job! YOU WIN.\n")

您可能想通知您的玩家猜数字的范围是多少。您还可以扩展此练习,并编写几个难度级别,每个难度级别范围不同(例如,简单级别1-6,中等级别1-20等),供玩家选择。


正如@Stef在评论中提到的那样,从技术上讲更干净,更常见的是将猜测数字(生存)条件作为while循环条件的一部分,

import random

rand_num  = random.randint(1,6)

print("\nNUMBER GUESSING GAME")
lives = 5

def guess():
    guess = int(input("Input guess: "))
    return guess

print(rand_num) #to see the correct answer

x = guess()
if x == rand_num:
    print("Good job! YOU WIN.\n")
else:
    while (x != rand_num) and (lives > 0):
        # 1) Notify the user
        print("Incorrect. Please try again")
        # 2) Decrement remaining guesses
        lives -= 1
        # 3) Get a new guess 
        x = guess()
        # 4) Compare, enf if correct             
        if x == rand_num:
            print("Good job! YOU WIN.\n")

# If ending because no more guesses left 
if lives == 0:
    print("YOU LOSE.\n")

我在每种情况下都使用括号,这里没有必要,也不必考虑样式。我喜欢这样分开条件。

此外,如果所有的猜测都已用尽,那么"YOU LOSE.\n"部分现在将显示在末尾。

一个注意事项:使用现在的代码,您的播放器实际上可以猜测6次,一开始是一次,而while循环中是另外5次。