5

I'm relatively new to python, so I'm not even sure if I'm approaching this in the correct way. But I haven't found a good solution anywhere.

In order to avoid very ugly and repetitive code, i want to loop the elif part of the if statement.

This is the ugly code i want to fix:

def codeToChar(code):
chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"

if code == ord(chars[0]):   ##### SUPER UGLY
    return chars[0]
elif code == ord(chars[1]):
    return chars[1]
elif code == ord(chars[2]):
    return chars[2]
elif code == ord(chars[3]):
    return chars[3]
elif code == ord(chars[4]):
    return chars[4]
elif code == ord(chars[5]):
    return chars[5]
..... etc .....
else:
    return "wat"

As you can see, the index is incrementing by one, so I thought looping would be very simple. However, when I tried the following, it didn't work because this must be formulated as an if, elif, elif, else statement, and not many if statements.

My failed attempt:

for x in xrange(0,len(chars)-1):
    if code == ord(chars[x]):
        return chars[x]
    else:
        return "wat"

How would I go about looping this? Note: if it's of any relevance, I'm coding this using the curses module, building a keyboard interface for a project. Many thanks

4 Answers 4

2
for c in chars:
    if code == ord(c):
        return c
return "wat"

the second return is executed only if no previous return has been previously executed (i.e. no character matched).

Sign up to request clarification or add additional context in comments.

Comments

1

It seems like you are just checking whether the code is one of the characters or not. One clean solution would be:

c = chr(code)
return c if c in chars else "wat"

Comments

1

Use a dict:

chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
chars_dict = {ord(c): c for c in chars}
return chars_dict.get(code, 'wat')

Comments

-1

You don't want to return "wat" inside the loop as it'll trigger as soon as the if statement fails once. You only want to return an error if all iterations failed. Unindent the else block to do this.

for x in xrange(0,len(chars)-1):
    if code == ord(chars[x]):
        return chars[x]
else:
    return "wat"

The else block is optional. You could also write:

for x in xrange(0,len(chars)-1):
    if code == ord(chars[x]):
        return chars[x]
return "wat"

1 Comment

Could use enumerate rather than xrange over the length

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.