-1

What am I doing wrong here?

money = 2.01
str_money = str(money)
last_digit = str_money[-1]
if last_digit == "0":
    is_zero = True
print(is_zero)

This is the error code I get:

Traceback (most recent call last):
  File "C:\Users\Robin Groot\PycharmProjects\huiswerk\TestLes2.py", line 8, in <module>
    print(is_zero)
NameError: name 'is_zero' is not defined

Process finished with exit code 1

EDIT: I found the problem, At the moment the if statement is not true it breaks at print because there is no value for is_zero you can solve this by adding an else statement or putting the print into the if statement.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    Indeed, since your condition is false (there is no trailing 0 in your number), `is_zero`is not defined. You may add `is_zero = false` at the begining of your code – Sebastien D Sep 16 '21 at 16:10
  • or without `if`: `is_zero = last_digit == "0"` or `is_zero = str_money.endswith("0")` – falsetru Sep 16 '21 at 16:13
  • When reviewing code, if without else requires extra scrutiny. Does any later code depend on something done in the if? In your case, yes. – tdelaney Sep 16 '21 at 16:26
  • Does this answer your question? ["UnboundLocalError: local variable referenced before assignment" after an if statement](https://stackoverflow.com/questions/15367760/unboundlocalerror-local-variable-referenced-before-assignment-after-an-if-sta) – wjandrea Nov 04 '21 at 22:59
  • 1
    @wjandrea that question is problematic because of the complex setup: the strange behaviour OP experienced was caused by the intersection of this problem, with trying to read an open file twice in a row. I have improved and established a new canonical (at least for now), for the cases where the variable is expected to be local: http://stackoverflow.com/questions/22101836. – Karl Knechtel Feb 06 '23 at 13:01

1 Answers1

1

add else condition or define is_zero = False at the begining.

money = 2.01
str_money = str(money)
last_digit = str_money[-1]
if last_digit == "0":
    is_zero = True
else:
    is_zero = False
    
print(is_zero)
hmn Falahi
  • 730
  • 5
  • 22