美文网首页
09-if判断语句

09-if判断语句

作者: 努力爬行中的蜗牛 | 来源:发表于2018-10-25 22:27 被阅读0次
if判断语句基本语法
if 条件:
   ......

注意:python开发中,tab和空格不要混用。

age = 20
if age >= 18:
    print("你已经成年了")
比较运算符

== , >, < ,>= , <= , !=
在python2.x中,不等于还可以用<>表示

注意:if语句和缩进部分是一个完整的代码块
例如:

age = 12
if age >= 18:
    print("你已经成年了")
    print("执行了")
print("hello")

PyCharm代码块及光标的位置提示,如图


光标的位置提示.png
if else条件判断语句
if  条件:
    条件成立时
    ......
else:
    条件不成立时
    ......
age = int(input("请输入你的年龄:"))  #不同类型不能直接比较,这里进行转换
if age >= 18:
    print("你已经成年了")
else:
    print("你还没有成年")

if else 可以看成一个完整的代码块

逻辑运算符

python中,逻辑运算符包括:and/or/非 not三种。

  • and
    条件1 and 条件2
age = int(input("请输入你的年龄:"))
if age > 0 and age <= 120:
    print("年龄正确")
else:
    print("年龄有误")
  • or
    条件1 or 条件2
python_score = int(input("请输入你的python分数:"))
c_score = int(input("请输入你的c语言分数:"))
if python_score > 60 or c_score >= 60:
    print("恭喜过关")
else:
    print("继续加油哦")
  • not
    not 条件
is_emplyee = True
if not is_emplyee:
    print("非本公司员工,请勿入内")
elif使用
python_score = int(input("请输入你的python分数:"))
if python_score < 60:
    print("小伙子,你没及格")
elif python_score < 80:
    print("中等")
elif python_score < 90:
    print("中上等")
else:
    print("优秀")

使用Tab键统一增加缩进,选中,按下Tab键或者Shift + Tab键。

if的嵌套
石头剪刀布的例子
#导入模块后,可以直接再模块后面敲一个.,则可以查看该模块包含的所有函数
import random
player = int(input("请输入你的手势 1石头 2剪刀 3布:"))
computer = random.randint(1,3)
if ((player == 1 and computer == 2)
        or (player == 2 and computer == 3)
        or (player == 2 and computer == 1)):
    print("我赢了,电脑弱爆了")
elif player == computer:
    print("平分秋色")
else:
    print("再接再厉")

相关文章

网友评论

      本文标题:09-if判断语句

      本文链接:https://www.haomeiwen.com/subject/etthtqtx.html