条件控制语句
-
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