1

I'm trying to print an array in python this way:

ord = []
def printTest():
    global ord
    print ', '.join(ord)


def main():
    ord = ["a","b"]
    printTest()

main()

But it prints only a new line empty. How can I solve this?

Thanks!!

2
  • You are not calling printTruthTable ! Commented May 6, 2016 at 14:03
  • 2
    Usage of global variables is a bad idea in general. See c2.com/cgi/wiki?GlobalVariablesAreBad if you interested in that idea. Commented May 6, 2016 at 14:04

3 Answers 3

2

I think you are missing global ord in the main method.

Sign up to request clarification or add additional context in comments.

2 Comments

I already correct my answer. Sorry, I forget the call of the method.
The global ord in the main method solve this! Thanks!
2

Use global for main function:

def printTruthTable():
    print ', '.join(ord)


def main():
    global ord
    ord = ["a","b"]

main()
printTruthTable()

But good practice looks like this:

def TruthTable(ord):
    return ', '.join(ord)

def main():
    # some code
    return ["a","b"]

print TruthTable(main())

Comments

1

global means that future assignments to this variable will be in the global scope. When you just use ord in printTruthTable(), you don't need to say global because the global scope is already checked when you refer to a variable. When you assign ord, however, you need to say that we are creating a global variable, not a local variable. Therefore, move global ord from printTruthTable() to main(). On the side, ord is a bad name because it shadows the built-in function. Also, global variables are almost never needed. In this case, just pass ord as an argument instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.