1.循环语句
1.for语句循环
示例:
a=(1,2,3,4)
for i in a:
print(i)
2.while语句
示例:
i=0
while i!=3:
print(i)
i=i+1
3. for与while适用的条件
- for循环语句适合循环次数已知的情况下
- while循环语句适用于终止条件已知的情况下
2.条件语句
1.if 语句
示例:
age=28
if age>=18:
print("you are an adult")
2.if else语句
示例:
age=12
if age>=18:
print("you are an adult!")
else:
print("you are not adult!")
3.if else elif语句
示例:
age=14
if age>=0 and age<18
print("孩子")
elif age>=18 and age<40:
print("青年人")
elif age>=40 and age<60:
print("中年人")
else:
print("老年人")
编程示例(循环语句)
- 打出数字金字塔
for i in range(1,9): #数字金字塔的高度(8)
for t in range(1,9-i):
print("",end="\t")
for k in range(0,i): #数字金字塔的左边部分
print(("%d")%(2**k),end="\t")
if i==1:
print()
for s in range(i-2,-1,-1):#数字金字塔的右边部分
print("%d"%(2**s),end="\t")
if 2**s==1:
print()
2.画出棋盘
import turtle
import random
row=10 # 行
col=10 # 列
cell=50 # 单元格边长
upLimit=row//2*cell # y上界
downLimit=-row//2*cell # y下界
leftLimit=-col//2*cell # x左界
rightLimit=col//2*cell # x右界
turtle.speed(0)
turtle.penup()
turtle.goto(leftLimit,upLimit)
turtle.pendown()
# 制作表格
for i in range(1,row+1):
for j in range(1,col+1):
# 画一个格子的循环
#如果各自所在的行数加列数再对二求余为零时格子为黑色
if (i+j)%2==0:
turtle.color("black")
turtle.begin_fill()
for k in range(1,5):
turtle.forward(cell)
turtle.right(90)
turtle.end_fill()
turtle.forward(cell)
else:
for k in range(1,5):
turtle.forward(cell)
turtle.right(90)
turtle.forward(cell)
turtle.penup()
turtle.goto(leftLimit,upLimit-i*cell)
turtle.pendown()
turtle.done()
编程示例(条件语句)
1.生成彩票,数字与顺序都相同时中奖5000,数字相同顺序不相同中奖1000,
有一个数字相同中奖500
import random
#彩票中奖数在101到999之间
number=random.randint(101,999)
a=int(input(print("Please enter a number between 101 and 999 ")))
#中奖数字拆分
c1=number%10
c2=(number//10)%10
c3=number//100
#输入数字拆分
d1=a%10
d2=(a//10)%10
d3=a//100
#中奖判断
if number==a :
print("Congratulasions! you got 5000 dollar!")
elif c1==d2 & c2==d1 & c3==d3 :
print("Congratulasions! you got 1000 dollar!")
elif c1==d3 & c2==d1 & c3==d2 :
print("Congratulasions! you got 1000 dollar!")
elif c1==d3 & c2==d2 & c3==d1 :
print("Congratulasions! you got 1000 dollar!")
elif c1==d2 & c2==d3 & c3==d1 :
print("Congratulasions! you got 1000 dollar!")
elif c1==d1 & c2==d3 & c3==d2 :
print("Congratulasions! you got 1000 dollar!")
elif c1==d1 or c1==d2 or c1==d3 :
print("Congratulasions! you got 500 dollar!")
elif c2==d1 or c2==d2 or c2==d3 :
print("Congratulasions! you got 500 dollar!")
elif c3==d1 or c3==d2 or c3==d3 :
print("Congratulasions! you got 500 dollar!")
else:
print("thanks!")
#打出中奖数字
print("The win number is %d"%number)