python - 如何通过不同的函数PYTHON正确传递变量
问题描述
我正在为一个刽子手游戏工作几天。我目前正在制作这些功能。我研究了如何将局部变量传递给另一个函数,但它似乎不起作用。我假设问题出在主题 = start() 上。当我运行程序时,它完全忽略了用户输入的主题内容并直接转到 else 语句并打印 “这不是一个选项”,即使用户正确输入了其中一个选项。如何让 python 意识到def sub_theme()中的主题是历史(或用户输入的任何内容,但在这种情况下我只是使用历史)然后从那里继续?
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()
解决方案
首先,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()
推荐阅读
- python - 如何让我的 Tkinter Simpledialog 位于顶部?
- javascript - 点击 iframe 中的链接后的 Puppeteer 页面内容
- python - 如何检测点击了哪个按钮?(拼音)
- python - 为什么我的尝试无法捕捉到“6”-“7”的两种模式?_Sum67_python 编码
- javascript - 如何设置响应式弯曲背景图像..CSS
- android - 我制作了一个下载pdf的代码,但我不知道如何在下载后显示它
- python - 如何在 Chrome 选项 python selenium 中通过 xpath 找到元素
- .net-core - “指定的类型无效。” 在 .NET Core 3.1 中使用带有证书的 CMS 进行签名时出现异常
- python - 通过图像处理查找对象边缘的长度
- python-3.x - Pyspark StreamingQueryException local using query.awaitTermination() - 本地 netcat 流与 jupyter notebook 上的 Pyspark 应用程序相结合