Learn two syntaxes that are not commonly used in Python

1、for - else

After the syntax executes the statement of the for loop, the else branch statement is executed, that is to say, the else must be executed finally. eg:

listvar = [1, 2, 3, 4, 5]

for i in listvar:
	print(i)
else:
	print("for执行完,轮到我else了。")

Only when you break out of the loop with break in the for loop, will the execution of the else branch be skipped. eg:

listvar = [1, 2, 3, 4, 5]

for i in listvar:
	if i == 4:
		break
	print(i)
else:
	print("for执行完,轮到我else了。")

2. assert

Statement asserts that the boolean value of its expression must be true, false will trigger AssertionError.

Used for debugging, you can implement some input parameters format or type verification. eg:

def test_assert(arg):
	assert(isinstance(arg, (str))), "参数必须为字符串"
	print('执行test_assert开始')
	print('执行test_assert中')
	print('执行test_assert结束')


test_assert('sss')
test_assert({1, 2, 3})
test_assert(5)

the above.

Guess you like

Origin www.cnblogs.com/sirxy/p/12687163.html