一、判断语句
1、简单的if语句
age = 20
if age >= 18:
print("已经成年")
2、if-else语句
age = int(input("请输入年龄:"))
if(age >= 18):
print("已经成年")
else:
print("未成年")
#输入三角形的三条边,计算三角形的面积
import math
a = int(input("请输入三角形的第一条边:"))
b = int(input("请输入三角形的第二条边:"))
c = int(input("请输入三角形的第三条边:"))
if a>0 and b>0 and c>0 and a+b >c and a+c>b and b+c>0:
s = 1/2*(a+b+c)
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print("三角形面积为",area)
else:
print("不能构成三角形!")
3、If-elif-else语句
score = int(input("请输入成绩:"))
if score >100 or score < 0:
print("无意义")
elif score>=90:
print("优")
elif score >=80:
print("良")
elif score >=70:
print("中")
elif score >=60:
print("及格")
else:
print("不及格")
4、嵌套的if语句
a = int(input("请输入第一个数字:"))
b = int(input("请输入第二个数字:"))
c = int(input("请输入第二个数字:"))
if a > b:
if a > c:
print("最大值为:",a)
else:
print("最大值为:",c)
else:
if b >c:
print("最大值为:",b)
else:
print("最大值为:",c)
二、循环语句
1、while循环语句(先判断后执行)
#求 S = 1+2+3....+100
s=0
i=1
while i<=100:
s+=i
i+=1
print("s=",s)
2、for循环语句
for 变量 in 序列:
语句块
for x in "Python":
print(x)
3、for+ramge([start],stop,step)
start:计数从start开始,默认是从0开始,
例如range(0,10)等价于range(10);
stop:计数到stop结束,但不包括stop,
例如range(5)是【0,1,2,3,4】
step:步长,默认为1,
例如range(0,5)等价于range(0,5,1);
#用for语句求1-100的值
s=0
for i in range(1,101):
s+=i
print("s=",s)
4、嵌套循环
#乘法表
for x in range(1,10):
for y in range(1,x+1):
print(y,"*",x,"=",x*y,end="")
print("")
二、使用break 和 continue跳出循环
break是跳出循环体,接着执行循环下面的语句,
continue是提前结束本次循环,接着执行下次循环。
代码1:
n=1
while True:
if(n>10):
break
n+=1
print(n)
代码2:
for x in range(1,21):
if x%2==0:
continue
else:
print(x)
三、案例
#猜拳游戏
people1= int(input("0:石头 1:剪刀 2:布"))
people2=int(input("0:石头 1:剪刀 2:"))
if people1<0 or people1>2 or people2<0 or people2>2:
print("请遵守比赛规则")
else:
if (people1==0) and (people2==1) or (people1==1) and (people2==2) or (people1==2) and (people2==0):
print("people1获胜")
elif people1 == people2:
print("平局")
else:
print("people2获胜")
#百钱买百鸡
for cock in range(0,20+1):
for hen in range(0,33+1):
for biddy in range(3,99+1):
if cock+hen+biddy == 100:
if biddy%3==0:
print("公鸡",cock,"母鸡",hen,"小鸡",biddy)
#判断用户账户输入是否正确
zh="yt"
mima="123"
z=input("请输入账户:")
m=input("请输入密码:")
if zh == z and mima == m:
print("Helllo Python")
else:
print("账户或密码有误")
#while循环打印2-100之间大素数
import math
i=2
while i<100:
j=2
k=math.sqrt(i)
while j<=k:
if i%j == 0:
break
else:
j+=1
if j>k:
print(i)
i+=1
#while九九乘法口诀表
x=1
while x<10:
y=1
while y<=x:
print(y,"*",x,"=",x*y ,end=" ")
y+=1
print("")
x+=1
#使用for循环打印正立实心等腰三角形
n=int(input("请输入层数"))
for i in range(1,n+1):
kg=n-i
for j in range(1,kg+1):
print(" ",end="")
xx=i*2
for x in range(1,xx):
print("*",end="")
print("")