1、条件语句流程图
2、if语句
a、形式
if condition_1 :
execute_1
elif condition_2 :
execute_2
else:
execute_3
b、说明
当condition_1 为真时,执行execute_1;
当condition_1 为假时,判断condition_2 的值,当condition_2 为真时,执行execute_2
当condition_2 为假时,执行execute_3
Python3中用elif代替了else if,因此if条件语句的关键字为:if - elif - else
注意:
- 1、每个条件后面要使用冒号 :,表示接下来是满足条件后要执行的语句块。
- 2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
- 3、在Python中没有switch – case语句。
c、常用操作运算符
>、>=、<、<=、==、!=等是if语句中经常使用到的操作运算符
"""
随便输入一个年份,判断该年份是否为闰年:
普通闰年:能被4整除但不能被100整除的年份为普通闰年
世纪闰年:能被400整除的为世纪闰年
"""
year = int(input("请输入一个年份:"))
if year % 400 == 0 :
print("%d 是一个世纪闰年" % year)
elif (year % 100 != 0) and (year % 4 == 0):
print("%d 是一个普通闰年" % year)
else:
print("%d 不是闰年" % year)
请输入一个年份:2000
2000 是一个世纪闰年
请输入一个年份:2004
2004 是一个普通闰年
请输入一个年份:2005
2005 不是闰年
3、if嵌套
a、形式
if 表达式1:
语句
if 表达式2:
语句
elif 表达式3:
语句
else:
语句
elif 表达式4:
语句
else:
语句
例子:
"""
查询 n 到 m 间的所有素数
质数是指在大于1的自然数中,除了1和它本身以外不再有其他因数的自然数
"""
def find_prime_number(n, m):
# 判断n和m是否是整数
if isinstance( n, int) and isinstance( m, int):
if m <= 1:
return "m不能小于1"
if 1 >= n > m:
return "m必须大于等于n,且n和m必须大于等于1"
# 创建一个空列表,用于存储素数
prime_number = list()
num = n
# while循环用于检查n - m之间的所有自然数
while num <= m:
i = 2
# while循环用于判断一个自然数是否为素数
while i < num:
if (num % i == 0) and (num != i):
#如果自然数有其他因子,跳出while i < num循环,num+1后再进入while num <= m循环进行下一个数的判断
break
else:
i += 1
#如果是素数,添加到prime_number列表中
if num == i:
prime_number.append(num)
# num不是素数时,num+1进行下一个数的判断
num += 1
# 返回n和m中的所有素数列表
return prime_number
else:
return "n和m必须都是整数!!!"
# 调用find_prime_number()函数,并传入n和m的值
print("n和m之间的所有素数为:" , find_prime_number(1, 100))
n和m之间的所有素数为: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]