Python中if条件语句

if – else语句

  • 每个if条件后要使用冒号(:),表示接下来是满足条件后要执行的语句
  • 在Python中没有switch-case语句
ticket = 1
if ticket == 1:  #注意用比较运算符(==),不能用赋值运算符(=)
    print("有票了,郑成伟就可以回家了")
    print("就问你美不美")
else:
    print("没票了,郑成伟回不去了")
    print("她还没有女朋友,没啥事")
  • if - elif语句
#if-elif条件语句(判断情况大于两种,if-else无法完成时使用)
score = 60
if score > 90:
    print("这是一个优秀的同学")
elif  90>score>80:
    print("这和我一样呀,只能算良")
elif  80>score>70:
    print("差点不及格呀")
elif score<70:
    print("这些都是cai怪")

if嵌套语句

  • 多重判断中可以使用if嵌套语句
#if嵌套,在if或者if-else语句里包含if或者if-else语句
#买火车票例子:
ticket = 1 #用1代表有票,用0代表无票
knife_length = 9  #刀子的长度为9cm
if ticket == 1:
    print("有车票,可以进站")
    if knife_length <=10:
        print("通过安检,可以乘火车")
    else:
        print("没有通过安检")
        print("刀子的长度超过10cm,超过规定,等待警察处理")
else:
    print("没有票了,只能等下一班火车")

if - elif - else语句的使用

#猜拳游戏
import random #random() 方法返回随机生成的一个实数,它在[0,1)范围内
player_imput =input("请输入(0剪刀、1石头、2布):")
player =int(player_imput)
computer = random.randint(0,2)
if (player ==0 and computer == 2) or (player ==1 and computer == 0)\
    or (player == 2 and computer == 1):
    print("恭喜你,你赢了")
elif (player ==2 and computer == 0) or (player ==0 and computer == 1)\
    or (player == 1 and computer == 2):
    print("电脑赢了,你是个猪吗")
else:
    print("平局,还不错")

猜你喜欢

转载自blog.csdn.net/weixin_41161522/article/details/86588640