我编写了以下Python代码。
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s = %s" % (key, value))
# Driver code
a = input("Enter first word")
b = input("Enter second word")
c = input("Enter third word")
d = input("Enter fourth word")
e = input("Enter fifth word")
myFun(first=a, second=b, third=c, fourth=d, fifth=e)
如您所见,上面的代码将用户的5个变量作为输入,然后打印它们。
现在的挑战是,如果用户输入'Hello‘,那么就不应该打印。
例如,如果假设第三个单词是'Hello‘,那么函数调用中就不应该出现"third=c“。因此,函数调用将如下所示。myFun(first=a, second=b, fourth=d, fifth=e)
请注意,“你好”只是一个例子,我可以有许多这样的词。
此外,“Hello”可以出现在多个变量中。例如,假设第三个和第五个单词是'Hello‘,那么函数调用中不应该出现"third=c“和"fifth=e”。因此,函数调用将如下所示。myFun(first=a, second=b, fourth=d)
我不能对函数定义做任何更改。
我知道我可以根据条件编写多个函数调用,但是有更好的方法吗?
发布于 2022-11-08 08:04:30
用字典调用函数。
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s = %s" % (key, value))
def main():
# Driver code
a = input("Enter first word")
b = input("Enter second word")
c = input("Enter third word")
d = input("Enter fourth word")
e = input("Enter fifth word")
keys = ['first', 'second', 'third', 'fourth', 'fifth']
parameters = {}
for key, value in zip(keys, [a, b, c, d, e]):
if value != 'Hello':
parameters[key] = value
myFun(**parameters)
if __name__ == '__main__':
main()
https://stackoverflow.com/questions/74357339
复制相似问题