How to play with python branch structure (2)

In addition to the basic usage above, you can also use more complex conditional expressions, including using not and or to combine conditions, and using in and not in to check whether an element is (or is not) in a set.

For example:

pythonif not condition1 or not condition2:
# do something if condition1 is False or condition2 is False

or:

pythonif x in {1, 2, 3}:
# do something if x is 1, 2, or 3
pythonif x not in {1, 2, 3}:
# do something if x is not 1, 2, or 3

In addition, Python also provides a switch-case structure, which can be used to replace the traditional if-elif-else structure. Although Python does not have a direct switch-case statement, you can use dicts and functions to simulate this structure.

For example:

pythondef func_for_value(value):
return {
'a': lambda: print('a was called'),
'b': lambda: print('b was called'),
'c': lambda: print('c was called'),
}[value]()

func_for_value('a') # prints: 'a was called'

In the above code, we create a dictionary whose keys are the strings 'a', 'b' and 'c' and the values ​​are the corresponding functions. Then we use the dictionary's get method to get the corresponding function and execute it. This simulates the effect of a switch-case construct.

In addition, Python also provides a special way to handle an indeterminate number of arguments, which is to use *args and **kwargs.

*args is used to pass an indeterminate number of positional arguments, while **kwargs is used to pass an indeterminate number of keyword arguments.

For example:

pythondef my_func(*args, **kwargs):
for arg in args:
print(arg)
for key, value in kwargs.items():
print(key, value)

my_func('a', 'b', 'c', x=1, y=2)

Output:

cssa
b
c
x 1
y 2

In the above code, *args will collect all arguments passed to the function into a tuple, while **kwargs will collect all arguments passed to the function into a dictionary. This way, we can handle an uncertain number of parameters.

Guess you like

Origin blog.csdn.net/babyai996/article/details/132734715