+ 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)
3 ответов
+ 2
def cton(c):
global y # <-- add this line
try:
+ 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! 👍🏻
+ 1
You got it and nice summary :)