Lesson 3

Python Basic, Lesson 3,

  • v1.0, 2016
  • v1.1, 2020.2,3,4 edit by David Yi

本章内容要点

  • for 循环语句和 range() 函数
  • 常用数据类型
    • 字符串
  • 思考

for 循环语句和 range() 函数

Python的循环语句主要是 for...in 循环,依次把 in 后面的 list列表或 tuple元组等中的每个元素迭代出来,进行循环;

Python 也有 while 循环,一般情况下不用。

for x in ... 循环就是把每个元素代入变量x,然后执行后面缩进块的语句。

如果是简单的按照次数的循环,一般用 range() 函数来产生一个可以生成迭代数字的序列。

我们看一下实际例子。


In [1]:
# 按照字符串进行迭代循环

s = 'abcdef'
for i in s:
    print(i)


a
b
c
d
e
f

In [2]:
# 按照列表进行循环,列表内容为字符

s = ['a', 'b', 'c']
for i in s:
    print(i)


a
b
c

In [3]:
# 按照列列表进行循环,列表内容为数字

for i in range(3):    
    print(i)


0
1
2

循环语句 while

while 循环是在 Python中的循环结构之一。 while 执行循环中的内容,直到表达式变为假。

表达式是指一个逻辑表达式,返回一个 True 或 False 值。 一定要小心设置表达式,如果永远是 True 的话,循环就一直执行下去了,称之为死循环。

大部分场景里,循环语句不建议使用 while,但有时候使用 while 语句会让程序很简洁。


In [4]:
# 用 while 进行循环

count = 0
while (count < 9):
    print('The count is:', count)
    count += 1
    
print("Good bye!")


The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

range() 函数

range() 函数产生一个等差序列,range(x,y,z),表示从 x 到 y(不含 y),z 为步长,可以为负。

修改下面例子中的 range() 中的起始、结束和步长,来看看各种效果。


In [5]:
# for 循环,使用range()

for i in range(1,10,3):
    print(i)


1
4
7

In [6]:
# for 循环,使用range()

for i in range(10,2,-1):
    print(i)


10
9
8
7
6
5
4
3

In [7]:
# print 时候输出内容,可以不换行

for i in range(10,2,-1):
    print(i,end='')


109876543

In [8]:
# print 时候不换行,优雅的分割

for i in range(10,2,-1):
    print(i,end=',')


10,9,8,7,6,5,4,3,

In [9]:
# 同时获得列表中的序号和内容,可以这样写
# len() 是获得列表的长度,可以理解为元素个数

s = ['Mary ', 'had', 'a', 'little ', 'lamb']
for i in range(len(s)):
    print(i, s[i])


0 Mary 
1 had
2 a
3 little 
4 lamb

In [10]:
# 更加好的写法, 使用 enumerate()

s = ['Mary ', 'had', 'a', 'little ', 'lamb']
for i, item in enumerate(s):
    print(i, item)


0 Mary 
1 had
2 a
3 little 
4 lamb

字符串

字符串即有序的字符的集合,用来存储或表现基于文本的信息。在程序开发中字符串被广泛使用。 Python 中使用单双引号都可以。


In [11]:
# 单引号

a = 'spam' 
print(a)


spam

In [12]:
# 双引号

a = "spam" 
print(a)
b = "spam's log"
print(b)


spam
spam's log

In [13]:
# 多行字符串
a = '''multile lines
this is an example'''
print(a)


multile lines
this is an example

In [14]:
s = 'a\nb\tc'  # 转义字符串
print(s)


a
b	c

In [15]:
# 输出内容因为转义而发生变化
a = 'C:\new\text.txt'
print(a)

# 输出内容不带转义
b = r'C:\new\text.txt'
print(b)


C:
ew	ext.txt
C:\new\text.txt

In [1]:
# 常用的字符串表达式

s = 'ABC.txt'
print(s + '123')  # 字符串拼接
print(s * 2)  # 重复
print(s[0])  # 索引
print(s[-1])
print(s[::-1])  # 反转
print(s[0:2]) # 切片


ABC.txt123
ABC.txtABC.txt
A
t
txt.CBA
AB

In [2]:
print(len(s))  # 长度
print(s.lower()) # 小写转换
print(s.upper()) # 大写转换
print(s.endswith('.txt'))  # 后缀测试
print('AB' in s) # 成员关系测试


7
abc.txt
ABC.TXT
True
True

练习

题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?

程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去掉不满足条件的排列。


In [1]:
for i in range(1,5):
    for j in range(1,5):
        for k in range(1,5):
            if( i != k ) and (i != j) and (j != k):
                print(i,j,k)


1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2

In [ ]: