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

Fix NameError in python

I have created a program to take inputs from the user and find the average of those inputs. My code is –

def avg(*a):
    sum = 0
    n = 0
    while 1:
        a = input("enter number :")
        b = a.isdigit()
        if b is False:
            continue
        if int(a) == 0:
            break
        sum += int(a)
        n += 1
    return sum/n

avg()
print("AVG :",avg(a))

However, am getting this error –

Traceback (most recent call last):
  File "C:\Users\Metro\Desktop\python\script2.py", line 16, in <module>
    print("AVG :",avg(a))
                      ^
NameError: name 'a' is not defined

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 got NameError because pass variable a to func avg and this variable not define in global scope and you dont need break and continue

def avg():
    total = 0
    count = 0
    while True:
        user_input = input("Enter number (for finish enter 0): ")
        if user_input.isdigit():
            num = int(user_input)
            if num == 0:
                return total / count if count != 0 else 0
            total += num
            count += 1

print("Average: ", avg())


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