第二章 Python 基础

Python3条件循环之while

Python循环语句的控制结构如下所示:

Python语法如下:

while   判断条件:
     循环语句

# 只要条件满足,就不断循环,条件不满足时退出循环

打印1到10:

n = 1
while n < 11:
    print(n)
    n += 1

打印1到99之间的偶数

n = 0
while n < 99:
    n += 1
    if n % 2 == 0:
        print(n)

打印1到99之间的奇数

n = 0
while n < 99:
    n += 1
    if n % 2 == 1:
        print(n)

死循环

n = 0 
while True:
    print(n)

循环嵌套与tag

tag = True

while tag:
    print("第一层")
    while tag:
        print("第二层")
        while tag:
            print("第三层")
            tag = False
            
#运行
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/while.py
第一层
第二层
第三层

# 仔细想想你会懂得?😁

break与continue

#break:用于退出本层循环

n = 0
while True:
    if n == 5:
        break
    print(n)
    n += 1 

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/while.py
0
1
2
3
4

ps:当n=5则会退出本层循环(break)
#continue:用于退出跳过本次循环,继续下一次循环

n = 0
while n < 10:
    n += 1
    if n == 5:
        continue
    print(n)
    
运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/while.py
1
2
3
4
6
7
8
9
10

ps:打印1-10,则不打印5,当n=5时跳过本次循环,进行下一次循环(continue)

while+else

#与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句,while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句
n = 0
while n < 3:
    print(n)
    n += 1
else:
    print("代码执行完毕")

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/while.py
0
1
2
代码执行完毕

while循环练习题

#1. 使用while循环输出1 2 3 4 5 6     8 9 10

n = 0
while n < 10:
    n += 1
    if n == 7:
        continue
    print(n)

#运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/while.py
1
2
3
4
5
6
8
9
10

#2. 求1-100的所有数的和
res = 0
count = 1
while count <= 100:
    res += count
    count += 1
print(res)


#3.求1-2+3-4+5 ... 99的所有数的和
res = 0
count = 0
while count <= 99:
    count += 1
    if count % 2 == 0:
        res += count
    else:
        res -= count
print(res)

流程控制之for循环

迭代式循环:for,语法如下:

for i in range(10):

    缩进的代码块
    
ps:内置range()函数,它会生成数列

break与continue(同上)

练习

  1. 打印九九乘法口诀表

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 打印九九乘法表
for line in range(1, 10):
    for column in range(1, line+1):
        print('%sx%s=%s' % (line, column, line*column), end=' ')
    print()


  1. 打印金字塔
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 金字塔
#              #line=5
#     *        #value=1,空格数=4,*号数=1
#    ***       #value=2,空格数=3,*号数=3
#   *****      #value=3,空格数=2,*号数=5
#  *******     #value=4,空格数=1,*号数=7
# *********    #value=5,空格数=0,*号数=9

line = 5
for value in range(1, line+1):        # 打印1-5行数
    for blank in range(line-value):   # 循环空格数
        print(" ", end="")
    for star in range(2*value-1):      # 循环*号数
        print("*", end="")
    print()                           # 换行


数据类型

  1. 什么是数据?
    x = 10, 10是我们要存储的数据

  2. 为何数据要分不同的类型
    数据是用来表示状态的,不同的状态就应该用不同的类型的数据去表示

  3. 数据类型分为哪几种:

  • 数字:整形,长整形,浮点型,复数)
  • 字符串
  • 列表
  • 元组
  • 字典
  • 集合

数字

python3 支持int,float,bool,complex(复数)
在python3里,只有一种整数类型int,表示为长整型,没有python2 中的 Long。
像大多数语言一样,数值类型的赋值和计算都是很直观的。
内置的 type() 函数可以用来查询变量所指的对象类型。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/test.py
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

整型(int)

作用:年龄,登记,身份证号等整型数字相关
定义:
age=18 #本质age=int(10)

浮点型float

作用:薪资,身高,体重,体质参数等浮点数相关
salary=3000.3 #本质salary=float(3000.3)

字符串(String)

Python中的字符串用单引号(')或双引号(")括起来,同时使用反斜杠()转义特殊字符。
字符串截取的语法:

变量[头下标:尾下标
> 1. 按索引取值(正向取+反向取):只能取

name = 'jack'
print(name[1])     # 取第二值
print(name[-1])    # 取倒数第一值

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
a
k
# 字符串类型是不可变类型,则不能更改

> 2. 切片(顾头不顾尾,步长)
name = "what is your name"
print(name[0:4])     # 取0到4的值
print(name[:])       # 取完
print(name[::-1])    # 倒着迈步取

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
what
what is your name
eman ruoy si tahw

3. 长度len
name = "what is your name"
print(len(name))      # 取长度

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
17

4. 成员运算in和not in
# in  #是否在里面
# not #不在里面为true,在里面为false
name = "what is your name"
print('name' in name)
print('name' not in name)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
True
False

5. 移除空白strip
name = "what is your name"
print(name.strip())
user = input("请输入账户:").strip()

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
what is your name
请输入账户:(当用户输入空格则自动移除)


6. 切分split
info = "xcn:123:admin".split(':')    # 转换为列表取值
print(info[0])

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
xcn

7. 循环
mgs = 'jack is sb'
i = 0
while True:
    if i < len(mgs):
        print(mgs[i])
        i += 1
 
 
运行:       
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
j
a
c
k
 
i
s
 
s
b

8. strip,lstrip,rstrip
print("***sss***".lstrip('*'))   # 去除左边的
print("***sss***".rstrip('*'))   # 去除右边的

运行;
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
sss***
***sss

9. lower,upper
print('Xcn'.lower())   # 所有大写变成小写
print('xcn'.upper())   # 所有小写变成大写

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
xcn
XCN

10. startswith,endswith
print('jack is sb'.startswith('jack'))   # 以jack开头为True
print('jack is sb'.endswith('sb'))    # 以sb结尾为True

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
True
True

11. format的三种玩法
# 第一种:{}
s1 = 'my name is {} my age is {}'.format('alex', '18')
print(s1)
# 第二种:
s1 = 'my name is {0} my age is {2}'.format('alex', '18', '19')
print(s1)
# 第三种:
s1 = 'my name is {name} my age is {age}'.format(name='alex', age='18')
print(s1)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
my name is alex my age is 18
my name is alex my age is 19
my name is alex my age is 18

12. split,rsplit
cmd = "jack:age:18"
i = cmd.split(':')
print(i)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
['jack', 'age', '18']

13. join
cmd = "jack:age:18"
i = cmd.split(':')
res = ':'.join(i)
res = ''.join(i)
print(res)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
jackage18

14. replace
msg = 'jack say my name is jack'
print(msg.replace('jack', 'sb'))
print(msg.replace('jack', 'sb', 1))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
sb say my name is sb
sb say my name is jack

15. isdigit
print('10'.isdigit())
print('10.1'.isdigit())

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
True
False

16. find,rfind,index,rindex,count
mgs = '123 egon 456 egon hello xxx'
print(mgs.find('egon'))   # 打印egon起始位置
print(mgs.rfind('egon'))  # 打印第二个egon起始位置
print(mgs.index('egon'))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
4
13
4

17. center,ljust,rjust,zfill
print('egon'.center(50, '#'))   # 打印居中
print('egon'.rjust(50, '#'))   # 右对齐
print('egon'.ljust(50, '#'))   # 左对齐
print('egon'.zfill(50))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
#######################egon#######################
##############################################egon
egon##############################################
0000000000000000000000000000000000000000000000egon

18. expandtabs
msg = 'abc\tdef'
print(msg.expandtabs(3))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
abc   def

19. captalize,swapcase,title
print('abcDEF'.capitalize())  # 所有大写变成小写,首字母变大写
print('abc DEF'.title())   # 首字母大写

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
Abcdef
Abc Def

20. is数字系列

num1 = b'4'   # bytes
num2 = u'4'  # unicode,python3中无需加u就是unicode
num3 = '四'  # 中文数字
num4 = 'IV'   # 罗马数字

# bytes,unicode的阿拉伯数字
print(num1.isdigit())
print(num2.isdigit())
print(num3.isdigit())
print(num4.isdigit())

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
True
True
False
False

21. isqita

print('dafadfadf'.isalpha())  # 全为字母为True
print('1232af13123'.isalnum())  # 字符串或数字组成为True

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/02-字符串类型.py
True
True
 
# 总结字符串类型:
# 1. 存一个值
#     只能存一个值
# 2. 有序or无序
#  有序:能按照索引取值都是有序的
# 3. 可变or不可变
# !!! 不可变:值变,id就变。不可变==可hash

列表(List)

List(列表)是Python中使用最频繁的数据类型。
列表可以完成大多数集合类的数据结构实现,列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。
列表是写在方括号([])之间,用逗号分隔开的元素列表
和字符串一样,列表同样可以被索引和截取,列表截取后返回一个包含所需元素的新列表。

列表截取的语法格式如下:

变量[头下标:尾下标]
# 1. 用途:存放多个值
# 2. 定义方式:[]内以逗号为分割多个元素,列表内元素无类型限制
# i = ['a', 'b', 'c']
# print(i)

#1、按索引存取值(正向存取+反向存取):即可存也可以取 
i = ['a', 'b', 'c']
print(i[0])    # 正向取
print(i[-1])   # 反向取

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
a
c
     
#2、切片(顾头不顾尾,步长)
student = ['aaa', 'bbb', 'ccc']
print(student[1:2])

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
['bbb']

#3、长度
student = ['aaa', 'bbb', 'ccc']
print(len(student))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
3

#4、成员运算in和not in
student = ['aaa', 'bbb', 'ccc']
print('aaa' in student)
print('aaa' not in student)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
True
False


#5、追加
student = ['aaa', 'bbb', 'ccc']
student.append('xxx')
print(student)
student.insert(0, 'bxx')   # 在索引0前面插入
print(student)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
['aaa', 'bbb', 'ccc', 'xxx']
['bxx', 'aaa', 'bbb', 'ccc', 'xxx']

#6、删除
student = ['aaa', 'bbb', 'ccc']
del student[1]    # 万能删除法
student.remove('bbb')
print(student)
student.pop(0)     # 按照索引删除
print(student)

#7、循环
student = ['aaa', 'bbb', 'ccc']

# 依赖索引
i = 0
while i < len(student):
    print(student[i])
    i += 1
    
运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
aaa
bbb
ccc

# 不依赖索引
for item in student:
    print(item)

for item in range(len(student)):
    print(student[item])

#8. clear()
student = ['aaa', 'bbb', 'wxx']
student.clear()   # 把列表清楚掉
print(student)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
[]

#9. copy
student = ['aaa', 'bbb', 'wxx']
i = student.copy()  # copy 一个列表
print(i)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
['aaa', 'bbb', 'wxx']


#10. count
student = ['aaa', 'bbb', 'wxx', 'aaa']
print(student.count('aaa'))   # 统计元素的个数

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
2

#11. extend
student = ['aaa', 'bbb', 'wxx', 'aaa']
student.extend(['a', 'b'])   # 扩展多个值
print(student)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
['aaa', 'bbb', 'wxx', 'aaa', 'a', 'b']

#12. index
student = ['aaa', 'bbb', 'wxx', 'aaa']
print(student.index('bbb'))   # 取元素的索引

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
1

#13. sort 
L = [1, 2, 8, 3, 6, 5]
L.sort()       # 默认从小到大排序
L.sort(reverse=True)   # 从大到小排序
print(L)

运行L
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/03-列表.py
[8, 6, 5, 3, 2, 1]

元组(Tuple)

元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开。
元组中的元素类型也可以不相同:

tuple = ('abcd', 786, 2.23, 'xcn', 70.2)
tinytuple = (123, 'xcn')

print(tuple)  # 输出完整元组
print(tuple[0])  # 输出元组的第一个元素
print(tuple[1:3])  # 输出从第二个元素开始到第三个元素
print(tuple[2:])  # 输出从第三个元素开始的所有元素
print(tinytuple * 2)  # 输出两次元组
print(tuple + tinytuple)  # 连接元组

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/04-元组.py
('abcd', 786, 2.23, 'xcn', 70.2)
abcd
(786, 2.23)
(2.23, 'xcn', 70.2)
(123, 'xcn', 123, 'xcn')
('abcd', 786, 2.23, 'xcn', 70.2, 123, 'xcn')

注意:

1、与字符串一样,元组的元素不能修改。
2、元组也可以被索引和切片,方法一样。
3、注意构造包含0或1个元素的元组的特殊语法规则。
4、元组也可以使用+操作符进行拼接

字典(Dictionary)

字典(dictionary)是Python中另一个非常有用的内置数据类型。

列表是有序的对象集合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。

键(key)必须使用不可变类型。

在同一个字典中,键(key)必须是唯一的。

#作用:存多个值,key-value存取,取值速度快

#定义:key必须是不可变类型,value可以是任意类型
info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})
或
info=dict(name='egon',age=18,sex='male')
或
info=dict([['name','egon'],('age',18)])
或
{}.fromkeys(('name','age','sex'),None)

