【问题标题】:Importing function in python在python中导入函数
【发布时间】:2014-01-09 21:32:07
【问题描述】:

我正在尝试创建菜单,用户可以在其中选择他/她想要运行的程序的哪个部分。当我导入函数时,计算机会自动运行它而不是等待用户输入。仅在调用时我该怎么做才能运行功能?我的代码:

    import hangman

    menu = raw_input("""Welcome to Menu, please choose from the following options: 
    1. Hangman game
    2.
    3. 
    4. Exit
    """)

    if menu == 1: 
        hangman()
    elif menu == 2:
        "Something"
    elif menu == 3:
        "Something"
    elif menu == 4:
        print "Goodbye"
    else:
        print "Sorry, invalid input" 

hangman.py 的代码如下所示:

import random

words = ["monitor", "mouse", "cpu", "keyboard", "printer",]  

attempts = [] # Stores user input

randomWord = random.choice(words) # Computer randomly chooses the word

noChar = len(randomWord) # Reads number of characters in the word

print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."

def game():    
    guess = raw_input ("Please choose letter")
    attempts.append(guess) # Adds user input to the list
    print (attempts)

    if guess in randomWord: 
        print "You have guessed the letter" 
    else: 
        print "Please try again"


while True:
    game()
    chance = raw_input ("Have a guess")
    if chance == randomWord:
        print "Congratulations, you have won!"
        break

【问题讨论】:

  • 相关:What does if __name__ == “__main__”: do?。并且使用hangman.hangman() 而不仅仅是hangman()... Python 的import 不像C 的include。它创建一个模块对象,其中包含您在该模块中定义的内容作为属性。
  • 假设你在hangman.py文件中有一个名为hangman的函数,你也可以使用from hangman import hangman
  • 您还需要将菜单转换为 int(或将菜单与字符串进行比较),因为 raw_input 返回一个字符串。尝试:menu = int(menu) except ValueError: print "that is not a valid option!!"

标签: python function import


【解决方案1】:

没有看到hangman.py,我会假设它直接包含运行刽子手游戏的代码,而不是包装在函数中。如果是这种情况,您创建了一个模块,没有功能(还)。

将该代码包装在

def run_hangman():
    # Your existing code, indented by 4 spaces
    # ...

像这样导入它:

from hangman import run_hangman

最后像这样调用函数:

run_hangman()

【讨论】:

  • 我添加了刽子手代码。问题可能是我已经在其中创建了一个函数
  • 不,问题是您的 while True: 块在函数中是 not - 这意味着它会在导入模块时立即执行。将它包装在一个函数def run_hangman(): 中,像我描述的那样导入那个函数,你应该很好。
【解决方案2】:

这里是开始菜单:

import hangman
option = raw_input('1) Start Normal\n2) Quick Start\n3) Default') # '\n' is a new line
if option == '1':
    hangman.main()
elif option == '2':
    hangman.run_hangman('SKIP')
elif option == '3':
    handman.run_hangman('Default User')

在您的刽子手代码中,您希望对其进行调制。你应该有这样的东西:

def main():
    stuff = raw_input('Starting new game. Please enter stuff to do things')
    run_hangman(stuff)


def run_hangman(options):
    if options == 'SKIP':
        important_values = 5
        vales_set_by_user = 'Player 1'
    else:
        values_set_by_user = options

    rest_of_code()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2018-06-05
    • 2017-05-18
    相关资源
    最近更新 更多