Python函数if/else函数



我是一个学生开发人员(第4天)练习一些编码。我正在寻找关于如何让这个if/else函数工作的指导。我遇到的问题是让2列表在定义函数中正常工作。

我正试图得到代码比较2列表,

-如果名字在两个列表中打印'you are authorized'

-else如果名称在list_name中但不在omaha_location中,print 'please see HR'

-else返回'您未被授权'

def authorization(name):
#if the user's name is in the list_names and omaha_location authorize 
`your text`if name.lower() in (omaha_location) and (list_names):`
return(f"Hello {name} you are authorized")

#if the user's name is in list_names but not in the omaha_location forward to HR
`your text`elif name.islower() in list_names not in omaha_location:
`your text`return(f'{name}this is not your location, please see HR')

#if the user's name is anything else decline authorization
`your text`else:
`your text`return(f"Hello {name}, you are not authorized !")
name = input("Please enter your name:")
list_names = ['dan','kyle','lady','luna']
omaha_location = ['dan','kyle']
print(authorization(name))type here
我真的很感谢你的回复。我已经做了一段时间了。

我尝试了多种方法。所粘贴的代码是最接近我想要的结果,但它不是完全在那里。

有多种方法可以实现相同的结果(即任何函数)。我给出了一个简单的解决方案。下面是基本语法:

if name.lower() in [l.lower() for l in omaha_location] and name.lower() in [l.lower() for l in list_names]:
return(f"Hello {name} you are authorized")
elif name.lower() not in [l.lower() for l in omaha_location] and name.lower() in [l.lower() for l in list_names]:
return(f'{name}this is not your location, please see HR')
else:
return(f"Hello {name}, you are not authorized !")

欢迎使用堆栈溢出!您的代码中有一些错误,例如围绕(omaha_location)(list_names)的括号。这应该是给你的:

def authorization(name):
# if the user's name is in the list_names and omaha_location authorize 
if name.lower() in list_names and name.lower() in omaha_location:
return f"Hello {name}, you are authorized"

# if the user's name is in list_names but not in the omaha_location forward to HR
elif name.lower() in list_names and name.lower() not in omaha_location:
return f"{name}, this is not your location, please see HR"

# if the user's name is anything else decline authorization
else:
return f"Hello {name}, you are not authorized!"
name = input("Please enter your name:")
list_names = ['dan', 'kyle', 'lady', 'luna']
omaha_location = ['dan', 'kyle']
print(authorization(name))

最新更新