Python basics: (4) statement --- if statement


ps: This section involves a simple for loop statement.
ps: The following code is run in pycharm

1. If statement syntax

if statement syntax:

if 判断条件:

ps: the judgment condition of the if statement is to return a True or False
ps: the judgment condition is in terms of - conditional test

1.1 Example of if statement

for num in range(2,10):
    if num%2==0:# %取余运算
        print(num)

insert image description here

Two. if-else statement syntax

if 判断条件:
else:

2.1 Example of if-else statement

for num in range(2,10):
    if num%2==0:# %取余运算
        print(f"{
      
      num}:偶数")
    else:
        print(f"{
      
      num}:奇数")

insert image description here

Three. if-elif-else statement syntax

if 判断条件:
	elif 判断条件:
	elif 判断条件:
	elif 判断条件:
	...
	else:	

3.1. Example of if-elif-else statement

for num in range(2,10):
    if num < 4:
        print(f"{
      
      num}:小于4")
    elif num<8:
        if num == 4:
            print(f"{
      
      num}:等于4")
        else:
            print(f"{
      
      num}:大于4小于8")
    else:
        if num == 8:
            print(f"{
      
      num}:等于8")
        else:
            print(f"{
      
      num}:大于8")

insert image description here

Four. if-elif statement syntax

if 判断条件:
	elif 判断条件:
	elif 判断条件:
	elif 判断条件:
	...	

4.1. Example of if-elif statement

for num in range(2,10):
    if num < 4:
        print(f"{
      
      num}:小于4")
    elif num < 8:
        if num == 4:
            print(f"{
      
      num}:等于4")
        else:
            print(f"{
      
      num}:大于4小于8")

insert image description here

Five. Multiple judgment conditions (analogous to && || in c language)

5.1 and

说明:条件1 and 条件2 and ...and是指他们条件都符合执行下一条语句。

Example:

for num in range(2,10):
    if num >= 4 and num < 8 :
        print(num)
   

insert image description here

5.2 or

说明:条件1 or 条件2 or ...and是指他们条件有一个返回True则执行下一条语句。
for num in range(2,10):
    if num < 4 or num > 8 :
        print(num)

insert image description here

Six.tips—Boolean expressions

Explanation: Boolean expression is an alias for conditional test, that is, the return value is True/False

Guess you like

Origin blog.csdn.net/qq_63913621/article/details/129149913