Bipt
Bipt

Reputation: 1

Can i have multiple global varibles within a python script?

Is it possible to have more than one global variable within a python script?

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

Using the global variable 'answerr' I'd like to open a csv file, and the refer to the user with the forname they input, but I want to use them multiple times through out my code within def functions. I apologise in advance if you do not understand what I'm asking, I'm relatively new to coding given the fact that I'm still a school student.

Upvotes: 0

Views: 68

Answers (2)

GIZ
GIZ

Reputation: 4643

Can I have multiple global variables within a Python script?

Yes and here's how:

When you're assigning any variable at the top-level of a module like: n = "Stackoverflow!" then your variable is global automatically. So let's say we have this modules:

#globals.py
x = 2 + 2 
y = 5 + x 

both x and y are global variables which means they're accessible to functions, classes and so on. *Just remember any assignment at the top-level of a module is actually global (this is what we call a global scope and it can contain as much variables as your memory allows). This is just like the code you posted. However, what we cannot have is same named variables in any scope:

same = 20
same = "s" 
print(same) 

will print s, not 20.

Hope you'll find this helpful :-)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 600026

Of course it's possible. But there is absolutely no reason to use any global variables in this code, let alone multiple.

The point of a function is that it can return a value:

def user():
    forename = input('What is your forename? ').capitalize()
    return forename

Upvotes: 3

Related Questions