关于《python编程快速上手-让繁琐工作自动化》的学习笔记
1.布尔值
True 和 False
2.比较操作符
操作符 | 含义 |
---|---|
== | 等于 |
!= | 不等于 |
< | 小于 |
> | 大于 |
<= | 小于等于 |
>= | 大于等于 |
3.布尔操作符
(比较级:not->and->or)
- 二元布尔操作符(只接受两个布尔值,所以被认为是“二元”操作符)
1.and和or操作符
and操作符真值表
表达式 | 求值 |
---|---|
True and True | True |
True and False | False |
False and True | False |
False and False | False |
or操作符真值表
表达式 | 求值 |
---|---|
True or True | True |
True or False | True |
False or True | True |
False or False | False |
2.not操作符(只作用于一个布尔值)
not操作符真值表
表达式 | 求值 |
---|---|
not True | False |
not False | True |
- 混合布尔和比较操作符
>>>(4<5)and(5<6)
True
4.控制流语句
-
if语句
如果条件为真,执行子句中的代码
if name=='Alice':
print('hello world!')
-
else语句
只有if语句代码为False时,else子句才会执行
if name=='Alice':
print('hello world!')
else:
print('hi~')
-
elif语句
elif语句是“否则如果”,总是跟在if或另一条elif语句后面
name=input()
age=input()
if name=='Alice':
print('hi,Alice!')
elif age<12:
print('hi,kiddo.')
-
while循环语句
只要while语句的条件为True,while子句中的代码就会执行
spam=0
while spam<5:
print('hello world!')
spam=spam+1
- break语句
执行时遇到break语句就会马上退出while循环子句
while True:
print('please type your name:')
name=input()
if name=='thee':
break
print('Thank you!')
- continue语句
执行时遇到continue语句就会马上跳回到循环开始处,重新判断循环条件
while True:
print('who are you?')
name=input()
if name!='thee':
continue
print('hello,thee!')
- for循环和range()函数
用于条件时,0,0.0,和‘ ’(空字符串)被认为是False,其他值被认为是True
tatal=0
for num in range(100):
total =total + num
print(total)
range()的开始、停止和步长参数:
for i in range(0,10,2)
print(i)
前两个参数分别是起始值和终止值,第三个参数是“步长”。步长是每次迭代后循环变量增加的值。第一个参数是for循环变量开始的值,第二个变量是上限,但不包括它,也就是循环停止的值
- 导入模块
import语句
import random
for i in range(5):
print(random.randint(1,10))
random.randint()函数调用求值为传递给它的两个整数之间的一个随机整数
from import语句
from random import *
for i in range(5):
print(randint(1,10))
调用random模块中的函数不需要random.前缀
- sys.exit()提前结束程序
import sys
while True:
print('Type exit to exit.')
response=input()
if response=='exit':
sys.exit()
print('You typed '+response+'.')