“”“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循环,明天再补上