0
a = int(input("How many pizza would you like to order? "))                   #line 1

def count_ordered_pizza():
    if a==0:
        print("Okay see u next time!")
    elif a==1:
        print(str(a)+ " pizza ordered.")
    elif a>1:
        print(str(a)+ " pizzas ordered.")
    else:
        print("Sorry that's impossible")

def reorder():
    user_said= str(input('Do you wish to order again? State Y/N. '))
    while user_said != "N":
        a = int(input("How many pizza would you like to order? "))          #line 16
        count_ordered_pizza()
        reorder()
    print('Bye!')

If I execute this, the a in reorder() function (line 16), doesn't replace the a in count_ordered_pizza() function (line 1). Why is that?

I thought it could replace them since the variable has been overwritten, but if i do this:

def reorder():
    user_said= str(input('Do you wish to order again? State Y/N. '))
    while user_said != "N":
        a = int(input("How many pizza would you like to order? "))          #line 16
        if a==0: 
            print("Okay see u next time!")
        elif a==1:
            print(str(a)+ " pizza ordered.")
        elif a>1:
            print(str(a)+ " pizzas ordered.")
        else:
            print("Sorry that's impossible")

        reorder()
    print('Bye!')

It shows the correct value. Can someone help me with this please? Thank you in advance!

leyy
  • 13
  • 4
  • "If I execute this, the `a` in `reorder()` function (line 16), doesn't replace the `a` in `count_ordered_pizza()` function (line 1). Why is that?" of course not, those are *two different variables*. One is the a global variable, and the other is a local variable in `reorder` – juanpa.arrivillaga Dec 27 '21 at 08:36
  • You *could* mutate the global `a` in `reorder`, but you *shouldn't*. The better way to share data between functions is to *provide inputs as arguments* and *return the values*. The other alternative is to use a class to encapsulate state – juanpa.arrivillaga Dec 27 '21 at 08:37

1 Answers1

0

You can change global's variable value if you use global a expression inside function global explanation

a = int(input("How many pizza would you like to order? "))                   #line 1

def count_ordered_pizza():
    if a==0:
        print("Okay see u next time!")
    elif a==1:
        print(str(a)+ " pizza ordered.")
    elif a>1:
        print(str(a)+ " pizzas ordered.")
    else:
        print("Sorry that's impossible")

def reorder():
    user_said= str(input('Do you wish to order again? State Y/N. '))
    while user_said != "N":
        global a
        a = int(input("How many pizza would you like to order? "))          #line 16
        count_ordered_pizza()
        reorder()
    print('Bye!')
Yevhen Bondar
  • 4,357
  • 1
  • 11
  • 31