使用函数外部的变量 (Python)

编程入门 行业动态 更新时间:2024-10-25 01:36:37
本文介绍了使用函数外部的变量 (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

所以我又开始学习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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 07:01:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   函数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!