if语句
if语句用来判断当某个条件成立(非0或为True)时,执行下一个语句。常与else一起使用,表示除if判断条件之外的其他情况。 示例:
num = 130
if num%2 == 0:
print(num, "is a even number")
else:
print(num, "is a odd number")
130 is a even number
基本语法
if 条件1:
执行体1
elif条件2: #如果不满足以上条件, 则判断是否与当前条件相符, 相符则执行当前执行体
执行体2
else: #表示以上条件都不符合,则会执行这一条
执行体3
如果条件1成立 则执行执行体1
如果条件1不成立 如果条件2成立 则执行执行体2
如果条件2不成立 表示以上条件都不符合,则会执行执行体3
注意:
可以有多个elif,else是可选的。elif是“else if”的缩写,对于避免过多的缩进非常有用,else与它最近的前一个if或elif匹配。
示例:
>>> x = 32
>>> if x < 0:
... print("Negative changed to zero")
... elif x == 0:
... print("Zero")
... elif x == 1:
... print("Single")
... else: ...
print("More")
...
More
while语句
while语句用于循环执行程序,即在某条件下,循环执行某段程序。示例:
i = 5
while i > 0:
print(i)
i = i-1
5
4
3
2
1
for语句
for语句用于循环执行程序,并按序列中的项目(一个列表或一个字符串)顺序迭代。
示例:
words = ['www', 'DFRobot', 'com', 'cn']
for w in words:
print(w, len(w))
www 3
DFRobot 7
com 3
cn 2
如果需要在for循环内修改迭代的顺序或条件,可以在for循环中增加条件判断。
示例:
words = ['www', 'DFRobot', 'com', 'cn']
>>> for w in words:
if len(w) < 7:
print(w)
www com cn
range()函数
如果你需要遍历一系列数字,可以使用内置函数range() 示例:
>>> for i in range(4):
... print(i)
...
...
...
0
1
2
3
break语句
break语句用于退出for或while循环。
示例:
>>> for x in range(2, 10):
... if x == 5:
... break
... print(x)
...
2
3
4
continue语句
continue语句用于退出for或while语句的当前循环,进入下一次循环。
示例:
>>> for x in range(2, 10):
... if x == 5:
... continue
... print(x)
...
2
3
4
6
7
8
9
pass 语句
pass语句表示空语句,不做任何事情,一般用作占位语句,用来保持程序结构的完整性。示例:
>>> for letter in 'hello':
... if letter == 'l':
... pass
... print("This is pass")
... print("Current letter:", letter)
...
Current letter: h
Current letter: e
This is pass
Current letter: l
This is pass
Current letter: l
Current letter: o
循环元组
shuzhi = (1,2,8,4,85,4,8)
for i in shuzhi: #按照元组顺序执行
print(i)
使用len方法循环
# a = 'hello'
# b = len(a) #计算变量里有多少元素
# print(b) #5
# print(type(b)) # <class int>
for i in range(len(a)): #range 是一个循环多少次的函数
print(i)
99乘法表
for i in range(1,10):
for h in range(i):
print(f'{h+1}*{i}={(h + 1) * i}',end=' ')
print() #打行
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
使用循环的本质 ,循环100次,每次将这个值与之前的值进行累加, 得出结果
使用while 循环
result = 0
a = 1
while a <=100:
result = result+a
print("当前的值为",a,"结果",result)
a = a+1