python基础复习笔记

文章目录

  • 💘1.for循环
  • 🌸1.1for循环基本语法
  • 🥀1.2 range介绍
  • 🌱1.3 break、continue、pass的区别
  • 🧡2.While循环

💘1.for循环

  • 重复执行某些语句
  • 分类
  • for循环
  • while循环

🌸1.1for循环基本语法

for 变量 in 序列:
      语句1
      语句2
      ...
# 打印列表中的每一个值
# 列表是用中括号表示的一些列值
colour = ['black','red','blue','green','yellow']
for col in colour :
    print(col)
black
red
blue
green
yellow

下面看看for循环和if语句的结合
例如,我最喜欢的颜色是black,如果颜色是black,返回I like it

colour = ['black','red','blue','green','yellow']
for col in colour :
    if col == 'black':
        print('I like it')
    else:
        print('I hate it')
I like it
I hate it
I hate it
I hate it
I hate it

🥀1.2 range介绍

  • 生成某一数字序列
  • range(a,b)左闭右开
# range练习
# 打印从1-10的数字
# 注意,一般在python中,如果由表示数字范围的两个数,一般是包含左边数字不包含右边数字
for i in range(1,11):
    print(i)
1
2
3
4
5
6
7
8
9
10

🌱1.3 break、continue、pass的区别

  • break:直接结束循环
  • continue:跳出当前循环,进入下一轮循环
  • pass:占位,无实际意义

break
例如我们要从上面的colour列表找到red,一旦找到就结束循环

for col in colour:
    if col == 'red':
        print('I find the red')
I find the red

continue
例如我们要从1-10中找出所有的偶数并打印。

  • 1.我们先使用for循环遍历1-10
  • 2.通过if语句判断是否是偶数,如果是,则打印出来
  • 3.如果不是偶数,跳出循环直接进入下一个循环。
    因为我们这里要找到所有的偶数,如果使用break只能得到第一个偶数
for i in range(1,11):
    if i % 2 == 1:
        continue
    print('%d是偶数'%(i))
2是偶数
4是偶数
6是偶数
8是偶数
10是偶数

🧡2.While循环

  • while循环和for循环不同的是其只要条件成立,则发生循环。
  • while循环不知道具体的循环次数,但是知道循环条件。
  • while循环的基本语法:
while 条件表达式:
    循环语句
[else]:
    循环语句

else可以省略

下面进行举例说明:假设年利率为5%,按照复利计算,则几年后本金翻倍

# 定义本金和年份,这里我们假设本金是10000
x = 10000
year = 0
# 此时我们的while条件一个是x小于20000,则循环继续
while x < 20000:
    x = (1+0.05)*x
    year += 1
    print('第%d年本息%d'%(year,x))
第1年本息10500
第2年本息11025
第3年本息11576
第4年本息12155
第5年本息12762
第6年本息13400
第7年本息14071
第8年本息14774
第9年本息15513
第10年本息16288
第11年本息17103
第12年本息17958
第13年本息18856
第14年本息19799
第15年本息20789

说明15年之后翻倍,上述在循环结束后就代码就停止,如果我们还希望在循环结束之后打印cheers~,可以使用else

# 定义本金和年份,这里我们假设本金是10000
x = 10000
year = 0
# 此时我们的while条件一个是x小于20000,则循环继续
while x < 20000:
    x = (1+0.05)*x
    year += 1
    print('第%d年本息%d'%(year,x))
else:
    print('cheers,本金在第%d年翻倍了'%year)
第1年本息10500
第2年本息11025
第3年本息11576
第4年本息12155
第5年本息12762
第6年本息13400
第7年本息14071
第8年本息14774
第9年本息15513
第10年本息16288
第11年本息17103
第12年本息17958
第13年本息18856
第14年本息19799
第15年本息20789
cheers,本金在第15年翻倍了