CSDN话题挑战赛第2期
参赛话题:学习笔记
整理是为了方便自己学习记忆使用。
参考书籍《Python编程--从入门到实践》(第2版),[美] 埃里克·玛瑟斯。
一、if语句
1、if语句
animal = "cat"
if animal != "dog": # '!='表示不等于
print("Animal is not dog.")
2、if-else语句
如果动物是cat,就以全部大写的形式输出,否则,就用首字母大写的方式输出。
animals = ['dog', 'cat', 'bear', 'ant', 'sheep']
for i in animals:
if i == 'cat': # ‘==’表示等于,‘=’表示赋值
print(i.upper())
else:
print(i.title())
3、if-elif-else语句
门票设定,四岁以下不收费,4~18岁收费25元,18岁及以上收费40元。
age = 22
if age<4:
print("Your admission cost is $0.")
elif age<18:
print("Your admission cost is $25.")
else: # 不满足以上条件的所有条件
print("Your admission cost is $40.")
二、条件测试
if语句的核心是判断表达式的值为True还是False。
1、检查是否相等
赋值后判断是否相等。
2、检查是否不相等
在这里引用一个if语句。
animal = "cat"
if animal != "dog": # '!='表示不等于
print("Animal is not dog.")
if animal == "cat":
print(f"It is {animal.title()}.")
3、数值比较('>' '=' '<')
4、检查多个条件
(1)使用and检查多个条件
在这里会先执行判断,再执行and。and判断时,必须两侧的条件都是正确的,才会返回True。
(2)使用or检查多个条件
会先执行判断,再执行or,这里加上括号展示,更加清晰。
or判断时,只要有一个条件是正确的,就会返回True,只有两个条件都错误的时候,才会返回False。
5、检查特定值是否在列表中
animals = ['dog', 'cat', 'bear', 'ant', 'sheep']
it = 'bird'
if it not in animals:
print(f"{it.title()} is not here.")
三、使用if语句处理列表
一个文具店,一个客户要钢笔,本,尺子。但是本买完了。
tools = ['pen', 'book', 'ruler']
for it in tools:
if it == "book":
print("Sorry, the book bought.")
else:
print(f"This is your {it}.") # 这里{}得用以表示能单独取出的变量it,不是tools