二、控制流

关于《python编程快速上手-让繁琐工作自动化》的学习笔记

1.布尔值

True 和 False

2.比较操作符

操作符含义
==等于
!=不等于
<小于
>大于
<=小于等于
>=大于等于

3.布尔操作符

(比较级:not->and->or)

  • 二元布尔操作符(只接受两个布尔值,所以被认为是“二元”操作符)

1.and和or操作符

and操作符真值表

表达式求值
True and TrueTrue
True and FalseFalse
False and TrueFalse
False and FalseFalse

or操作符真值表

表达式求值
True or TrueTrue
True or FalseTrue
False or TrueTrue
False or FalseFalse

2.not操作符(只作用于一个布尔值)

not操作符真值表

表达式求值
not TrueFalse
not FalseTrue
  • 混合布尔和比较操作符
>>>(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+'.')   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值