#优先掌握的操作:
#1、按key存取值:可存可取
info = {"name": "aaa", "age": "18"}
print(info["name"])

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/字典.py
aaa

#2、长度len
info = {"name": "aaa", "age": "18"}
print(len(info))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/字典.py
2

#3、成员运算in和not in
info = {"name": "aaa", "age": "18"}
print("aaa" in info["name"])
print("aaa" not in info["name"])

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/字典.py
True
False

#4、删除
info = {"name": "aaa", "age": "18"}
info.pop("name")
print(info)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/字典.py
{'age': '18'}

#5、键keys(),值values(),键值对items()
>>> dic={'name':'egon','age':18}
>>> print(dic)
{'name': 'egon', 'age': 18}
>>> print(dic.keys())
dict_keys(['name', 'age'])
>>> print(dic.values())
dict_values(['egon', 18])
>>> print(dic.items())
dict_items([('name', 'egon'), ('age', 18)])

#6、循环
>>> dic={'name':'egon','age':18}
>>> for key in dic.keys():
...     print(key)
... 
name
age
>>> dic={'name':'egon','age':18}
>>> for value in dic.values():
...     print(value)
... 
egon
>>> dic={'name':'egon','age':18}
>>> for k,v in dic.items():
...     print(k,v)
... 
name egon
age 18

