python if statement learning summary

First, the if statement representation

if condition:
    print('ok')
elif condition:
    print('elif means parallel judgment')
else:
    print('error')
Here, add a colon after the if, and use the tab key (representing 4 spaces) to indent the code after the if. We call these codes "code blocks"
. The code blocks here tell us that the if condition is true. It should
be noted that several lines of code in the same code block must be indented with the same size

E.g:

if 1:
	print('1')
	print('2')
	print('3') #The three lines of output 1, 2, and 3 are the same code block because the indentation is the same
print('This line is not the same code block because of different indentation')

if statement also supports nesting

if 1:
	print('1')
	print('2')
	print('3')
	if 2==2:
	    print('2=2')
		if 3==3:
			print('3=3')
		else:
		    print('Not equal to 3')
	else:
	    print('Not equal to 2')
else:
	print('1 must be equal to 1, so this else is impossible')
In python, code blocks are judged by indentation, so you must pay attention to reasonable indentation when writing things.

In addition , when an if statement performs multiple parallel judgments, you can use elif to implement it.
For example :
a = int(input('Enter a number'))
if a == 1:
	print('The input is 1')
elif a == 2:
	print('The input is 2')
elif a == 3:
	print('The input is 3')
elif a == 4:
	print('The input is 4')
elif a == 5:
	print('The input is 5')
else:
	print('What are you entering?')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325728191&siteId=291194637