【发布时间】: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!!"