[Tutor] trouble with 'char'

Adelein and Jeremy adeleinandjeremy at yahoo.com
Mon Jun 7 20:47:13 EDT 2004

*** I had replied to this previously but not to the list, I am
sending to the list now.

--- Dragonfirebane at aol.com wrote:
> Hello all,
> As far as I know, char is a valid variable describing characters in
> a user response, correct?

It is a valid variable, period. But, variables need to be assigned
values before being referenced....

> Traceback (most recent call last):
>   File "C:\Documents and Settings\Orri
> Ganel\Desktop\Hexadecimal-Binary-Text.py", line 32, in ?
>     convertxt()
>   File "C:\Documents and Settings\Orri
> Ganel\Desktop\Hexadecimal-Binary-Text.py", line 2, in convertxt
>     if char in alphabet[:26]:
> NameError: global name 'char' is not defined
> come up when i run the following program?:
> def convertxt():
>     if char in alphabet[:26]:
>         print binary[alphabet.index(original)]
>     elif char in alphabet[26:]:
>         print binary[alphabet.index(original)]

Maybe I am missing something here, but if this is your actual code,
how would the interpreter know if 'char' is in the list, when you
haven't told it what 'char' is? Maybe you are confusing the if-in
construct with the for-in? ``for char in alphabet[:26]:'' is valid,
but not what you want. Perhaps you meant to pass 'char' as an
argument? And where is 'original' coming from?

Also, you have an if-elif, but no else. Maybe if-else would be more
appropriate? And the actions to be taken are the same in both cases,
so why use a selection structure at all?

If I am reading the intent of your code correctly, I would prefer the

def convertxt(char):
    return binary[alphabet.index(char)]

Note that I have changed the print statement to a return statement so
as to avoid side-effects. Print the returned value elsewhere, if
that's what's required - in this case it would be more normal to do
something like ``new_text += convertxt(next_char)'' - of course,
having first properly assigned the variables 'new_text' and

- Jeremy

Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 

More information about the Tutor mailing list