Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 639
dhdz Avatar asked Oct 17 '22 18:10

dhdz


1 Answers

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

like image 50
fferri Avatar answered Oct 20 '22 05:10

fferri