我正在做一个man子手游戏几天。我目前正在做功能。我已经研究了如何将局部变量传递给另一个函数,但是它似乎没有用。我假设问题出在 theme = start()。。当我运行程序时,它完全忽略了用户输入的主题,直接进入else语句并打印”。 “不是选项” ,即使用户正确输入了其中一个选项也是如此。如何让python认识到 def sub_theme()中的主题是历史记录(或用户输入的任何内容,但在这种情况下,我只是使用历史记录),然后从那里继续? / p>
def start():
print("Welcome to hangman!!!")
print("Let's get started.")
theme = input("Okay I'll pick a word, all you have to do is pick a theme :) \n Themes to pick from: History, Companies, Geography, Music, Movies, Celebrities, and Sports Team! ")
return theme
def sub_theme():
#### If the user chooses History as their option ####
theme = start()
if theme.casefold() == 'History':
print("So your options are: Presidents or Vice Presidents.")
user_theme = input("So what's your choice? ")
if user_theme.casefold() == "Presidents":
secret_word = "George Washington"
print(secret_word)
print(secret_word)
#### if they type in something besides the options ####
else:
print("That wasn't an option.")
return
def hide_word():
#hides the word with underscores
hide = ""
secret_word = sub_theme()
for letter in secret_word:
if letter in [" " , "," , ":" , "'" , "-" , "_" , "&" , "é", '"', "/" , "." , "?" , "!"]:
hide = hide + letter
else:
hide = hide + "_ "
print(hide)
return(hide)
def play():
hide_word()
play()
答案 0 :(得分:0)
首先,string.casefold() == "History"
永远不会成立,因为casefold
扮演着lower
的角色,但更具侵略性。只需将“历史记录”更改为“历史记录”即可。
第二,您可能要研究classes。
这样,您可以将theme
(或其他任何东西,在本例中为secret_word)设置为self属性,并从类的所有函数中访问它,而不必在它们之间传递。
以下是您提供的代码的快速转换汇总:
class Hangman:
def __init__(self):
print("Welcome to hangman!!!")
print("Let's get started.")
theme = input("Okay I'll pick a word, all you have to do is pick a theme :) \n"
"Themes to pick from: History, Companies, Geography, Music, Movies, "
"Celebrities, and Sports Team! ")
if theme.casefold() == 'history':
print("So your options are: Presidents or Vice Presidents.")
user_theme = input("So what's your choice? ")
if user_theme.casefold() == "presidents":
self.secret_word = "George Washington"
else:
print("That wasn't an option.")
return
self.hide_word()
def hide_word(self):
hide = ""
for letter in self.secret_word:
if letter in [" " , "," , ":" , "'" , "-" , "_" , "&" , "é", '"', "/" , "." , "?" , "!"]:
hide = hide + letter
else:
hide = hide + "_ "
print(hide)
Hangman()