简体   繁体   English

理解函数调用函数的问题

[英]Problem with understanding functions calling functions

I am new to python and have a problem with understanding functions and calling one function within the other.我是 python 的新手,在理解功能和调用另一个 function 时遇到问题。 I made some improvised code to show you my problem, I just keep on getting an error saying that variable "comp" from the function is not defined when I call it within the other function.. just don't understand.我编写了一些即兴代码来向您展示我的问题,我只是不断收到一个错误消息,当我在另一个 function 中调用它时,没有定义来自 function 的变量“comp”。只是不明白。 Help please, I am getting frustrated with this:)请帮忙,我对此感到沮丧:)

import random

def start_game():
    start=input("Would you like to start the game? y/n ").lower()


def c_turn():
    print("Computer's turn: ")
    comp=print(random.choice(["rock","paper", "scissors"]))
    return  comp

def p_turn():
    player=input ("Now it's your turn: ")
    return player

def compare():
    c_turn()
    p_turn()
    if comp=="rock" and player=="scissors":
        print("Computer wins")
    elif comp=="rock" and player=="paper":
        print("Player wins")
    elif comp=="scissors" and player=="rock":
        print("Player wins")
    elif comp=="scissors" and player=="paper":
        print("Computer wins")
    elif comp=="paper" and player=="scissors":
        print("Player wins")
    elif comp=="paper" and player=="rock":
        print("Computer wins")
    elif comp==player:
        print("IT'S A TIE!")

start_game()
compare()

As you are new to Python I suggest you to take a look at the following URL to understand the scope of variables before doing stuff with python. As you are new to Python I suggest you to take a look at the following URL to understand the scope of variables before doing stuff with python.
Scope of variables Scope 变量
Functions in python python 中的函数

As for the solution, you can convert your variables to global (as mentioned in the comments)至于解决方案,您可以将变量转换为全局变量(如评论中所述)

You can actually find these kinds of solutions by simply googling.您实际上可以通过简单的谷歌搜索找到这些类型的解决方案。 Anyways try referring to the links.无论如何尝试参考链接。 I hope it helps!我希望它有帮助!

You need to store the returned values from c_turn() and p_turn() so you can use them in the compare() function, otherwise they are simply discarded.您需要存储c_turn()p_turn()的返回值,以便可以在compare() function 中使用它们,否则它们将被丢弃。 For example:例如:

def compare():
    comp = c_turn()
    player = p_turn()
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM