1.条件判断语句
if分支语句
语法格式:
if 要判断的条件:
执行语句
a=50
print("------------")
if a>=10:
print("你真棒!")
print("------------")
If-else双分支语句:
语法格式:
if 要判断的条件:
执行语句1
else
执行语句2
if 11:
print("Ture")
print("Answer")
else:
print("false")
print("end")
注意:①if和else后面必须要有冒号②同一层次下换行不一致会导致运行错误
多分支if-elif-else语句:
语法格式:
if 表达式1:
执行语句1
elif 表达式2:
执行语句2
elif 表达式3:
执行语句3
……
……
score=50
if score>=90 and score <=100:
print("等级为A")
elif score>=80 and score <90:
print("等级为B")
elif score>=70 and score <80:
print("等级为C")
elif score>=60 and score <70:
print("等级为D")
else: #elif和else可以一起使用
print("等级为E")
if嵌套:
语法格式:
if 表达式1:
执行语句1
if 表达式2:
执行语句2
if ……
……
gender = 1 # 1代表男生,0代表女生
dansheng = 1 # 1代表单身,0代表不单身
if gender == 1:
print("男生")
if dansheng == 1:
print("我给你介绍一个吧!")
else:
print("你给我介绍一个吧!")
else:
print("女生")
improt和from……import
- 在Python中用import和from……import来导入相应的模块
- 将整个模块(somemodule)导入,格式为:import somemodule
- 从某个模块中导入某个函数格式为:form somemodule import somefunction
- 从某个模块中导入多个函数格式为:form somemodule import firstfunction,secondfunction,thirdfunction
- 将某个模块中的全部函数导入:form somemodule import \*
例:引入随机库
import random #引入随机库
a=random.randint(0,2)#随机生成0,1,2中的一个数字,赋值给变量a
print(a)
课后作业
使用if语句的相关知识,实现石头剪刀布游戏效果
请输入:剪刀(0)、石头(1)、布(2):_
输入数字0-2中的一个数字,与系统随机产生的数字比较后给出结果信息
#方法1
print("我们来玩石头剪刀布吧")
import random
b=random.randint(0,2)
a=input("你先出:")
print(b)
if a=="石头" or a=="剪刀" or a=="布":
if a=="剪刀":
a=0
elif a=="石头":
a=1
elif a=="布":
a=2
if a>b:
print("您赢了")
elif a==b:
print("咋们平了")
else:
print("我赢了")
else:
print("您输错了,亲,重新输入")
#方法2
import random
person=int(input("please enter:[0:剪刀1:石头2:布]"))
computer=random.randint(0,2)
print("电脑出拳:%d"%computer)
if person>2:
print("enter wrong")
elif person==0 and computer==2:
print("good you win")
elif person==1 and computer==0:
print("good you win")
elif person==2 and computer==1:
print("good you win")
else:
print("you lose")
#方法3
import random
a=random.randint(0,2)
print(a)
b=int(input("剪刀0,石头1,布2""\n"))
if a==b:
print("平局")
elif a==1 and b==0:
print("你输了")
elif a==0 and b==2:
print("你输了")
elif a==2and b==1:
print("你输了")
else:
print("你赢了")