Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError even with a direct, unconditional assignment on the line above

Tags:

python

unicode

Just explain me how it is possible:

сhar = input()
print(char)

Traceback (most recent call last): File "test.py", line 2, in print(char) NameError: name 'char' is not defined

To make things more interesting, consider running that code in repl.it with double-checked python version:

import sys
print(f'Python version on this machine:\n{sys.version}')
сhar = input()
print(char) 

Python version on this machine:
3.7.4 (default, Jul 13 2019, 14:20:24)
[GCC 6.3.0 20170516]
type anything
Traceback (most recent call last):
File "main.py", line 5, in
print(char)
NameError: name 'char' is not defined

like image 492
theuses Avatar asked Dec 02 '22 09:12

theuses


2 Answers

Unicode identifier names.

>>> "char" == "сhar" 
False

One of those c is a vanilla 'LATIN SMALL LETTER C' but the other is chr(0x441), i.e. 'CYRILLIC SMALL LETTER ES'. On a typical machine they will render to the terminal with very similar looking (or exactly same) glyphs.

like image 161
wim Avatar answered Dec 03 '22 23:12

wim


Your char = input() contains the cyrillic character с (see here) Whereas the print(char) is purely latin.

This also reminds me of the greek question mark prank, where the characters for semicolon and the question mark are rendered almost the same: ;;

Edit: wim was faster

like image 27
Mark G Avatar answered Dec 04 '22 00:12

Mark G