Python Learning 06: Introduction and Use of If Statement

One, if statement

The Python conditional statement determines the code block to be executed by the execution result (True or False) of one or more statements. In Conditional statement execution process
Python programming, the if statement is used to control the execution of the program. The basic form is:

if 判断语句:
	执行语句....
else
	执行语句....
'''
当满足判断条件时,则执行后面的执行语句,执行内容可以为多行,已缩进来区分表示同意范围;
else为可选语句,当需要在条件不成立时执行内容则可以执行相关语句。
'''
实例1
name = input("Your name:")  
age = input("Your age:")
if int(age) < 20:
    print(name,age)
else:
    print("old")
#输入namedd,age21 ,输出结果 :old
#输入namedd,age19 ,输出结果:dd 19

实例2#判断元素是否存在
str = 'csdn so good'
if 'so' in str:
    print("true")        ====> 打印结果:true
###############################################################
str = 'csdn so good'
if 'sn' in str:
    print("true")        ====> 打印结果:空 #sn不存在元素中

The judgment condition of the if statement can be expressed by> (greater than), <(less than), == (equal to), >= = (greater than or equal to), and <= = (less than or equal to).
When the judgment condition is multiple values, the following forms can be used:

if 判断语句1
	执行语句1....
elif 判断语句2
	执行语句2....
elif 判断语句3
	执行语句3....
else
	执行语句4....
'''
1.当未满足判断语句1的条件时,会执行下个elif的判断语句2,直到满足了其中的某一个判断语句就会执行其下执行语句
2.当其中的一个条件满足,其他的条件分支自动屏蔽,不会再运行
3.如果所有判断语句都不满足,则会直接执行else中的执行语句
'''
实例1
age = input("Your age:")
if int(age) < 20:
    print(age)
elif int(age) > 30:
    print("so old")
else:
    print("old")
#输入age40 ,输出结果 :so old
#输入namedd,age21 ,输出结果 :old
#输入namedd,age19 ,输出结果:dd 19

The if variable, "", [], {}, 0, False, () means that the condition is not established

例如:
if 1:
    print("这是1")
if "":
    print("这是 空字符串")
if True:
    print("这是True")
#打印结果:这是1     这是True    

nesting of if

a = 10
b = 20
if a < b :
	print ("继续执行")
	if "csdn" in "csdn so good":
		print ("嵌套执行")
else:
	print("lose")
#打印结果:继续执行   嵌套执行 

if complex connection

DING_age = input("DING age:")
SUN_age = input("SUN age:")
if int(DING_age) < int(SUN_age) and int(SUN_age) < 26:
    print("sister")
    if 1 :
        print("true")
elif int(DING_age) < int(SUN_age) or int(DING_age) <= 18:
    print("young")
else:
    print("lose")

Guess you like

Origin blog.csdn.net/DINGMANzzz/article/details/112836000