是否可以在python脚本中拥有多个全局变量?
import os,csv,random
def user():
global Forname
Forname = input('What is your forname? ').capitalize()
while True:
try:
global answerr
answerr = input('Welcome to the phone troubleshooting system '
'\nApple\nSamsung '
'\nOut of the following options enter the name of the device you own ').lower()
except ValueError:
continue
if answerr in ('apple','samsung'):
break
myfile = open(answerr+'_device.csv','r')
answer = input(Forname + ', do you have anymore problems? ').lower()
if 'yes' in answer:
#do whatever
else:
#do whatever
使用全局变量'answerr'我想打开一个csv文件,并用他们输入的forname引用用户,但我想在def函数中通过我的代码多次使用它们。如果你不明白我的要求,我会事先道歉,鉴于我还是一名学生,我对编码比较新。
答案 0 :(得分:3)
当然有可能。但是绝对没有理由在此代码中使用任何全局变量,更不用说多个。
函数的关键是它可以返回一个值:
def user():
forename = input('What is your forename? ').capitalize()
return forename
答案 1 :(得分:0)
我可以在Python脚本中拥有多个全局变量吗?
是的,以及如何:
如果您在模块的顶级分配任何变量,例如:n = "Stackoverflow!"
,那么您的变量会自动变为全局变量。所以,让我们说我们有这个模块:
#globals.py
x = 2 + 2
y = 5 + x
x
和y
都是全局变量,这意味着它们可以被函数,类等访问。 *记住模块顶层的任何赋值实际上都是全局的(这就是我们所说的全局范围,它可以包含与内存允许的一样多的变量)。这就像您发布的代码一样。但是,我们不能拥有的是任何范围内的相同命名变量:
same = 20
same = "s"
print(same)
将打印s,而不是20。
希望你能发现这有用:-)