使用函数外部的变量 (Python) [英] Using a variable outside of the function (Python)

查看:35
本文介绍了使用函数外部的变量 (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我又开始学习python了,目前我正在制作一个迷你电影推荐器.我希望我的代码更容易理解,所以我总是尝试使用 def 使代码变得简单.我的问题是;

so I've started learning python again and I'm currently making a mini movie-recommendator. I want my code to be a little bit more understandable so I'm always trying to use def to make the code simple. My problem is ;

def welcome():
    print("""Welcome to the low budget film recommender!
             Here you can tell me what kind of movies do you like or what movie did you watch
             and I'll suggest you a movie from my database according to that.""")
    name = input("But first I need to learn your name:>> ").capitalize()
    print(f"Nice to meet you {name}")
    return name

我想在函数外部(实际上在另一个函数内部)使用 name 变量,但它给了我 NameError 并说name"未定义.如何解决此问题并在函数外部使用 name 变量?

I want to use the name variable outside of the function(inside another function actually) but it gives me NameError and says "name" is not defined. How can I fix this and use the name variable outside of the function?

推荐答案

您可以将变量 name 声明为全局变量.

代码 -

You can declare the variable name as global variable.

Code -

def welcome():
    global name
    print("""Welcome to the low budget film recommender!
             Here you can tell me what kind of movies do you like or what movie did you watch
             and I'll suggest you a movie from my database according to that.""")
    name = input("But first I need to learn your name:>> ").capitalize()
    print(f"Nice to meet you {name}")
    return name


def second_function():
    welcome()
    print(name) #prints the value of name in this function which was defined in the welcome()

second_function()

这篇关于使用函数外部的变量 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