Python:循环遍历if语句的elif部分

dhd*_*hdz 5 python loops for-loop if-statement

我对python比较陌生,所以我甚至不确定我是否以正确的方式接近它.但我在任何地方都找不到好的解决方案.

为了避免非常丑陋和重复的代码,我想循环if语句的elif部分.

这是我想修复的丑陋代码:

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"
Run Code Online (Sandbox Code Playgroud)

如您所见,索引递增1,所以我认为循环将非常简单.但是,当我尝试以下操作时,它不起作用,因为这必须被表述为if,elif,elif,else语句,而不是很多if语句.

我失败的尝试:

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

我该如何循环呢?注意:如果它有任何相关性,我使用curses模块对其进行编码,为项目构建键盘接口.非常感谢

ffe*_*rri 2

for c in chars:
    if code == ord(c):
        return c
return "wat"
Run Code Online (Sandbox Code Playgroud)

仅当之前没有执行过前一个(即没有匹配的字符)时才return执行第二个。return