Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:循环if语句的elif部分_Python_Loops_For Loop_If Statement - Fatal编程技术网

Python:循环if语句的elif部分

Python:循环if语句的elif部分,python,loops,for-loop,if-statement,Python,Loops,For Loop,If Statement,我对python比较陌生,所以我甚至不确定我是否以正确的方式处理了这个问题。但我还没有找到一个好的解决办法 为了避免非常难看和重复的代码,我想循环if语句的elif部分 这是我想要修复的丑陋代码: def codeToChar(code): chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm" if code == ord(chars[0]): ##### SUPER UGLY return chars[0]

我对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"
正如您所看到的,索引正以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"
我该如何循环这个? 注意:如果它有任何相关性,我将使用curses模块编写它,为一个项目构建一个键盘接口。 非常感谢

for c in chars:
    if code == ord(c):
        return c
return "wat"
第二个
返回
仅在之前未执行任何
返回
的情况下执行(即,没有匹配的字符)。

您不希望在循环内返回“wat”,因为如果
语句失败一次,它将在
时立即触发。只有在所有迭代都失败时,才希望返回错误。取消输入
else
块以执行此操作

for x in xrange(0,len(chars)-1):
    if code == ord(chars[x]):
        return chars[x]
else:
    return "wat"
else
块是可选的。你也可以写:

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

看起来您只是在检查代码是否是其中一个字符。一种清洁的解决方案是:

c = chr(code)
return c if c in chars else "wat"
使用口述:

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

可以在长度上使用enumerate而不是xrange