Python基础-day01

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础-day01相关的知识,希望对你有一定的参考价值。

写在前面



 

   先后接触过很多编程语言,最喜欢的就是C和Python,相比其他语言,C 是神器,优点太多了;个人而言,C 最重要的一点就是能够让你在敲代码的时候是以一个计算机科学家的角度去思考,而不是仅仅停留在程序表面;

而Python很简单、实用;可以节省很多开发时间,Life is short, use Python.  他的简单之美也符合Unix/Linux 哲学:KISS(Keep It Simple, Stupid.)

  这次来学习不仅仅是想写一些基础的脚本,而是想深入、全面的接触Python,应用到实际工作中; 加油,standby!



 

一、程序语言分类

- C               代码写好之后会经过一个编译的过程,最终生成机器码,然后交给计算机去执行,详细过程参见:C 编译过程浅析

- C 之外的其他程序语言       其他语言在得到机器码之前都会有一个转换的步骤,例如Java:通过Java虚拟机去转换;

                  所以论执行速度,最快的是:   汇编 > C > others

二、Python种类

- CPython            Python的官方版本,C语言实现,CPython实现会将源文件(py文件)转换成字节码文件(pyc文件),然后再转换成机器码让计算机执行(由Python解释器完成)

- PyPy               Python实现的Python,执行速度比CPython快很多,原因是PyPy使用了JIT技术,详见:解释型语言与编译型语言

- 其他Python            JPython、RubyPython...

三、Python解释器

- Python解释器就是一个把Python代码转换成机器码的媒介,类似于Java的JVM以及 UNIX/Linux 里的Bash;

- Python解释器能做什么?

  - 打开Python代码文件,读取文件内容;

  - 对代码进行 词法分析 -> 语法分析;

  - 把源码转换成字节码,再转换成机器码,交给计算机执行

四、关于编码

- ASCII:计算机科学是以英语为母语的前辈们发现推广的,所以最初的编码规范即ASCII码没有考虑到其他语言,用 1个字节/8个位 来表示一个字符,所以最多只能表示 2**8==256个字符;不能表示中文;

- Unicode:随着计算机快速扩展,为了兼容其他语言文字和符号,出现了Unicode/万国码,规定用2个字节/16个位来表示一个字符,对于ASCII码里的字符,将其高位补0;此时,无论是中文汉字还是英文字母都统一视为一个字符,即都视为统一的两个字节存在浪费磁盘空间和带宽流量的问题;

- utf-8:是对Unicode压缩和优化、是一种变长编码,它可以使用1~4个字节表示一个符号,根据不同的符号而变化字节长度,即最小化存储空间的使用和降低带宽传输成本;英文字母由1个字节/8个位表示,中文汉字由3个字节/24个位来表示;

- GB2312:GB2312 是对 ASCII 的中文扩展。中文汉字用2个字节/16个位表示;

- GBK:是对GB2312的补充,增加了繁体字和一些符号;中文汉字用2个字节/16个位表示;

- GB18030:对GBK的扩展,增加了几千个少数民族的字;中文汉字用2个字节/16个位表示;

参考:编码的故事

> 以上数据只是参看网友的解释,还需要实际验证下;


 

- Python编码相关

  - 文件存储编码

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

  - Python解释器编码

    - Python2.x.x 解释器默认编码是 ASCII

    - Python3.x.x 解释器默认编码是 UTF-8

五、Python基础知识

- 文件格式

  - .py  代码文件后缀

  - .pyc  字节码文件后缀

- 变量

  - 由字母、数字、下划线的任意组合

  - 数字不能开头

  - 不能使用Python内置关键字:【‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘exec‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘not‘, ‘or‘, ‘pass‘, ‘print‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘】

  - 建议使用下划线进行分割,例如:user_id,不建议使用驼峰式声明变量;

- 输入

  - 简答明文显示输入:   

1 v = input("Please input your name: ")

  - 密码隐藏输入:     

1 import getpass
2 v = getpass.getpass("Please input your password: ")

- 输出

1 print(v)

- 条件判断

  - 单分支单条件判断

1 WARNING = "包含敏感字符!"
2 WELCOME = "^_^"
3 str = "I figure life is a gift and I don‘t intend on wasting it."
4 if "wastin" in str:
5     print(WARNING)
6 else:
7     print(WELCOME)

  - 单分支多条件判断(condition1 [and|or] conditions2...)

 1 #!/usr/bin/python
 2 # -*- coding:utf-8 -*-
 3 
 4 import getpass
 5 
 6 name = input("请输入用户名:")
 7 pwd = getpass.getpass("请输入密码:")
 8 
 9 if name == alex and pwd == db:
