Python编程入门到实践 - 笔记( 5 章)

第 5 章练习了以下内容

简单的 if 判断语句

判断字符串是否相等,还是不等

进行数字的大小比较

and,or 比较

检查列表中是否存在指定的元素

if,if-else,if-elif-else 语句写法

if 判断列表是否为空

使用多个列表进行比较判断

这一章的内容也比较简单,感觉和 shell 差不多,但还是多练习吧。

希望路过的大牛指出不足,小弟在此谢过了。



一个简单的 if 判断语句

循环打印 cars 列表中的元素,如果其中的元素等于 bmw,就全部大写打印

否则只是将元素的首字母大写

-------------------------------------------------

cars = [‘audi‘, ‘bmw‘, ‘subaru‘, ‘toyota‘]

for car in cars:  
     if car == ‘bmw‘:    
          print(car.upper())    
     else:    
          print(car.title())

-----------------------------------------------------

Audi  
BMW    
Subaru    
Toyota



判断是否相等

大小写不一样,也会不等

--------------------------

car = ‘Audi‘  
print(car == ‘Audi‘)

--------------------------

True

--------------------------

car = ‘Audi‘  
print(car == ‘audi‘)

---------------------------

False

转换大小写进行比较

------------------------------------

car = ‘Audi‘  
print(car.lower() == ‘audi‘)

------------------------------------

True

检查是否不相等

不过两个值不相等,就打印

-----------------------------------------------

requested_topping = ‘mushrooms‘

if requested_topping != ‘anchovies‘:  
      print("Hold the anchovies!")

------------------------------------------------

Hold the anchovies!

数字的比较

----------------------

age = 18  
print(age == 18)

----------------------

True

进行 if 语句判断,如果两个数字不等,就打印

-----------------------------------------------------------------------------

answer = 17  
if answer != 18:    
     print("That is not the correct answer. Please try again!")

-----------------------------------------------------------------------------

That is not the correct answer. Please try again!

不光可以进行比较是否相等,还可以比较大小

直接在 python 的 IDE 下进行比较是不是看着更方便。哈哈哈

>>> age = 19  
>>> age < 21    
True    
>>> age <= 21    
True    
>>> age > 21    
False    
>>> age >= 21    
False

检查多个条件

and 当两个条件都满足的情况下,打印 True 否则打印 False

>>> age_0 = 22  
>>> age_1 = 18    
>>> age_0 >= 21 and age_1 >=21    
False    
>>> age_1 = 22    
>>> age_0 >= 21 and age_1 >=21    
True

or 至少满足一个条件,打印 True 否则打印 False

>>> age_0 = 22  
>>> age_1 = 18    
>>> age_0 >= 21 or age_1 >= 21    
True    
>>> age_0 = 18    
>>> age_0 >= 21 or age_1 >= 21    
False

检查指定的值是否包含在列表中

----------------------------------------------------------------------------

requested_toppings = [‘mushrooms‘, ‘onions‘, ‘pineapple‘]  
print(‘mushrooms‘ in requested_toppings)    
print(‘pepperoni‘ in requested_toppings)

----------------------------------------------------------------------------

True  
False

给要查找的值指定一个变量并查找,如果不存就打印出来

----------------------------------------------------------------------------

banned_users = [‘andrew‘, ‘carolina‘, ‘david‘]  
user = ‘marie‘

if user not in banned_users:  
     print(user.title() + ", you can post a response if you wish.")

----------------------------------------------------------------------------

Marie, you can post a response if you wish.

简单的 if 语句

设定年龄为19,进行 if 语句判断,如果大于18就打印

---------------------------------------------------

age = 19  
if age >= 18:    
     print("You are old enough to vote!")

----------------------------------------------------

You are old enough to vote!

if-else 语句

设定年龄为 17,与 18 进行比较,如果大于等于 18 就打印 if 下的语句,

否则打印 else 中的语句

----------------------------------------------------------------------------

age = 17  
if age >= 18:    
     print("You are old enough to vote!")    
     print("Have you registered to vote yet?")    
else:    
     print("Sorry, you are too young to vote.")    
     print("Please register to vote as soon as you turn 18!")

------------------------------------------------------------------------------

Sorry, you are too young to vote.  
Please register to vote as soon as you turn 18!

if-elif-else 语句

年龄设定为 17,分别进行判断,小于 4 多少钱,小于 18 多少钱,其他多少钱进行打印

--------------------------------------------------

age = 17  
if age < 4:    
     print("Your admission cost is $0.")    
elif age < 18:    
     print("Your admission cost is $5.")    
else:    
     print("Your admission cost is $10.")

----------------------------------------------------

Your admission cost is $5.

简化一下上面的写法,将判断的值定义一个变量,最后打印

----------------------------------------------------------------

age = 12  
if age < 4:    
     price = 0    
elif age < 18:    
      price = 5    
else:    
     price = 10

print("Your admission cost is $" + str(price) + ".")

-----------------------------------------------------------------

Your admission cost is $5.



使用多个 elif 代码块

判断条件当然不止3个,这时候就用到了多个 elif 代码块

python 并不要求必须有 else 代码块,虽然书里是这么写的,但我作为小白的我还是倔强的认为这个习惯不太好,

所以自作主张不练这个 ’省略代码块‘ 了

----------------------------------------------------------------

age = 12  
if age < 4:    
     price = 0    
elif age < 18:    
     price = 5    
elif age < 65:    
     price = 10    
else:    
     price = 5

print("Your admission cost is $" + str(price) + ".")

----------------------------------------------------------------

Your admission cost is $5.



检查特殊元素

判断列表中的元素并指定某个元素,进行判断

-------------------------------------------------------------------------------------------

requsested_toppings = [‘mushrooms‘, ‘green peppers‘, ‘extra cheese‘]  
for requsested_topping in requsested_toppings:    
     if requsested_topping == ‘green peppers‘:    
          print("Sorry, we are out of green peppers right now.")    
     else:    
          print("Adding " + requsested_topping + ".")    
print("\nFinished making your pizza!")

-------------------------------------------------------------------------------------------

Adding mushrooms.  
Sorry, we are out of green peppers right now.    
Adding extra cheese.

Finished making your pizza!

在 循环之前先进行一个 if 判断

if requested_toppings 意识是对列表进行判断,列表中至少有一个元素时,返回 True,

现在这个列表为空,返回值为 False,打印 else 代码块中的内容

--------------------------------------------------------------

requested_toppings = []

if requested_toppings:  
     for requested_topping in requested_toppings:    
          print("Adding " + requested_topping + ".")    
     print("\nFinished making your pizza!")    
else:    
      print("Are you sure you want a plain pizza?")

----------------------------------------------------------------

Are you sure you want a plain pizza?

使用多个列表

对 requested_toppings 进行遍历,和 available_toppings 列表中的元素进行比较

-------------------------------------------------------------------------------------

available_toppings = [‘mushrooms‘, ‘olives‘, ‘green peppers‘,  
                      ‘pepperoni‘, ‘pineapple‘, ‘extra cheese‘]    
requested_toppings = [‘mushrooms‘, ‘french fries‘, ‘extra cheese‘]

for requested_topping in requested_toppings:  
     if requested_topping in available_toppings:    
          print("Adding " + requested_topping + ".")    
     else:    
          print("Sorry, we don‘t have " + requested_topping + ".")    
print("\nFinished making your pizza!")

--------------------------------------------------------------------------------------

Adding mushrooms.  
Sorry, we don‘t have french fries.    
Adding extra cheese.

Finished making your pizza!

时间: 2024-08-11 01:25:39

Python编程入门到实践 - 笔记( 5 章)的相关文章

Python编程入门到实践 - 笔记(1,2章)

自学 Python 有段时间了,总是觉得自己基础不牢,想着把看完的两本基础书写个博客做个笔记啥的. 准备在重新看一遍<Python编程入门到实践>,坚持写博客笔记. Python编程入门到实践的前两章笔记,学习的内容如下: 查看当前环境中的 python 版本 python环境的搭建 变量和变量的命名 字符串的打印 修改字符串的大小写 制表符和换行符 删除空白字符 python的整数运算,计算平方,立方 使用 str() 函数 查看当前环境中的 python 版本 命令行下输入 python 

Python编程入门到实践 - 笔记( 8 章)

