初级python函数

2024-06-13 15:01:48 发布

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

这是个愚蠢的问题,但是在下面的代码中guess\u compare函数失败了(我认为是因为它不能引用输入'guess'和'game word'。有什么关于如何修复的见解吗?代码如下:

import random

max_guesses=1
guess=""
game_word=""

def word_gen():
    potential_guesses=["hello", "test", "never"]
list_length=int(len(potential_guesses))

 game_word=potential_guesses[random.randint(1-1,list_length-1)]
    print (game_word)

def guesser():
   guess=input("give a letter...")
   print(guess)

def guess_compare():
    if guess==game_word[0]:
        print("correct")
    else:
        print("wrong")

guess_compare()

Tags: 函数代码importgamedefrandomlengthmax
2条回答

在本例中,您从未将游戏\u word分配给单词\u gen()。您还必须首先调用猜测函数。你知道吗

在代码的最后一行尝试以下操作:

guesser()
game_word = word_gen()
guess_compare()

我会停止使用全局变量,你倾向于通过在本地声明相同名称的变量来隐藏它们,假设你设置了一个全局变量,但它只是本地变量。你知道吗

我重新构造了您的一些代码,因此它应该在没有全局变量的情况下工作:

import random

def word_gen():
    """Returns a ramdom choice word form a fixed list"""
    return random.choice(["hello", "test", "never"])  

def guesser():
   """Returns an input from the user - ask for 1 letter"""
   return input("give a letter...")

def guess_compare():
    """Main game loop for "guess my word character by character".

    Gets a random word. Asks for letters until the correct
    one is given. Prints out status messages regarding correctness
    of guesses. Stops when all characters were guessed correctly."""

    game_word = word_gen()

    soFar = ""   # for status-message, text correctly guessed so far
    for ch in game_word:        # check for every character in word
        while(guesser() != ch):   # guess until char is correct
            print("wrong")
        else:                     # finally, one more ch solved...
            soFar += ch
            print("you guessed correctly: " + soFar)
    print("you solved it!")     # finished


guess_compare()  # start the game

不使用globals似乎更难,但它消除了一个错误源。你知道吗

如果仍然需要它们,则需要声明要在函数中使用全局:


一些具有全局变量的函数:

def myFunc():
    global myVar        # declare that we use the global here
    myVar += 20         # modifying the global one here
    print (myVar)

def myOtherFunc():
    myVar = "something"   # this is just local , not the global one
    print (myVar)

myVar = 25
print ("myVar: ", myVar)

myFunc()
print ("after myFunc: ", myVar)

myOtherFunc()
print ("after myOtherFunc: ", myVar)

输出:

myVar:  25
45
after myFunc:  45
something
after myOtherFunc:  45

相关问题 更多 >