注意:

1、字典是一种映射类型,它的元素是键值对。
2、字典的关键字必须为不可变类型,且不能重复。
3、创建空字典使用 { }。

集合(Set)

集合(set)是一个无序不重复元素的序列。

基本功能是进行成员关系测试和删除重复元素。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

#作用:去重,关系运算,

#定义:
            知识点回顾
            可变类型是不可hash类型
            不可变类型是可hash类型

#定义集合:
            集合:可以包含多个元素,用逗号分割,
            集合的元素遵循三个原则:
             1:每个元素必须是不可变类型(可hash,可作为字典的key)
             2:没有重复的元素
             3:无序

注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值


#1、长度len
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print(len(student))

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/集合.py
5

#2、成员运算in和not in
student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print("Tom" in student)
print("Tom" not in student)

运行:
/usr/local/bin/python3.5 /Users/xcn/PycharmProjects/oldboy/day2/集合.py
True
False

#3、|合集
a = set('abracadabra')
b = set('alacazam')
print(a | b)

运行:
{'b', 'm', 'a', 'd', 'c', 'r', 'z', 'l'}

#4、&交集
a = set('abracadabra')
b = set('alacazam')
print(a & b )

运行:
{'c', 'a'}

#5、-差集
a = set('abracadabra')
b = set('alacazam')
print(a - b)

运行:
{'b', 'r', 'd'}

#6、^对称差集
a = set('abracadabra')
b = set('alacazam')
print(a ^ b)

运行:
{'b', 'm', 'd', 'r', 'z', 'l'}

#7、==
a = set('abracadabra')
b = set('alacazam')
print(a == b )

运行:
False

#8、父集:>,>= 
a = set('abracadabra')
b = set('alacazam')
print(a > b)
print(a >= b)

运行:
False
False

#9、子集:<,<=    
a = set('abracadabra')
b = set('alacazam')

print(a < b)
print(a <= b)

运行:
False
False

按存储空间的占用分(从低到高)

数字
字符串
集合:无序,即无序存索引相关信息
元组:有序,需要存索引相关信息,不可变
列表:有序,需要存索引相关信息,可变,需要处理数据的增删改
字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改

posted @ 2018-04-12 18:06  云原生运维社区  阅读(129)  评论(0编辑  收藏  举报