Python函数参数作为全局变量

编程入门 行业动态 更新时间:2024-10-09 04:20:41
本文介绍了Python函数参数作为全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我编写了以下函数,它接受一个变量input_name.然后,用户输入一些分配给input_name的值.我想知道使input_name在函数外部可访问的最佳方法.我知道在函数内部将变量定义为全局变量意味着可以在函数外部使用它.但是,在这种情况下,变量实际上是函数的参数,因此我不确定如何将其定义为全局变量.感谢您的帮助,请在下面找到有问题的代码:

I have written the following function, it takes in a variable input_name. The user then inputs some value which is assigned to input_name. I want to know the best way to make input_name accessible outside of the function. I know that defining a variable as global, inside a function, means that is can be used outside of the function. However, in this case the variable as actually a parameter of the function so I am not sure how to define it as a global variable. I appreciate any help with this, please find the code in question below:

def input(input_name, prompt): while True: data = raw_input(prompt) if data: try: input_name = int(data) except ValueError: print 'Invalid input...' else: if input_name >= 0 and input_name < 100: print 'Congratulations' break input_name = 'Please try again: ' else: print 'Goodbye!' break month = 0 day = 0 year = 0 century = 0 input(month, "Please enter the month (from 1-12, where March is 1 and February is 12): ") input(day, "Please enter the day (from 1-31): ") input(year, "Please enter the year (from 0 - 99, eg. 88 in 1988): ") input(century, "Please enter the century (from 0 - 99, eg. 19 in 1988): ") A = month B = day C = year D = century

推荐答案

最简单的方法是返回值,并将其分配给函数之外:

The simplest thing would be to return the value, and assign it outside the function:

def my_input(prompt): #.. blah blah.. return the_value month = my_input("Please enter the month") # etc.

更多推荐

Python函数参数作为全局变量

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

发布评论

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

>www.elefans.com

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