Sangwon Chae
Sangwon Chae

Reputation: 13

Why doesn't program print value?

I am wondering why the following program does not print 'b'. It is is very simple code; I think it must work; and do not know the reason why it doesn't.

def a():
    if b > 10:
        print 'b'
        sys.exit(1)

# main
while 1:
    a()
    b += 1

b is global variable. Actual code is more complicated but the structure is the same as mine. I guess when I call a() function and if b is greater than 10, it shows 'b'. However, it does not go inside if-statement.

Would you help me out how to solve?

Thanks.

Upvotes: 0

Views: 119

Answers (5)

Vidul
Vidul

Reputation: 10528

Global vars are not the usual way to go. You may prefer the usage of nested functions instead:

import sys

def outer(value=0):
    count = [value]
    print "started at:", count[0]
    def inner(x=1):
        print "current val:", count[0]
        count[0] += x
        if count[0] > 10:
            print "stopped at:", count[0]
            sys.exit(0)
    return inner

f = outer(5)
while True:
    f(1)

Upvotes: 0

bpgergo
bpgergo

Reputation: 16037

just my 2 cents: forget global variables.

anyway, this should work

def a():
    global b
    if b > 10:
        print 'b'
        sys.exit(1)

EDIT FUUUUUUUUUUUUUUU

Although I fully agree with Jackob on how you should use functions arguments and avoid globals, just for the record, here's the solution with global:

def a():
    global b
    if b > 10:
        print 'b'
        sys.exit(1)

# main
b = 0
while 1:
    a()
    b += 1

Upvotes: 0

jgomo3
jgomo3

Reputation: 1223

You need to define b before "+="ing it.

def a():
    if b > 10:
        print 'b'
        sys.exit(1)

# main
b = 0 # HERE
while 1:
    a()
    b += 1

By the way, as many had told you: avoid globals.

Upvotes: 0

jadkik94
jadkik94

Reputation: 7068

Another answers suggests not using globals, and I agree. If you still want to use globals, you should define b outside of the loop first.(if you do, then please post the complete code, because apart from that, it should work (and it does)).

Now, global b in the function definition is not necessary, because python guesses it is a global variable when you try to access it before assigning. But since it is not defined it raises an NameError:

NameError: global name 'b' is not defined

If you don't see that, so there's something else, you're not showing the actual code that has a problem.

This gives you in the end, something similar:

import sys
def a():
    global b
    if b > 10:
        print 'b'
        sys.exit(1)

b = 0
# main
while 1:
    a()
    b += 1

Upvotes: 0

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

Globals are horrid learn not to use them, try something like this

import sys
def a(value):
    if value > 10:
        print value
        print "Greater than 10!"
        sys.exit(0)
b = 0
while True:
    a(b)
    b += 1

Upvotes: 4

Related Questions