简体   繁体   English

Python-从main()中的另一个python文件调用2个函数

[英]Python - calling 2 functions from another python file in main()

I created 2 different python files. 我创建了2个不同的python文件。 The first file named "game.py" has the code: 第一个名为“ game.py”的文件具有以下代码:

h = int(input("Pick number 1 or 2: "))

def game():

    if h == 1:
        print ("You lose!")
    if h == 2:
        print ("You win!")

def play_again():

    rounds = input("Play again? (Y/N): ")
    if rounds == "Y":
        game()
    if rounds == "NO":
        print ("Game Over")

As shown, I have 2 functions in this file. 如图所示,此文件中有2个函数。

Then I created another file with my main function that calls these 2 functions. 然后,我用主函数创建了另一个文件,调用了这两个函数。 The following is the code inside it: 以下是其中的代码:

import game

def main():

    game.game()

    game.play_again()

main()

When I run this on the console, it prints "Pick number 1 or 2: ". 当我在控制台上运行它时,它会显示“ Pick number 1 or 2”。 But if I run it again, it prints "Play again? (Y/N): ". 但是,如果我再次运行它,它会显示“再次播放?(是/否):”。

How do I fix this so that it only prints "Pick number 1 or 2 : " whenever I run the code? 如何解决此问题,以便在运行代码时仅打印“ Pick number 1 or 2:”?

maingame.py: maingame.py:

import game

game.game()

if __name__ == "__main__":
    print("maingame.py is being run directly")
else:
    print("maingame.py is being imported into another module")

game.py: game.py:

def game():
    h = input("Pick number 1 or 2:\n")
    if h == 1:
        print("You lose!")
    if h == 2:
        print("You win!")
    play_again()

def play_again():
    rounds = raw_input("Play again? (Y/N): ") # just use input() for python3
    if rounds == 'Y':
        game()
    if rounds == 'N':
        print("Game Over")

See also: What does if __name__ == "__main__": do? 另请参阅: __name__ ==“ __main__”怎么办?

and: Python 2.7 getting user input and manipulating as string without quotations 和: python 2.7获取用户输入并以不带引号的字符串形式进行操作

You can delete the three bottom lines from maingame.py but you should read the associated link to understand what if __name__ == "__main__": does and why. 您可以从maingame.py中删除三行内容,但是您应该阅读相关链接,以了解if __name__ == "__main__":和原因。 Normally you would just write: 通常,您只需要写:

if __name__ == "__main__":
    main()

And this will ensure that your file will run, beginning with main(), when called from the command line. 这样可以确保从命令行调用时,文件将从main()开始运行。

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

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