【问题标题】:Can I make a print statement run before a module I imported?我可以在我导入的模块之前运行打印语句吗?
【发布时间】:2021-02-23 19:39:10
【问题描述】:

我是 python 和一般编码的初学者,我想知道如何在我导入的模块之前运行打印语句。我正在做一个猜数游戏,在我组合所有模块的主文件中,我有一个通用函数可以一起运行所有代码。最好是我展示我的代码,以便你们更好地理解我正在处理的内容:

import random
import lvl1
import time

level1 = lvl1.Level_1_activated()

# This is the main file combining everything together to make this game playable

introduction = """
Hello and welcome to NumGuess by Sava. Here is a little bit about the game:
The game works by having 3 levels, each where you must pick a number between a range of
1-10 (level 1), 1-20 (level 2), and 1-50 (level 3).
You are given 5 attempts in the first level, 10 in the second level, and 20 in the final one.
You can also access a hint by typing ‘hint’. You win the game by picking the right number in each level.
You lose the game when you run out of tries. You can get a free bonus with 5 extra tries if you type ‘hlp’. 





"""
def start_game(time, lvl1):
    print(introduction)
    level1
    
    
start_game(time, lvl1)

这只是主模块的代码,我有 lvl1 的代码(这是我的“游戏”的第一级),我有一个类,它包含所有函数,然后参与 while 循环.我还将显示该文件:

import random
import time

# I will fist make variables for the time breaks. S is for short, M is for medium and L is for long

S = 0.2
M = 0.7
L = 1.1

class Level_1_activated():





    def get_name(self):

        # This function simply asks the name of the player

        name = input("Before we start, what is your name? ")

        time.sleep(S)
        print("You said your name was: " + name)

    def try_again(self):

        # This asks the player if they want to try again, and shows the progress of the level
        
        answer = (input("Do you want to try again? "))
        time.sleep(M)

        if answer == "yes":
            print("Alright!, well I am going to guess that you want to play again")
            time.sleep(M)

            print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
            # Return statement for if the player wants to play again 
            return True

        else:
            print("Thank you for playing the game, I hope you have better luck next time")
            # This is the return statement that stops the while loop 
            return False


    def find_rand_num(self, random):

        # This is the core of the level, where the player just chooses numbers between 1 and 10
        time.sleep(S)   

        print("The computer is choosing a random number between 1 and 10... beep beep boop")
        time.sleep(L)

        # The list of numbers for the level that the player is on at the moment
        num_list = [1,10]
        number = random.choice(num_list)

        ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10  "))
        print(ques)

        if ques == str(number):
            time.sleep(S)
            print("Congratulations! You got the number correct!")

            # Yet another return statement for the while loop
            return "Found"
            
        elif input != number:

            time.sleep(M)
            print("Oops, you got the number wrong")


    # This variable is fairly self-explanatory; it is what controls how many itterations there are in the while loop 
tries = 1


while tries < 6:

    if tries < 2:
        Level_1_activated().get_name()
    
    res = Level_1_activated().find_rand_num(random)
    if res == "Found":
        break

    checker = Level_1_activated().try_again()
    if checker is False:
        break
    
    tries += 1

如果你回到主文件中的这个函数:

def start_game(time, lvl1):
    print(introduction)
    level1

我故意将 print 语句放在模块之前以使其首先运行,并且我尝试了不同的方法,但似乎仍然无法掌握我在这里做错了什么。感谢您花时间阅读代码,如果您有任何可能的解决方案,我将不胜感激。

【问题讨论】:

  • 在顶层的 lvl1 模块中的循环应该在您的主模块调用的函数中,以便您可以在打印后调用它,而不是在导入模块时运行它.
  • 我尝试过这样做,但我不确定如何编写代码。对不起,我还在学习python。
  • 只写level1 绝对没有效果(除了验证您实际上有一个同名的变量)。您必须对值实际做一些事情 - 如果它是一个函数,则调用它,如果它是一个类的实例,则调用它的方法,等等。
  • 好的,我明白了,谢谢你的帮助。

标签: python python-import


【解决方案1】:

您可以做很多事情,其中​​之一是将您的代码封装成仅在您要求时运行的函数

lvl1

... #all the previous code    

def run_game(): 
    tries = 1
    while tries < 6:
        ...
        tries += 1

您还可以区分直接执行和导入,这样做很简单,包括以下检查(通常在文件末尾)

if __name__ == "__main__":
    #if true it mean that you're executing this module directly, otherwise it was imported
    #and you include here whatever you want that happens when you execute the module directly but not when is imported, like for example running a game
    run_game()
    

__name__是一个特殊变量,如果直接执行python会赋值"__main__",否则就是文件名,比如"lvl1"

在你的 main 你可以导入它并做类似的事情

import lvl1
...

def start_game():
    print(introduction)
    lvl1.run_game()

【讨论】:

  • 非常感谢!我需要删除指示尝试的打印语句,但我可以将它放在循环中的任何位置。你值得投票!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-12
  • 2020-01-27
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多