Python 在 FOR 循环中使用 IF

标签 python if-statement for-loop dictionary

这个问题可能很愚蠢,但我正在尝试使用字典来迭代并返回结果。我知道如何遍历字典,但我想检查输入的键是否存在于字典中,并且我希望程序打印该值是否存在。

class companyx:

    def __init__(self,empid):

        self.empid=empid

    def employees(self):

        employees={1:'Jane',2:'David',3:'Chris',4:'Roger'}

        entered=self.empid

        for emp in employees :
            if emp == entered:
                print ('Hi '+employees[emp] +' you are an employee of companyx.com')
        print('You dont belong here')

emp=companyx(2)

emp.employees()

当我传递一个不在字典中的参数时,我希望函数打印“你不属于这里”

最佳答案

检查键是否在字典中的最简单(也是最惯用的)方法是:

if entered in employees:

以上代码替换了代码的 for/if 部分。请注意,无需显式遍历字典,in 运算符负责检查成员资格。简短而贴心:)完整的代码如下所示:

def employees(self):
    employees = {1:'Jane', 2:'David', 3:'Chris', 4:'Roger'}
    if self.empid in employees:
        print('Hi ' + employees[self.empid] + ' you are an employee of companyx.com')
    else:
        print("You don't belong here")

关于Python 在 FOR 循环中使用 IF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18969224/

相关文章:

python - 如何在python中更改环境变量?

python - 在 Google App Engine 的 ModelForm 中设置父级

jquery - 使用 ajax 和 jQuery 根据在 flask 中第一个下拉列表中选择的值填充第二个下拉列表

php - Mysql IF 两列相等并且它们都大于一

java - 在字符串中检查字母或 0 的问题。[JAVA]

java - 在 Java 中使用嵌套 for 循环查找概率

java - for 循环类分配出错

javascript - 循环遍历json对象并将其放入html表中

python - 嵌套循环中的向量化操作 : Python

c++ - 在 C++ 中打印重复的字母