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个位表示;

参考:编码的故事

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

  - 实验1

 #!/usr/bin/python
# -*- coding:utf-8 -*- str = "中" print(str.encode('utf-8'))
print(str.encode('GBK'))
print(str.encode('GB2312'))
print(str.encode('GB18030')) result:
D:\soft\work\python35\python.exe D:/soft/work/Python_17/day01/s10.py
b'\xe4\xb8\xad'
b'\xd6\xd0'
b'\xd6\xd0'
b'\xd6\xd0' Process finished with exit code 0

  - 实验2

 #!/usr/bin/python
# -*- coding:utf-8 -*- china = "中国"
utf8_china = china.encode('utf-8')
gbk_china = china.encode('GBK')
print("Type is %s; \tcontent is %s; \t\tlength is \t%s" % (type(utf8_china), utf8_china, len(utf8_china)))
print("Type is %s; \tcontent is %s; \t\tlength is \t%s" % (type(gbk_china), gbk_china, len(gbk_china))) result:
Type is <class 'bytes'>; content is b'\xe4\xb8\xad\xe5\x9b\xbd'; length is 6
Type is <class 'bytes'>; content is b'\xd6\xd0\xb9\xfa'; length is 4

参考:http://blog.csdn.net/foryouslgme/article/details/54948394

参考:http://www.cnblogs.com/chenwolong/p/6497514.html

- Python编码相关

  - 文件存储编码

 #!/usr/bin/python
# -*- 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,不建议使用驼峰式声明变量;

- 输入

  - 简答明文显示输入:   

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

  - 密码隐藏输入:    

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

- 输出

 print(v)

- 条件判断

  - 单分支单条件判断

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

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

 #!/usr/bin/python
# -*- coding:utf-8 -*- import getpass name = input("请输入用户名:")
pwd = getpass.getpass("请输入密码:") if name == 'alex' and pwd == 'db':
print('Welcome, alex!')
else:
print('You are not authorized, please check your name and passwd.')

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

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

  - 多分支条件匹配

 #!/usr/bin/python
# -*- coding:utf-8 -*- user_type = input('Input your User Type: ')
if 'admin' == user_type:
user_name = input('Input your User Name: ')
if 'alex' == user_name:
print('-> admin -> alex...\t welcome!')
elif 'mike' == user_name:
print('-> admin -> mike...\t welcome!')
elif 'tim' == user_name:
print('-> admin -> tim...\t welcome!')
else:
print('-> admin -> other...\t welcome!')
else:
print('You are not admin, bye...')

- while循环

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

 # First method
i = 0
while True:
i += 1
if 7 == i:
continue
print(i)
if 10 == i:
break # Second method
i = 0
while i < 10:
i += 1
if 7 == i:
continue
print(i)

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

 i = 1
sum = 0
while i <101:
sum += i
i += 1
print(sum)

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

 i = 0
while True:
if 1 == i%2:
print(i)
i += 1
if 101 == i:
break

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

 i = 0
sum = 0
while i < 100:
if 0 == i%2:
sum -= i
else:
sum += i
i += 1
print(sum)

- Python数据类型

  - 整数 int

    - 创建

 a = 1
b = int(2)
print(type(a),a)
print(type(b),b) result:
<class 'int'> 1
<class 'int'> 2

    - 转换

      - 字符串转整型

 age = ""
age_int = int(age)
print(type(age),age)
print(type(age_int),age_int) result:
<class 'str'> 18
<class 'int'> 18

      - 整型转字符串

 num = 20
num_str = str(num)
print(type(num),num)
print(type(num_str),num_str) result:
<class 'int'> 20
<class 'str'> 20

  - 布尔值

    - 创建

 a = True
b = False

    - 转换

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

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

      - ...

  - 字符串

    - 创建

 str1 = "alex"
str2 = str("hahaha")
print(type(str1),str1)
print(type(str2),str2) result:
<class 'str'> alex
<class 'str'> hahaha

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

    - 字符串的拼接

name = "alex"
sex = "male"
str = name + ", " + sex
print(type(str))
print(str) result:
<class 'str'>
alex, male

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

 name = input("name: ")
age = input("age: ")
print("Name: %s, age: %s" % (name, age)) result:
name: alex
age: 18
Name: alex, age: 18

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

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

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

 val = " sex girl    "
print(val)
print(val.strip())
print(val.rstrip())
print(val.lstrip())

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

 str = "alex|boy|29|beijing"
print(str.split('|'))
print(str.split('|',1))
print(str.split('|',2))
print(str.rsplit('|',1)) result:
['alex', 'boy', '', 'beijing']
['alex', 'boy|29|beijing']
['alex', 'boy', '29|beijing']
['alex|boy|29', 'beijing']

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

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

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

    - 切片

 jack = "I figure life is a gift and I don't intend on wasting it."
print(jack[24:])
print(jack[0:3])
print(jack[3:6])
print(jack[6:])
print(jack[-5:])
print(jack[10:-7])
print(jack[6::2])
print(jack[6:16:2]) result:
and I don't intend on wasting it.
I f
igu
re life is a gift and I don't intend on wasting it.
g it.
ife is a gift and I don't intend on wast
r iei itadIdntitn nwsigi.
r iei

  - 列表

    - 创建

 a = ['alex','男','eric',123]
b = list(['alex','男','eric',123])

    - in 判断

 str = "borui"
list1 = ['borui','漂亮','超可爱','','beijing']
if str in list1:
print(str)
else:
print("No exist.")

    - 索引

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

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

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

 list1  = ['borui','漂亮','超可爱','','beijing','hahaha','it']

 print(list1[2:])
print(list1[-3])
print(list1[-3:])
print(list1[3:5])
print(list1[4:])
print(list1[0::2]) result:
['超可爱', '', 'beijing', 'hahaha', 'it']
beijing
['beijing', 'hahaha', 'it']
['', 'beijing']
['beijing', 'hahaha', 'it']
['borui', '超可爱', 'beijing', 'it']

    - 追加

 list1.append('baby')

    - 在指定位置插入

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

    - 删除

 del list1[-2]

    - 更新

 list1[1] = "henan"

    - for 循环输出列表的值

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

  - 字典

    - 创建

 v = {'name':'alvn','age':'','tel':''}

    - 按索引取值

 print(v['tel'])

    - 增加元素

 v['home'] = 'beijing'

    - 更改元素

 v['age'] = 100

    - 删除元素

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

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

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

 v = {'name':'alvn','age':'','tel':''}

 for key in v.keys():
print(key)
for value in v.values():
print(value)
for key,value in v.items():
print(key,value)

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

 #!/usr/bin/python
# -*- coding:utf-8 -*- import getpass
user_list = [
{'name':'alex', 'pwd':'', 'times':2},
{'name':'eric', 'pwd':'', 'times':0},
{'name':'tony', 'pwd':'', 'times':0},
] count = 0
while count < 3:
name = input("Please input your name: ")
flag = -1
for item in user_list:
if item['name'] == name:
count = 0
flag = 1
pwd = getpass.getpass("Please input your password: ")
if item['pwd'] == pwd:
print("Welcome %s." % name)
item['times'] = 0
count = 3
else:
if 0 == 2-item['times']:
pass
else:
print("Wrong password, you have %s times to retry." % (2-item['times']))
item['times'] += 1
if item['times'] >= 3:
print("You have attempt 3 times which all wrong, so we have to lock your account to keep the security.\n\
You can contact the admin: admin@standby.pub")
count = 3
break
if -1 == flag:
print("Invalid account, please check your user name...")
count += 1

六、练习题

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

 #!/usr/bin/python
# -*- coding:utf-8 -*- v1 = [11,22,33,44,55,66,77,88,99,90]
k1 = []
k2 = []
for i in v1:
if i > 66:
k1.append(i)
else:
k2.append(i)
v2 = {'k1':k1, 'k2':k2}
print(v2)

运行结果:

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

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

 #!/usr/bin/python
# -*- coding:utf-8 -*- goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
while True:
mon = input('Please input your money:(n/N to exit): ')
if mon.isdigit():
money = int(mon)
break
elif 'n' == mon or 'N' == mon:
exit(0)
else:
print("Input money Error, please again!") print("Now we have goods below: \nNum\t\t\tName\t\t\tPrice")
for i in range(0,len(goods)):
print("%d\t\t\t%s\t\t\t%s" % (i+1, goods[i]['name'], goods[i]['price'])) good_array = {}
while True:
num = input("What do you need(input the goods num please, n/N to exit.)?\t\t")
if 'n' == num or 'N' == num:
break
elif num.isdigit():
if int(num) <= len(goods) and int(num) > 0:
count = input("How many do you want?\t\t")
if count.isdigit():
good_array[num] = count
else:
print("Input Error, input again!")
else:
print("Please input Goods's num.")
else:
print("Input Error, input again!") if 0 == len(good_array):
print("You don't buy anything, bye...")
exit(0)
sum = 0
print("++++++++++++++++++++++++++++++++++++")
print("You have choosen goods below: ")
print("++++++++++++++++++++++++++++++++++++")
for key,value in good_array.items():
key_num = int(key)
cost = 0
if 1 == key_num:
cost = goods[key_num-1]['price']
elif 2 == key_num:
cost = goods[key_num-1]['price']
elif 3 == key_num:
cost = goods[key_num-1]['price']
elif 4 == key_num:
cost = goods[key_num-1]['price']
costs = cost * int(value)
print(goods[key_num-1]['name'] + "\t\t\t" + "*" + "\t\t\t" + value)
sum += costs print("++++++++++++++++++++++++++++++++++++")
print("++++++++++++++++++++++++++++++++++++")
confirm = input("Are you sure to buy them(y/n)?\t\t")
if "y" == confirm:
if money < sum:
print("Sorry, your credit is running low...")
else:
print("The payment has been successfully completed and you have %d$ left." % (money-sum))
else:
print("Bye...")
exit(0)

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

 #!/usr/bin/python
# -*- coding:utf-8 -*- zone = {
'山东' : {
'青岛' : ['四方','黄岛','崂山','李沧','城阳'],
'济南' : ['历城','槐荫','高新','长青','章丘'],
'烟台' : ['龙口','莱山','牟平','蓬莱','招远']
},
'江苏' : {
'苏州' : ['沧浪','相城','平江','吴中','昆山'],
'南京' : ['白下','秦淮','浦口','栖霞','江宁'],
'无锡' : ['崇安','南长','北塘','锡山','江阴']
},
'浙江' : {
'杭州' : ['西湖','江干','下城','上城','滨江'],
'宁波' : ['海曙','江东','江北','镇海','余姚'],
'温州' : ['鹿城','龙湾','乐清','瑞安','永嘉']
},
'安徽' : {
'合肥' : ['蜀山','庐阳','包河','经开','新站'],
'芜湖' : ['镜湖','鸠江','无为','三山','南陵'],
'蚌埠' : ['蚌山','龙子湖','淮上','怀远','固镇']
},
'广东' : {
'深圳' : ['罗湖','福田','南山','宝安','布吉'],
'广州' : ['天河','珠海','越秀','白云','黄埔'],
'东莞' : ['莞城','长安','虎门','万江','大朗']
}
} print("===============================")
print("Select your location below: ")
while True:
for key in zone.keys():
print(key)
print("===============================")
province = input("Province: ")
if province in zone.keys():
citys_dict = zone[province]
while True:
for key in citys_dict.keys():
print(key)
print("===============================")
city = input("City: ")
if city in citys_dict.keys():
county_list = citys_dict[city]
while True:
for item in county_list:
print(item)
print("===============================")
county = input("County: ")
if county in county_list:
print("Your location is %s -> %s -> %s" % (province, city, county))
break
else:
print("Input County Error, again please...")
break
else:
print("Input City Error, again please...")
break
else:
print("Input Province Error, again please...")
print("===============================")

七、day01课后作业

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

 #!/usr/bin/python
# -*- coding:utf- -*-
# Description: A login function based on file storage( times to try, all failed then lock the user account)
import getpass WARNING = "You have attempt 3 times which all wrong, so we have to lock your account to keep the security.\n\
You can contact the admin: admin@standby.pub"
# Open the db file and read the content(user info)
f1 = open('D:\soft\work\Python_17\day01\db','r')
data = f1.read()
f1.close() # Format the string to user_info's list which contains the dictionary for everybody.
user_info = []
# print(data.split('\n'))
for item in data.split('\n'):
user_dict = {'name':item.split('|')[], 'pwd':item.split('|')[], 'times':int(item.split('|')[])}
user_info.append(user_dict) # User login verification func
count =
while count < :
name = input("Please input your name: ")
flag = -
for item in user_info:
if item['name'] == name:
if item['times'] >= :
print(WARNING)
exit()
else:
count =
flag =
pwd = getpass.getpass("Please input your password: ")
if item['pwd'] == pwd:
print("Welcome %s." % name)
item['times'] =
count =
else:
if == -item['times']:
pass
else:
print("Wrong password, you have %s times to retry." % (-item['times']))
item['times'] +=
if item['times'] >= :
print(WARNING)
count =
break
if - == flag:
print("Invalid account, please check your user name...")
count += # Format the user_info's list to string before write to db file.
result = ""
for item in user_info:
user_info_str = item['name'] + "|" + item['pwd'] + "|" + str(item['times'])
result = result + user_info_str + "\n" # Open the db file and write update the user's times.
f2 = open('D:\soft\work\Python_17\day01\db','w')
f2.write(result.strip())
f2.close()
db file:

1 alex||
eric||
jack||
tim||
上一篇:JS 读取本地Excel文件


下一篇:iOS学习笔记---oc语言第九天