-1

I don't know the rules to defining a var. Why doesn't this work? Is there a way that I can send many variables from one function to another or do I need to re-define the variables in each function to make them last?

def first():
  great = 1
  print(great)
  second()

def second(great):
  # Do I need to re-define great here
  if great == 1:
    cool = 3001
  third(great, cool)

def third(great, cool):
  if great > 1:
    print(cool)
  # To make great = 1 here?

first()

3 Answers3

2

Because great is defined within the scope of first(), not second(). You need to change your functions to:

def first():
    great = 1
    # code
    second(great)

def second(great):
    if great == 1:
        # code
spicypumpkin
  • 1,209
  • 2
  • 10
  • 21
2

Look up globals in Python. This works:

def first():
   global great
   great = 1
   print(great)
   second()

def second():
   if great == 1:
     print ("awesome")
   else:
     print("God damn it!")

first()

In your original functions, great was only in the local scope of first(); second() had no idea what/where great was. Making great global (i.e. available to other functions) solves your issue.

Edit: The code above does work, but perhaps a better way to do things (per the suggestion below), would be like this:

great = 1

def first():
    print(great)
    second()

def second():
    if great == 1:
        print("awesome")
    else:
        print("God damn it!")

Or an even better way would be to actually pass the value of great (as a parameter) to each function.

Community
  • 1
  • 1
blacksite
  • 12,086
  • 10
  • 64
  • 109
  • Your code won't work. You need to define global variable `great` before getting him into the function. `global` doesn't create a variable, but gets a variable from the outer scope. – Cheyn Shmuel Feb 08 '17 at 04:00
1

The variable great is defined locally in first(). It doesn't exist in second(). You are testing for equality on a variable that doesn't exist.

Pass the variable from one function to the other...

def first():
  great = 1
  print(great)
  second(great)

def second(great):
  if great == 1:
    print ("awesome")
  else:
    print("God damn it!")

first()
Skinner
  • 1,461
  • 4
  • 17
  • 27