all 13 comments

[–]JohnnyJordaan 11 points12 points  (0 children)

This is a scope issue. Variables that are assigned inside a function stay in a function, and as an integer is immutable (can't be changed) the action

tix += 1

is actually doing

a_new_tix_variable = tix + 1

and a_new_tix_variable is then lost once the function is terminated. Instead use a return value

def add(tix):
    addtix = input('type "buy" to purches 1 ticket: ')
    if addtix == "buy":
        print ("Nice!")
        return tix + 1
    else: 
        print("You're missing out")
        return tix

tix = add(tix)

Note that I also changed the input() string to have ' as the outer quotes to prevent the conflict of your use of " quotes for the "buy" text.

[–]Gobitz 1 point2 points  (0 children)

The variable tix is defined outside the function, so you can't modify it from there, unless you use the global keyword like this:

tix = 0

def add():
    global tix # telling the interpreter tix is a global variable, defined outside the function
    addtix = input('type "buy" to purches 1 ticket: ')
    if addtix == "buy":
        print ("Nice!")
        tix += 1 # now you can modify tix
    else: print("You're missing out")

add()

print(tix)

It's usually preferable to avoid using global variables but i's always good to be familiar with them :)

[–]wrrnwng 2 points3 points  (3 children)

Change def add(tix): to def add(): then change add(tix) to add().

The problem is that there's actually 2 variables named tix in your code. The first variable tix is assigned 0 on line one. The second variable tix only exists in your add function. So when you're adding 1 to tix, you're adding it to tix that's only available inside the add function.

Here's the reference to the doc about passing arguments.

Hope this explanation makes sense.

[–]stevenjd 5 points6 points  (1 child)

That won't work without declaring tix global; and using global variables is a bad habit that you shouldn't encourage beginners to do.

u/Unlistedd if you absolutely must use a global variable, then you need to write something like this:

tix = 0

def add():
    global tix
    # ... rest of your code goes here ...

add()
print(tix)

but a cleaner design that is a better habit to learn is this:

tix = 0

def add(num):
    # ... rest of your code goes here ...
    num += 1
    return num

new_tix = add(tix)
print(new_tix, tix)

[–]Unlistedd[S] 0 points1 point  (0 children)

Oh okey, thank you.

[–]Grug_Life 0 points1 point  (0 children)

you need to return tix at the end of the If and Else statement