python笔记--条件控制语句

条件控制语句

  • if判断语句

    • if语句在执行时,会先对条件表达式进行求值判断
    • 如果为True,则执行if后的语句
    • 如果为False,则不执行
// A code block
x=input('输入两个数字:')
a,b=map(int,x.split())
if a>b:
	a,b=b,a
print(a,b)
// An highlighted block
输入两个数字:10 5
5 10
  • input函数

    • 只要执行,就会阻塞程序
    • input输入的都是字符串
  • if-else

    • if-else语句在执行时,先对if后的条件表达式进行求值判断
    • 如果为True,则执行if后的代码块
    • 如果为False,则执行else后的代码块)
// A code block
chTest=['1','2','3','4','5']
if chTest:
	print(chTest)
else:
	print('Empty')
// An highlighted block
['1', '2', '3', '4', '5']
  • if- elif-else

    • if-elif-else语句在执行时,会自上向下依次对条件表达式进行求值判断
    • 如果表达式的结果为True,则执行当前代码块,然后语句结束
    • 如果表达式的结果为False,则继续向下判断,直到找到True为止
    • 如果所有的表达式都是False,则执行else后的代码块
// A code block
def func(score):
	if score>100:
		return 'wrong score must <=100'
	elif 100>=score>=90:
		return 'A'
	elif 90>score>=80:
		return 'B'
	elif 80>score>=70:
		return 'C'
	elif 70>score>=60:
		return 'D'
	elif 60>score>=0:
		return 'E'
	else:
		return 'wrong score must > 0'
func(60)
func(87)
func(101)
// An highlighted block
'D'
'B'
'wrong score must <=100'
  • 选择结构的嵌套
if 表达式1:
	语句块1
	if 表达式2:
		语句块2
	else:
		语句块3
else:
	if表达式4:
		语句块4
// A code block
def func(score):
	degree='DCBAAE'
	if score>100 or score<0:
		return 'wrong score must between 0 and 100'
	else:
		index=(score-60)//10
		if index>=0:
			return degree[index]
		else:
			return degree[-1]
func(-10)
func(98)
func(53)
// An highlighted block
'wrong score must between 0 and 100'
'A'
'E'
  • while循环
    • 1. 初始化表达式,通过初始化表达式来处事初始一个变量
      # 2. 条件表达式,用来设置循环的执行条件 例如 i《 20
      # 3. 更新条件表达式,修改初始化变量的值
      ``'
      

例如:

// A code block
s=i=0
while i <=100:
	s+=i
	i+=1
else:
	print(s)
// An highlighted block
5050
  • break与continue语句
    break语句与continue语句在while循环及for循环中都可以使用,并且一般常与选择结构结合使用。一旦break语句被执行,将使得break语句所属层次的循环提前结束。continue语句的作用是提前结束本次循环,并忽略continue之后的所有语句,直接回到循环的顶端,提前进入下一次循环。
    下面的代码用来输出100以内的所有素数
// A code block
i = 2
while i <= 100:
    for j in range(2,i):
        if i % j == 0:
            break
    else:
        print(i,end=' ')
    i += 1
// An highlighted block
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 

下列代码用于判断水仙花数:

// A code block
i=100
while i<1000:
	ge=i%10
	shi=i//10%10
	bai=i//100
	if ge**3+shi**3+bai**3 == i:
		print(i)
	i=i+1
// An highlighted block
153
370
371
407
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值