Python学习之if循环

这篇博客介绍了Python中if循环的使用,包括数学条件、列表、字典的比较,if-else语句的简写形式,以及and和or的逻辑判断。通过示例代码展示了如何进行条件判断,并涉及random库的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

“”“Python if & while”""

1,if函数语句支持的数学条件

#函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
#== != > < >= <=
import random

age = random.randint(1, 101)
time = 100 - age

if age == time:
print(‘人到半百心犹盛’)
if age > time:
print(‘老当益壮气亦足’)
if age < time:
print(‘年少勇闯天下难’)

#这结果就是完全随机的了

2,list对比

test_num01 = [1, 3, 4, 5, 9]
test_num02 = [1, 3, 4, 5, 8]
if test_num01 == test_num02:
print(‘两个列表相等’)
if test_num01 != test_num02:
print(‘两个列表不相等’)

#两个列表不相等

3,字典对比

test_dict01 = {‘fruit’: ‘apple’, ‘plant’: ‘white poplar’}
test_dict02 = {‘plant’: ‘white poplar’, ‘fruit’: ‘apple’}
if test_dict01 == test_dict02:
print(‘两个字典相同’)
elif test_dict01 != test_dict02:
print(‘两个字典不相同’)

#两个字典相同

4, if 的兄弟 else

test_tuple01 = (1, 3, 5, 9)
test_tuple02 = (2, 4, 6, 8)
if test_tuple01 == test_tuple02:
print(‘一摸一样的元组双胞胎’)
else:
print(‘我想这两个是姐妹元组’)

#我想这两个是姐妹元组

5,if 语句的简写

bro1_age = 100
bro2_age = 99
if bro1_age > bro2_age: print(‘100岁的是哥哥,99的是弟弟’)

#100岁的是哥哥,99的是弟弟

6,简写 if else

child1 = ‘Lucas’
child2 = ‘Lux’
print(‘Lux love Lucas’) if child1 != child2 else print(‘They are same name.’)

#Lux love Lucas

7, and & or

sky = ‘blue’
choose = [‘above’, ‘below’]
space = random.choice(choose)
if sky == ‘blue’ and space == ‘above’:
print(‘blue sky’)
else:
print(‘gray sky’)

#blue sky

bird = [‘sparrow’, ‘eagle’]
fly = random.choice(bird)
if fly == ‘sparrow’ or fly == ‘eagle’:
print(‘Bird flying in the sky!’)

#Bird flying in the sky!

代码

#今天没有学习while循环,明天再补上
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值