dhdz
dhdz

Reputation: 899

Python: Loop through the elif section of an if statement

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

Upvotes: 5

Views: 934

Answers (4)

fferri
fferri

Reputation: 18940

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).

Upvotes: 2

ted
ted

Reputation: 14714

Use a dict:

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

Upvotes: 1

nuric
nuric

Reputation: 11225

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"

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361585

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"

Upvotes: -1

Related Questions