首页 > 解决方案 > 如何通过不同的函数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()

标签: python

解决方案


首先,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()

推荐阅读