python简单帮助(NameError:名称未定义)

时间:2020-09-17 02:30:19

标签: python-3.x

每当我运行时,它就会得到:

Traceback (most recent call last):
  File "main.py", line 130, in <module>
    while is_playing_cg:
NameError: name 'is_playing_cg' is not defined  

我希望用户能够按1或2选择要使用的游戏模式,然后一旦按下它就开始。我不知道为什么要这么做。只要修复,就可以正常运行。

新修改

现在,它只是循环播放,并一遍又一遍地说1或2。

import random

is_playing_cg = False
is_playing_hg = False

def game_select_screen():
    
    #Game Select Screen
    print("""
    ._________________________________.
    |                                 |
    |  ~ Welcome To Guess-A-Number ~  |
    |               ~~~               |
    |     ~ Press 1  OR  Press 2 ~    |                   
    |     You ^ Guess | PC ^ Guess    |
    |_________________________________|""")                               
   
    selecting = True
   
    while selecting:
        
        print()
        game_mode = input("1 OR 2: ")
    
        try:
            int(game_mode)
        except ValueError:
            print("This is not a Number.")
        else:
            
            game_mode = int(game_mode)

        if game_mode == 1:
            is_playing_hg = True
            
        elif game_mode == 2:
            is_playing_cg = True
            

    
             
#Defining Random Number for human guess
def play_human_guess():
    num = random.randint (1,10)
    print()
    print("Im Thinking of a Number 1 Through 10.")
    print("You Have 3 Chances.")
    chances = 3
    game_fisnished = False
    
    #Game is playing (Human Guesses)
    while not game_fisnished:
            guess = input("> Take A Guess: ")
             
            #Accept only numbers
            try:                   
                int(guess)
            except ValueError:
                print("This is not a Number.")
            else:
                
                guess = int(guess) 
                if guess < num:
                    chances -=1
                    if chances == 0:
                        print()
                        print("Sorry You Guessed Too Many Times.")
                        game_fisnished = True
                    elif chances !=0:
                        print()
                        print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
                elif guess > num:
                    chances -=1
                    if chances == 0:
                        print()
                        print("Sorry You Guessed Too Many Times.")
                        game_fisnished = True
                    elif chances !=0:
                        print()
                        print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
                else:
                    print()
                    print("Congradulations, You Won!")
                    game_fisnished = True
                    
#Game Ended
def end():
    print()
    print("Thanks For Playing!")
    
    


#Setting up for computer guess    
def play_computer_guess():
    print()
    print("Pick a Number 1 Through 10")
    print("I Have 3 Chances to Guess Your Number.")
    chances = 3
    game_fisnished = False
    
    #Game is playing (Computer Guess)
    while not game_fisnished:
            guess1 = input("Is your number 5?")
            
    
    
    
    
                    
    
                   

    
#Show Game Select Screen    
game_select_screen()



while is_playing_cg:
    #Start Game
    selecting = False
    play_computer_guess()
    
    answer = input("""
Do You Want to Play Again? (y/n) : """)
    if answer == "n":
        is_playing_cg = False



 

while is_playing_hg:
    #Start Game
    selecting = False
    play_human_guess()
    
    answer = input("""
Do You Want to Play Again? (y/n) : """)
    if answer == "n":
        is_playing_hg = False
        
end()

3 个答案:

答案 0 :(得分:1)

变量is_playing_cg仅在创建它的“块”中可用。 块是函数/循环/ if语句/等等。 在程序中,您需要全局初始化变量,以便可以在多个函数中调用它们。

祝你好运!

答案 1 :(得分:0)

您正在代码顶部的条件语句中定义is_playing_cg。因此,如果未选择该选项,那么当您进入后一个条件语句时,它从未听说过该变量...,并且未在命名空间中定义它。因此,您可以在顶部定义它,并给它一个默认值(False)或更优,因为您只有2个选项,只需使用一个变量来控制计算机/人。

这是一个玩具示例:

selection = int(input('enter 1 for human, 2 for computer: '))

if selection == 1:
    human_play = True
elif selection == 2:
    human_play = False

else:
    # make some loop that asks for input again or such...
    pass

# later on...

if human_play:
    # ask human for input...

else:
    # have AI make turn


#if needed, you can also handle special cases like this:

if not human_play:
    # do something unique to computer turn ...

其他信息...

因此,您对更新中的变量的作用域有所了解。您正在函数内部定义这些变量,并且将默认值置于函数外部时,它们不在同一范围内,因此您在函数内部所做的任何操作都会丢失。因此,您需要将函数更改为可以返回所需模式的某种东西,并在函数调用中捕获它,例如:

def ... :
    # input ...

    if game_mode == 1:
        human_playing = True
        selecting = False
        
    elif game_mode == 2:
        human_playing = False
        selecting = False

    return human_playing   # this will return T/F back to the function call

再后来:

#Show Game Select Screen    
human_playing = game_select_screen()

while not human_playing:
    #Start Game
    selecting = False
    play_computer_guess()
    
    answer = input("""
Do You Want to Play Again? (y/n) : """)
    if answer == "n":
        is_playing_cg = False

while human_playing:
    #Start Game

(上面)对我有用,但是仍然弹出其他逻辑错误! :)开心

答案 2 :(得分:0)

该特定错误可能存在,因为您尚未在函数<rule name="SetPost" stopProcessing="false"> <match url=".*" /> <conditions logicalGrouping="MatchAll" trackAllCaptures="true"> <add input="{REQUEST_METHOD}" pattern="^PUT$" /> </conditions> <serverVariables> <set name="{REQUEST_METHOD}" value="POST" /> </serverVariables> <action type="Rewrite" url="{R:0}" logRewrittenUrl="true" /> </rule> 中使用is_playing_cg时将其定义为全局变量。只需将game_select_screen放在函数global is_playing_cg的开头,告诉python您要使用全局变量而不是创建作用域变量。