Python学习笔记(四):if语句

第四章 if语句


4.1 条件测试


4.1.1 检查是否相等

car = 'bmw'
print(car == 'bmw')
print(car == 'byd')
print(car != 'byd')

输出结果:

True
False
True

  • == 等于
  • != 不等于
  • >, >=, <, <= 大小于等于

4.1.2 检查多个条件

car = 'bmw'
phone = 'iphone'
print(car == 'bmw' and phone == 'iphone')
print(car == 'byd' or phone == 'samsung')

True
False

  • and 逻辑且
  • or 逻辑或

4.1.3 检查特定值是否在列表中

nums = [10, 20, 30]
print(30 in nums)
print(40 not in nums)

True
True

  • in 在列表中
  • not in不在列表中

4.1.4 布尔表达式

flag = True
flag = False

不多赘述

4.2 if语句

age = 15
if age >= 18:
	print("You are old enough")
	print("You can vote now")

没有输出结果

Python的if语句不需要加括号。注意冒号

4.2.1 if-else语句

age = 15
if age >= 18:
	print("You are old enough")
	print("You can vote now")
else:
	print("You are too young")
	print("Please wait for " + str(18-age) + " year(s)")

输出结果:

You are too young
Please wait for 3 year(s)

4.2.2 if-elif-else语句

age = 15
if age >= 18:
	print("You are an adult")
elif age >= 12:
	print("You are a teenager")
else: 
	print("You are a child")

输出结果:

You are a teenager

4.2.3 检查列表是否为空

nums = []
if nums:
	print("list is not empty")
else:
	print("list is empty")

输出为:

list is empty

4.2.4 if语句与布尔表达式

flag = True
if flag:
    print("YES")
else:
    print("NO")

输出:

YES

不多赘述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值