Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't a variable be overwritten under a function?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading