5.3 Python conditional testing

5.2.8 Boolean expressions

As you learn more about programming, you'll come across the term boolean expression , which is just an alias for conditional testing . Like conditional expressions, Boolean expressions evaluate to either True or False.

Boolean values ​​are often used to record conditions, such as whether a game is running, or whether a user can edit certain content of a website:

game_active = True
can_edit = False

Boolean values ​​provide an efficient way of keeping track of program state or important conditions in a program.

try it yourself

#5-1 条件测试: 编写一系列条件测试: 将每个测试以及你对其结果的预测和实际结果都打印出来。你编写的代码应类似于下面这样:
#car = 'subaru'
#print("Is car = 'subaru'? I predict True.")
#print(car == 'subaru')
#
#print("\nIs car == 'audi'? I predict False.")
#print(car == 'audi')
#详细研究实际结果,直到你明白了它为何为True或False。
#创建至少10个测试,且其中结果分别为 True 和 False 的测试都至少有5个。
car='bmw'
print("\nIs car=='bmw'?I predict True.")
print(car=='bmw')

print("\nIs car=='audi'?I predict False.")
print(car=='audi')

foods=['pizza','falafel','carrot cake','cannoli','ice cream']
print("\nIs 'rice' in foods?I predict False.")
print('rice' in foods)

print("\nIs 'pizza' in foods?I predict True.")
print('pizza' in foods)

print("\nIs 'beer' in foods?I predict False.")
print('beer' in foods)

print("\nIs 'ice cream' in foods?I predict True.")
print('ice cream' in foods)

names=["Iron Man","Spider Man","Captain","Ant-Man"]
print("\nIs 'Iron Man' in names?I predict True.")
print('Iron Man' in names)

print("\nIs 'Black Widow' in names?I predict False.")
print('Black Widow' in names)

print("\nIs 'Ant-Man' in names?I predict True.")
print('Ant-Man' in names)

print("\nIs 'Hulk' in names?I predict False.")
print('Hulk' in names)
#5-2 更多的条件测试: 你并非只能创建 10 人测试。如果你想尝试做更多的比较,可再编写一些测试,并将它们加入到 conditional tests.py 中。对于下面列出的各种测试至少编写一个结果为 True 和 False 的测试。
#检查两个字符串相等和不等。
#使用函数 lower()的测试。
#检查两个数字相等、不等、大于、小于、大于等于和小于等于。
#使用关键字 and和 or 的测试。
#测试特定的值是否包会在列表中。
#测试特定的值是否未包含在列表中。

#1检查两个字符串相等和不等。
car='bmw'
print(car=='bmw')
print(car=='audi')

#2使用函数lower()测试。
car='BMW'
print(car.lower()=='bmw')
print(car.lower()=='audi')

#3检查两个数字相等、不等、大于、小于、大于等于和小于等于。
number_0=50
print(number_0==50)
print(number_0!=50)
print(number_0>40)
print(number_0<40)
print(number_0<=50)
print(number_0>=60)

#4使用关键字and和or的测试。
number_0=13
number_1=23
print(number_0>=0 and number_1>=10)
print(number_0>=15 and number_1>=15)
print(number_0>=15 or number_1>=15)
print(number_0>=25 or number_1>=25)

#5试特定的值是否包含在列表中。
cars=['bmw','audi','subaru']
print('bmw' in cars)

#6试特定的值是都未包含在列表中。
print('toyota' in cars)

Guess you like

Origin blog.csdn.net/Allen1862105/article/details/129226604
5.3