10     print(Welcome, alex!)
11 else:
12     print(You are not authorized, please check your name and passwd.)

  - 多条件判断,由左至右,在没有括号的情况下是没有优先级的

1 if 1 == 1 and 1 > 2 or 1 == 4:
2     print(正确)
3 else:
4     print(错误)

  - 多分支条件匹配

 1 #!/usr/bin/python
 2 # -*- coding:utf-8 -*-
 3 
 4 user_type = input(Input your User Type: )
 5 if admin == user_type:
 6     user_name = input(Input your User Name: )
 7     if alex == user_name:
 8         print(-> admin -> alex...\\t welcome!)
 9     elif mike == user_name:
10         print(-> admin -> mike...\\t welcome!)
11     elif tim == user_name:
12         print(-> admin -> tim...\\t welcome!)
13     else:
14         print(-> admin -> other...\\t welcome!)
15 else:
16     print(You are not admin, bye...)

- while循环

  1.使用while循环输出 1-10,没有7

 1 # First method
 2 i = 0
 3 while True:
 4     i += 1
 5     if 7 == i:
 6         continue
 7     print(i)
 8     if 10 == i:
 9         break
10 
11 # Second method
12 i = 0
13 while i < 10:
14     i += 1
15     if 7 == i:
16         continue
17     print(i)

  2.求1-100的所有数的和

1 i = 1
2 sum = 0
3 while i <101:
4     sum += i
5     i += 1
6 print(sum)

  3.输出 1-100 内的所有奇数

1 i = 0
2 while True:
3     if 1 == i%2:
4         print(i)
5     i += 1
6     if 101 == i:
7         break

  4.求1-2+3-4+5 ... 99的所有数的和

1 i = 0
2 sum = 0
3 while i < 100:
4     if 0 == i%2:
5         sum -= i
6     else:
7         sum += i
8     i += 1
9 print(sum)

- Python数据类型

  - 整数 int

    - 创建

1 a = 1
2 b = int(2)
3 print(type(a),a)
4 print(type(b),b)
5 
6 result:
7 <class int> 1
8 <class int> 2

    - 转换

      - 字符串转整型

1 age = "18"
2 age_int = int(age)
3 print(type(age),age)
4 print(type(age_int),age_int)
5 
6 result:
7 <class str> 18
8 <class int> 18

      - 整型转字符串

1 num = 20
2 num_str = str(num)
3 print(type(num),num)
4 print(type(num_str),num_str)
5 
6 result:
7 <class int> 20
8 <class str> 20

  - 布尔值

    - 创建

1 a = True
2 b = False

    - 转换

      - 数字:    只有0是False,其他均是True

      - 字符串:   只有 "" 是False,其他均是True

      - ...

  - 字符串

    - 创建

1 str1 = "alex"
2 str2  = str("hahaha")
3 print(type(str1),str1)
4 print(type(str2),str2)
5 
6 result:
7 <class str> alex
8 <class str> hahaha

    - 转换见上 【整型转字符串】

    - 字符串的拼接

name = "alex"
sex = "male"
str = name + ", " + sex
print(type(str))
print(str)

result:
<class str>
alex, male

    - 利用占位符把字符串格式化

1 name = input("name: ")
2 age = input("age: ")
3 print("Name: %s, age: %s" % (name, age))
4 
5 result:
6 name: alex
7 age: 18
8 Name: alex, age: 18

    - 判断字符串是否包含某个子序列

1 WARNING = "包含敏感字符!"
2 WELCOME = "^_^"
3 str = "I figure life is a gift and I don‘t intend on wasting it."
4 if "wastin" in str:
5     print(WARNING)
6 else:
7     print(WELCOME)

    - 利用 strip() 移除字符串头尾指定的字符(默认为空格), 【strip | lstrip | rstrip】

1 val = " sex girl    "
2 print(val)
3 print(val.strip())
4 print(val.rstrip())
5 print(val.lstrip())

    - 分割字符串,【split | rsplit】

 1 str = "alex|boy|29|beijing"
 2 print(str.split(|))
 3 print(str.split(|,1))
 4 print(str.split(|,2))
 5 print(str.rsplit(|,1))
 6 
 7 result:
 8 [alex, boy, 29, beijing]
 9 [alex, boy|29|beijing]
10 [alex, boy, 29|beijing]
11 [alex|boy|29, beijing]

    - 字符串长度:len(),按字符计数,而非字节

    - 按照索引取值,可理解为C语言数组

1 str = "life is a gift."
2 print(len(str))
3 print(str[0])
4 print(str[3])

    - 切片

 1 jack = "I figure life is a gift and I don‘t intend on wasting it."
 2 print(jack[24:])
 3 print(jack[0:3])
 4 print(jack[3:6])
 5 print(jack[6:])
 6 print(jack[-5:])
 7 print(jack[10:-7])
 8 print(jack[6::2])
 9 print(jack[6:16:2])
10 
11 result:
12 and I dont intend on wasting it.
13 I f
14 igu
15 re life is a gift and I dont intend on wasting it.
16 g it.
17 ife is a gift and I dont intend on wast
18 r iei  itadIdntitn nwsigi.
19 r iei

  - 列表

    - 创建

1 a = [alex,‘男,eric,123]
2 b = list([alex,‘男,eric,123])

    - in 判断

1 str = "borui"
2 list1  = [borui,漂亮,超可爱,21,beijing]
3 if str in list1:
4     print(str)
5 else:
6     print("No exist.")

    - 索引

1 list1  = [borui,漂亮,超可爱,21,beijing]
2 print("%s: %s" % (list1[0], list1[2]))

    - 长度:len(),列表中元素个数

    - 切片,可参考字符串切片

 1 list1  = [borui,漂亮,超可爱,21,beijing,hahaha,it]
 2 
 3 print(list1[2:])
 4 print(list1[-3])
 5 print(list1[-3:])
 6 print(list1[3:5])
 7 print(list1[4:])
 8 print(list1[0::2])
 9 
10 result:
11 [超可爱, 21, beijing, hahaha, it]
12 beijing
13 [beijing, hahaha, it]
14 [21, beijing]
15 [beijing, hahaha, it]
16 [borui, 超可爱, beijing, it]

    - 追加

1 list1.append(baby)

    - 在指定位置插入

1 list1.insert(1,河南)
2 # 在list1的下标为1的位置插入这个元素

    - 删除

1 del list1[-2]

    - 更新

1 list1[1] = "henan"

    - for 循环输出列表的值

1 list1  = [borui,漂亮,超可爱,21,beijing,hahaha,it]
2 for item in list1:
3     print(item)

  - 字典

    - 创建

1 v = {name:alvn,age:34,tel:15011506666}

    - 按索引取值

1 print(v[tel])

    - 增加元素

1 v[home] = beijing

    - 更改元素

1 v[age] = 100

    - 删除元素

1 # 按照key删除某个元素
2 del v[age]
3 # 清空字典元素
4 v.clear()

    - 长度:len(),字典中元素个数

    - for 循环遍历字典keys、values、items

1 v = {name:alvn,age:34,tel:15011506666}
2 
3 for key in v.keys():
4     print(key)
5 for value in v.values():
6     print(value)
7 for key,value in v.items():
8     print(key,value)

    - 字典可以和列表相互嵌套使用,示例如下,模拟用户登录程序,记录用户登录失败的次数,失败3次则锁定用户:

 1 #!/usr/bin/python
 2 # -*- coding:utf-8 -*-
 3 
 4 import getpass
 5 user_list = [
 6     {name:alex, pwd:123, times:2},
 7     {name:eric, pwd:124, times:0},
 8     {name:tony, pwd:125, times:0},
 9 ]
10 
11 count = 0
12 while count < 3:
13     name = input("Please input your name: ")
14     flag = -1
15     for item in user_list:
16         if item[name] == name:
17             count = 0
18             flag = 1
19             pwd = getpass.getpass("Please input your password: ")
20             if item[pwd] == pwd:
21                 print("Welcome %s." % name)
22                 item[times] = 0
23                 count = 3
24             else:
25                 if 0 == 2-item[times]:
26                     pass
27                 else:
28                     print("Wrong password, you have %s times to retry." % (2-item[times]))
29                 item[times] += 1
30             if item[times] >= 3:
31                 print("You have attempt 3 times which all wrong, so we have to lock your account to keep the security.\\n32 You can contact the admin: [email protected]")
33                 count = 3
34                 break
35     if -1 == flag:
36         print("Invalid account, please check your user name...")
37     count += 1

 六、练习题

  1.元素分类,有集合 v1 = [11,22,33,44,55,66,77,88,99,90],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中;

 1 #!/usr/bin/python
 2 # -*- coding:utf-8 -*-
 3 
 4 v1 = [11,22,33,44,55,66,77,88,99,90]
 5 k1 = []
 6 k2 = []
 7 for i in v1:
 8     if i > 66:
 9         k1.append(i)
10     else:
11         k2.append(i)
12 v2 = {k1:k1, k2:k2}
13 print(v2)

运行结果:

1 D:\\soft\\work\\python35\\python.exe D:/soft/work/Python_17/day01/s07.py
2 {k1: [77, 88, 99, 90], k2: [11, 22, 33, 44, 55, 66]}
3 
4 Process finished with exit code 0

  2.要求用户输入总资产,显示商品列表,让用户根据序号选择商品,加入购物车进行购买;如果商品总额大于总资产,提示账户余额不足,否则,购买成功;需要对用户的无脑输入进行健壮性容错处理;

 1 #!/usr/bin/python
 2 # -*- coding:utf-8 -*-
 3 
 4 goods = [
 5     {"name": "电脑", "price": 1999},
 6     {"name": "鼠标", "price": 10},
 7     {"name": "游艇", "price": 20},
 8     {"name": "美女", "price": 998},
 9 ]
10 while True:
11     mon = input(Please input your money:(n/N to exit): )
12     if mon.isdigit():
13         money = int(mon)
14         break
15     elif n == mon or N == mon:
16         exit(0)
17     else:
18         print("Input money Error, please again!")
19 
20 print("Now we have goods below: \\nNum\\t\\t\\tName\\t\\t\\tPrice")
21 for i in range(0,len(goods)):
22     print("%d\\t\\t\\t%s\\t\\t\\t%s" % (i+1, goods[i][name], goods[i][price]))
23 
24 good_array = {}
25 while True:
26     num = input("What do you need(input the goods num please, n/N to exit.)?\\t\\t")
27     if n == num or N == num:
28         break
29     elif num.isdigit():
30         if int(num) <= len(goods) and int(num) > 0:
31             count = input("How many do you want?\\t\\t")
32             if count.isdigit():
33                 good_array[num] = count
34             else:
35                 print("Input Error, input again!")
36         else:
37             print("Please input Goods‘s num.")
38     else:
39         print("Input Error, input again!")
40 
41 if 0 == len(good_array):
42     print("You don‘t buy anything, bye...")
43     exit(0)
44 sum = 0
45 print("++++++++++++++++++++++++++++++++++++")
46 print("You have choosen goods below: ")
47 print("++++++++++++++++++++++++++++++++++++")
48 for key,value in good_array.items():
49     key_num = int(key)
50     cost = 0
51     if 1 == key_num:
52         cost = goods[key_num-1][price]
53     elif 2 == key_num:
54         cost = goods[key_num-1][price]
55     elif 3 == key_num:
56         cost = goods[key_num-1][price]
57     elif 4 == key_num:
58         cost = goods[key_num-1][price]
59     costs = cost * int(value)
60     print(goods[key_num-1][name] + "\\t\\t\\t" + "*" + "\\t\\t\\t" + value)
61     sum += costs
62 
63 print("++++++++++++++++++++++++++++++++++++")
64 print("++++++++++++++++++++++++++++++++++++")
65 confirm = input("Are you sure to buy them(y/n)?\\t\\t")
66 if "y" == confirm:
67     if money < sum:
68         print("Sorry, your credit is running low...")
69     else:
70         print("The payment has been successfully completed and you have %d$ left." % (money-sum))
71 else:
72     print("Bye...")
73     exit(0)

  3.用户交互,显示省市县三级联动的选择

 1 #!/usr/bin/python
 2 # -*- coding:utf-8 -*-
 3 
 4 zone = {
 5     山东 : {
 6         青岛 : [四方,黄岛,崂山,李沧,城阳],
 7         济南 : [历城,槐荫,高新,长青,章丘],
 8         烟台 : [龙口,莱山,牟平,蓬莱,招远]
 9     },
10     江苏 : {
11         苏州 : [沧浪,相城,平江,吴中,昆山],
12         南京 : [白下,秦淮,浦口,栖霞,江宁],
13         无锡 : [崇安,南长,北塘,锡山,江阴]
14     },
15     浙江 : {
16         杭州 : [西湖,江干,下城,上城,滨江],
17         宁波 : [海曙,江东,江北,镇海,余姚],
18         温州 : [鹿城,龙湾,乐清,瑞安,永嘉]
19     },
20     安徽 : {
21         合肥 : [蜀山,庐阳,包河,经开,新站],
22         芜湖 : [镜湖,鸠江,无为,三山,南陵],
23         蚌埠 : [蚌山,龙子湖,淮上,怀远,固镇]
24     },
25     广东 : {
26         深圳 : [罗湖,福田,南山,宝安,布吉],
27         广州 : [天河,珠海,越秀,白云,黄埔],
28         东莞 : [莞城,长安,虎门,万江,大朗]
29     }
30 }
31 
32 print("===============================")
33 print("Select your location below: ")
34 while True:
35     for key in zone.keys():
36         print(key)
37     print("===============================")
38     province = input("Province: ")
39     if province in zone.keys():
40         citys_dict = zone[province]
41         while True:
42             for key in citys_dict.keys():
43                 print(key)
44             print("===============================")
45             city = input("City: ")
46             if city in citys_dict.keys():
47                 county_list = citys_dict[city]
48                 while True:
49                     for item in county_list:
50                         print(item)
51                     print("===============================")
52                     county = input("County: ")
53                     if county in county_list:
54                         print("Your location is %s -> %s -> %s" % (province, city, county))
55                         break
56                     else:
57                         print("Input County Error, again please...")
58                 break
59             else:
60                 print("Input City Error, again please...")
61         break
62     else:
63         print("Input Province Error, again please...")
64 print("===============================")

七、day01课后作业

 问题描述:基于文件存储的用户登录程序,如果用户连续三次登录失败则锁定用户。

 1 #!/usr/bin/python
 2 # -*- coding:utf-8 -*-
 3 # Description: A login function based on file storage(3 times to try, all failed then lock the user account)
 4 import getpass
 5 
 6 WARNING = "You have attempt 3 times which all wrong, so we have to lock your account to keep the security.\\n\\
 7 You can contact the admin: [email protected]"
 8 # Open the db file and read the content(user info)
 9 f1 = open(D:\\soft\\work\\Python_17\\day01\\db,r)
10 data = f1.read()
11 f1.close()
12 
13 # Format the string to user_infos list which contains the dictionary for everybody.
14 user_info = []
15 # print(data.split(\\n))
16 for item in data.split(\\n):
17     user_dict = {name:item.split(|)[0], pwd:item.split(|)[1], times:int(item.split(|)[2])}
18     user_info.append(user_dict)
19 
20 # User login verification func
21 count = 0
22 while count < 3:
23     name = input("Please input your name: ")
24     flag = -1
25     for item in user_info:
26         if item[name] == name:
27             if item[times] >= 3:
28                 print(WARNING)
29                 exit(0)
30             else:
31                 count = 0
32                 flag = 0
33                 pwd = getpass.getpass("Please input your password: ")
34                 if item[pwd] == pwd:
35                     print("Welcome %s." % name)
36                     item[times] = 0
37                     count = 3
38                 else:
39                     if 0 == 2-item[times]:
40                         pass
41                     else:
42                         print("Wrong password, you have %s times to retry." % (2-item[times]))
43                     item[times] += 1
44                 if item[times] >= 3:
45                     print(WARNING)
46                     count = 3
47                     break
48     if -1 == flag:
49         print("Invalid account, please check your user name...")
50     count += 1
51 
52 # Format the user_infos list to string before write to db file.
53 result = ""
54 for item in user_info:
55     user_info_str = item[name] + "|" + item[pwd] + "|" + str(item[times])
56     result = result + user_info_str + "\\n"
57 
58 # Open the db file and write update the users times.
59 f2 = open(D:\\soft\\work\\Python_17\\day01\\db,w)
60 f2.write(result.strip())
61 f2.close()
db file:

1
alex|123456|3 2 eric|123457|0 3 jack|123458|3 4 tim|123459|0

 

以上是关于Python基础-day01的主要内容,如果未能解决你的问题,请参考以下文章

day01基础部分

day01(pyhon基础)

python基础-day01

Python入门学习 DAY 01 计算机基础

Day01python基础

python 基础day01