if循环:有条件的执行,做出选择
例1:
a=42
if a<=10:
print('the number less than 10')
else:
print('thank you!')
例2:
people='M'
if people =='M':
print('girl')#if下的缩进归if管
else:
print('boy')
print('the end') #没有缩进不归if管
[root@localhost ~]# python 1.py
girl
the end
例3
a=103
if a>=100:
print('the number is larger or equal to 100')
else:
print('the number is less than 100')
[root@localhost ~]# python 1.py
the number is larger or equal to 100
例4(if嵌套)
a='F'
b=30
if a=='M':
if b>=20:
print('gentleman')
else:
print('boy')
else:
if b<20:
print('girl')
else:
print('women')
[root@localhost ~]# python 1.py
women
例5 分数分等级 0~60为no pass,60~70just pass,70~80good,80~90better,90~100best
record=92
if record >=60:
if record>=70:
if record>=80:
if record>=90 and record<=100:
print('best')
else:
print('better')
else:
print('good')
else:
print('just pass')
else:
print('no pass')
[root@localhost ~]# python 1.py
best
while循环:重复某个功能多次
- 循环变量初始化(开始)——第一步
- 循环条件(给出终止的条件)——第二步
- 循环【可重复】语句()——第四步
- 循环的修正(修正条件)——第三步
例1
greetings=1
while greetings<=3: #这里记住了是<=而不是<-,不要和R混淆了
print('hello!'*greetings)
greetings=greetings+1
[root@localhost ~]# python 2.py
hello!
hello!hello!
hello!hello!hello!
例2:打印100到200间的偶数
a=100
while a<=200:
if a%2 == 0:
print(a)
a=a+1
####方法二 7 a=100
while a<=200:
print(a)
a=a+2
例3:输出1-100间3的倍数
a=1
while a<=100:
if a%3==0:
print(a)
a=a+1
例4:求1到100的和
a=1
sum=0
while a<=100:
if a==100:
print(sum)
sum=sum+a
a=a+1
########
a=1
sum=0
while a<=100:
a=a+1
sum=sum+a
print(sum)
(正确的方法)###########
a=1
sum=0
while a<=100:
sum=sum+a
a=a+1
print(sum)
###########
a=1
sum=0
while a<=100:
sum=sum+a
a=a+1
print(sum) #注意print的位置缩进
例5:求1到100间的奇数和
a=1
sum=0
while a<=100:
if a%2==1:
sum = sum+a
a = a+1
print(sum)
[root@localhost ~]# python 1.py
2500
for循环:遍历列表中的每一个元素
例1
names=['a','b','c']
for name in names:
print('hello!'+name)
[root@localhost ~]# python 1.py
hello!a
hello!b
hello!c
例2
n=10
for i in range(n):
print(i)
题1:a=100,b=200,求a,b之间所有奇数的和