初学python函数

时间:2018-01-12 22:01:47

标签: python python-3.x python-requests programming-languages python-3.6

如此愚蠢的问题,但在下面的代码中,guess_compare函数失败了(我认为因为它无法引用输入'猜测'和'游戏字'。有关如何修复的任何见解?代码如下:

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()

2 个答案:

答案 0 :(得分:1)

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

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

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

使用无全局变量可能看起来更难,但它会消除一个错误来源。

如果你仍然想要它们,你需要声明你想在你的功能中使用全局:

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

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

答案 1 :(得分:0)

在这种情况下,您从未使用word_gen()分配game_word。你还必须先调用你的猜测函数。

在代码的最后一行尝试这个:

guesser()
game_word = word_gen()
guess_compare()
相关问题