Search code examples
pythonpython-3.xnameerror

Why is Python 3 giving me a name error when the name is defined?


the goal of my project is to find exact change using decision-making blocks. All of my code is returning the right answers, except in the answer that is expected to come out as "No Change".

The solution comes out as "No Change" as expected but then is followed by an error code that states

Traceback (most recent call last):
  File "main.py", line 21, in <module>
    if dollars == 1:
NameError: name 'dollars' is not defined

Any idea why this might be? Code that I have is below.

print("This program asks the user to enter a change amount using integers only,")
print("and outputs the change using the fewest coins.")
input_val = int(input("Enter the change amount as integer:"))



if input_val <= 0:
    print("No Change")

else: 
    dollars = input_val // 100
    input_val %= 100
    quarters = input_val // 25
    input_val %= 25 
    dimes = input_val // 10
    input_val %= 10
    nickels = input_val // 5
    input_val %= 5
    pennies = input_val


if dollars == 1:
    print('%d dollar' % dollars)
elif dollars > 1:
    print('%d dollars' % dollars)

if quarters > 1:
    print('%d quarters' % quarters)
elif quarters == 1:
    print('%d quarter' % quarters)

if dimes > 1:
    print('%d dimes' % dimes)
elif dimes == 1:
    print('%d dime' % dimes)

if nickels > 1:
    print('%d nickels' % nickels)
elif nickels == 1:
    print('%d nickel' % nickels)

if pennies > 1:
    print('%d pennies' % pennies)
elif pennies == 1:
    print('%d penny' % pennies)

Solution

  • you need to declare variables before using them.

    In your code the variables dollars, quarters, dimes, nickels, pennies are not visible outside the else block

    ...
    input_val = int(input("Enter the change amount as integer:"))
    
    dollars = 0
    quarters = 0
    dimes = 0
    nickels = 0
    pennies = 0
    
    
    if input_val <= 0:
        print("No Change")
    ...