第 8 章主要练习了各种函数,内容如下 定义一个简单的函数 向函数传递信息 什么是形参 什么是实参 位置参数 多次调用函数 关键字实参 默认值参数 返回值 return 让参数编程可选的 返回字典 结合使用函数和 while 循环 传递列表 在函数中修改列表 传递任意数量的实参 传递任意数量的参数并循环打印 结合使用位置参数和任意数量实参 使用任意数量的关键字实参 导入整个模块 导入特定的函数 使用 as 给函数指定别名 使用 as 给模块指定别名 导入模块中所有的函数 定义一个简单的函数 直接

Python编程入门到实践 - 笔记( 9 章)

第 9 章主要讲的类,这个之前在 shell 中没遇到过 一直运用的也不是很溜,不过多敲多练,应该会有进步吧 创建类和使用类 创建一个 Dog 类 --------------------------------------------------------------------- class Dog():         def __init__(self, name, age):               self.name = name               self.age

Python编程入门到实践 - 笔记( 6 章)

第 6 章主要练习了各种字典,以下内容 什么是字典 字典中 键-值 的关系 一个简单的字典 通过字典中的键查找其对应的值 在字典中添加 键-值 修改字典中的值 遍历字典中的键值对 items( ) 遍历字典中的键 keys( ) 遍历字典中的值 value( ) 遍历字典中的值并且去重复 set( ) 列表中嵌套字典 通过 for 循环将字典添加到同一个列表中 在字典中存储列表并打印 什么是字典? 我自己来个不成熟的总结吧:就是一个高级列表,为啥说是高级列表,因为列表中的元素是单一的,没有属性

Python编程入门到实践 - 笔记( 7 章)

第 7 章讲了用户输入 input( ) 和 while 循环,内容如下 input( ) 工作原理 超过一行的 input( ) int( ) 来获取数字的输入,进行比较 求模运算 简单的 while 循环.我自己的理解就是设定一个条件,while 满足这个条件开始循环,不满足退出 break 直接退出 continue 跳出当前层的循环 避免无限循环 while 在列表中的应用 while 删除列表中指定的字符串 remove() 用户输入的字符来填充字典 input( ) 工作原理 首先定

Python编程入门到实践 - 笔记( 3 章)

练习内容包括 创建并访问列表 列表的索引 使用列表中的各个值 修改列表中的元素 在列表中添加元素 append() 在列表中插入元素 insert() 在列表中删除元素 del,pop() 根据值删除列表中的元素 remove() 对列表中的元素进行排列 1)永久性修改 sort(),按字母表正向排列 2)永久性修改 sort(reverse=True),按字母表反向排列 3)临时修改 sorted(),按字母表正向排列 对列表中的元素进行反转打印 reverse() 计算列表长度 len()

Python编程入门与实践pdf电子版下载

Python编程入门与实践pdf电子版下载 分享链接:https://pan.baidu.com/s/1h7TfuuUcaju8nkrMZgv-hg 提取码:7lo8 本书针对想要学习Python却无从下手的同学们准备的,希望好的资源能够给老铁提供有用的帮助 书籍目录 第一部分 基础知识 第1章 起步 1.1 搭建编程环境 1.1.1 Python 2和Python 3 1.1.2 运行Python代码片段 1.1.3 Hello World程序 1.2 在不同操作系统中搭建Python编程环境

Python编程入门到实践(三)

1.异常 异常是使用try-except代码块处理的.try-except代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办. 使用了try-except代码块时,即便出现异常,程序也将继续运行:显示你编写的友好错误消息,而不是令用户迷惑的traceback.. print(5/0) Traceback (most recent call last): File "exception_division", line 1, in <module> pri

Python:从入门到实践--第三章--列表简介--练习

#1.将一些朋友的姓名存储在一个列表中,并将其命名为friends.依次访问该列表中的每个元素,从而将每个朋友的姓名都打印出来. #2.继续使用1中的列表,为每人打印一条消息,每条消息包含相同的问候语,但抬头为相应朋友的名字 #3.创建一个自己喜欢的出行方式列表.根据该列表打印一系列有关这些出行方式的宣言. friends = ['马脑壳','小波','玮哥','二小姐','短命','田鸡'] print(friends[0] +'\n' + friends[1] + '\n' + friend