标签:成功 keyword 结束 loop 执行 对象 好用 12px 之间
一、if条件语句:
语法:
1.if单分支(单重条件判断)
if expression:
expr_true_suite
注释:expession为真执行代码expr_true_suite
if单分支(单重条件判断)
if not active or over_time >= 10:
print(‘Warning:service is dead‘)
warn_tag+=1
2.if+else循环语句
if 1<2:
print(‘ok‘)
else:
print(‘no‘)
3.多分支if+elif+else
oldboyage= 53
guessage=input(‘请输入老男孩的年龄:‘)
if guess<53:
print("猜小了")
elif guess>53:
print("猜大了")
else:
print("猜对了"):
if语句小结:
二、while循环语句
基本的语法:
while expression:
suite_to_repeat
注解:重复执行suite_to_repeat,直到expression不再为真
具体结构如下:
while 条件:
循环体的代码1
循环体的代码2
循环体的代码3
..........
1. 计数循环
count=0
while (count < 9):
print(‘the loop is %s‘ %count)
count+=1
2.无限循环
count=0
while True:
print(‘the loop is %s‘ %count)
count+=1
ps:
tag=True
count=0
while tag:
if count == 9:
tag=False
print(‘the loop is %s‘ %count)
count+=1
3.while循环与break、countinue
break跳出本层循环
ps:
#break:跳出本层循环
count=0
while count < 10:
if count == 5:
break
print(count)
count+=1
countinue跳出本次循环
ps:
#continue:跳出本次循环
#0 1 2 3 7 8 9
count=0
while count < 10:
if count >=4 and count <=6:
count += 1
continue
print(count)
count+lse=1
与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句
while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句
ps:
count = 0
while count <= 5 :
count += 1
print("Loop",count)
else:
print("循环正常执行完啦")
print("-----out of while loop ------")
小节练习:
1.使用while循环输出1 2 3 4 5 6 8 9 10
count=1
while True:
if(count!=7):
print(count)
count+=1
if(count>10):
break
2 .求1-100的所有数的和
sum=0
for i in range(1,101):
sum=sum+i
print("从1加到100等于",str(sum))
3. 输出 1-100 内的所有奇数
for i in range(1,101):
if i%2!=0:
print(i)
4. 输出 1-100 内的所有偶数
for i in range(1,101):
if i%2==0:
print(i)
5. 求1-2+3-4+5 ... 99的所有数的和
sum=0
for i in range(1,100):
if(i%2==0):
sum=sum-i
else:
sum=sum+i
print("和是"+str(sum))
6. 用户登陆(三次机会重试)
count = 3
while count>0:
username = input("please your username ")
password = input("please your password ")
if(username=="admin" and password=="admin"):
print("登录成功")
break
else:
count=count-1
print("你输入的用户名或密码有误请重新登录还有%s次机会."%(count))
标签:成功 keyword 结束 loop 执行 对象 好用 12px 之间
原文地址:http://www.cnblogs.com/moning/p/7200496.html