-1

I need to use a variable that I created inside a function outside the function

ls1 = []
ls2 = []
def process_line(filename):
            i = 0
            global ls 1
            global ls2
            tup = ()
            while i<len(filename):
                if i%2==0:
                    ls1.append(float(filename[i]))
                else:
                    ls2.append(float(filename[i]))
                i += 1
            tup = tup + (ls1, )
            tup = tup + (ls2, )
            return tup
        process_line(filename)
if command == 'regular':
        k = 0
        print('Regular Transactions:')
        while k<7:
            print('{}: +{:.2f} -{:.2f}'.format(weekdays[k], ls1[k], ls2[k]))

however, it is written that ls1 and ls2 are not defined. how to call the variable?

khelwood
  • 55,782
  • 14
  • 81
  • 108
ygnaiyu
  • 7
  • 2
  • This might help: https://stackoverflow.com/questions/423379/using-global-variables-in-a-function – Grzegorz Skibinski Sep 05 '19 at 21:22
  • To use a value outside of a function, you should `return` the value from the function. – zvone Sep 05 '19 at 21:23
  • You never even call the function, and it doesn't seem like what you really want is to "use a variable that I created inside a function outside the function". What you want is to use the value returned from the function, aka the tuple of `ls1` and `ls2` – Jim Nilsson Sep 05 '19 at 21:25
  • I'm not OP - why the downvote? – CPak Sep 05 '19 at 21:48
  • Someone revised this question so that their answer is now the posted code. @ygnaiyu, can you please revert the code to your original? – Mason Caiby Sep 05 '19 at 21:58
  • [Scope of Variables in Python](https://www.datacamp.com/community/tutorials/scope-of-variables-python) – Trenton McKinney Sep 06 '19 at 00:10

1 Answers1

2

You can return those variables as well. You have a few other issues as well:

def process_line(filename):
            i = 0
            ls1 = []
            ls2 = []
            tup= ()
            while i<len(filename):
                if i%2==0:
                    ls1.append(float(filename[i]))
                else:
                    ls2.append(float(filename[i]))
                i += 1
            tup = tup + (ls1, )
            tup = tup + (ls2, )
            return tup, ls1, ls2
tup, ls1, ls2 = process_line(filename)
if command == 'regular':
        k = 0
        print('Regular Transactions:')
        while k<7:
            print('{}: +{:.2f} -{:.2f}'.format(weekdays[k], ls1[k], ls2[k])
        k += 1
  1. You need to call the function before it will run
  2. You need increment k in your while loop, or it will run forever.
  3. I'm also not sure what the tup is supposed to be? If you want to have a tuple of ls1 and ls1 you would probable just call tup = (ls1, ls2) and the end of process_line before the return line.
Mason Caiby
  • 1,846
  • 6
  • 17