+ 1

Code Issues

What is wrong with this code? It's a simple Unicode converter, and when I type a valid number, like 43, it works and prints 43 ---> +, but when I type a valid character like g, it produces an error. I can't figure out what's wrong with it. y = False def ntoc(n): try: print(str(n) + ' ---> ' + chr(n)) except ValueError: print('Invalid Number') def cton(c): try: print(str(c) + ' ---> ' + str(ord(c))) except ValueError: print('Invalid Character') y = True x = input('Type Unicode value or character: ') try: x = int(x) except ValueError: cton(x) if y == False: ntoc(x)

23rd Nov 2016, 6:22 PM
Henry Riser
Henry Riser - avatar
3 odpowiedzi
+ 2
def cton(c): global y # <-- add this line try:
23rd Nov 2016, 10:15 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Oh, I see. In the function cton I was creating a local variable y and assigning it the value True, not reassigning the global variable y. The line of code global y tells the interpreter that when it references y to use the global variable, not the local variable. Thanks Kirk Schafer! 👍🏻
23rd Nov 2016, 10:32 PM
Henry Riser
Henry Riser - avatar
+ 1
You got it and nice summary :)
23rd Nov 2016, 10:35 PM
Kirk Schafer
Kirk Schafer - avatar