Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set constants in module by function and use it in another function in python?

I want to get in print A2. What is the best way to do that?
(for any numbers and types of constants):

VAR1=1
VAR2=2

def choose_var(variation):
    if variation == 1:
        VAR1 = "A"
        VAR2 = 2
    elif variation ==2:
        VAR1 = "B"
        VAR2 = 3 
        
def get_some_stuff():
    return str(VAR1 + VAR2)
    
choose_var(1)
print(get_some_stuff())

without passing VAR1 and VAR2 to get_some_stuff()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to make both variables global, by default they’re local to the method

def choose_var(variation):
    global VAR1, VAR2
    if variation == 1:
        VAR1 = "A"
        VAR2 = 2
    elif variation == 2:
        VAR1 = "B"
        VAR2 = 3

And fix the concatenation between int and str

def get_some_stuff():
    return f"{VAR1}{VAR2}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading