2018/3/15

注:2.0版本中只用raw_input()函数

1.让密码密文输入:(只适用于linux和windows命令终端,pycharm中不适用)

import getpass

username = input("用户名:")

password = getpass.getpass("密码:")

print(username,password)


2.保存命令的结果

import os

os.system('df -h')#调用系统shell指令

os.mkdir('yourdir')#新建目录

cmd_res = os.popen("df -h").read()#保存命令的结果而非返回值(执行正确时返回0,错误时非0)

print(cmd_res)


import sys

print(sys.path)#打印出系统环境变量路径


3.猜年龄最终优化

#!/usr/bin/env python
# -*- coding:utf-8 -*-
age = 22
counter = 0
for i in range(10):
    print("-->counter:",counter)
    if counter <3:
        guess_num = int(input("input your guess num:"))
        if guess_num ==age:
            print("Congratulations!You got it!")
            break
        elif guess_num > age:
            print("You need think smaller")
        else:
            print("You need think bigger")
    else:
        continue_confirm = input("Do you want to contiue because you are stupid:")
        if continue_confirm == "y":
            counter = 0
            continue #跳出当次循环,不往下走了
        else:
            print("bye!")
            break

    counter += 1


4.编写登录接口,输入用户名密码,认证成功后显示欢迎界面,输错三次后锁定

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:YanceChan
#作业1:编写登录接口,输入用户名密码,认证成功后显示欢迎界面,输错三次后锁定
username = "bruce"
password = "bruce123"
counter = 0
for i in range(10):
    if counter < 3:
        username_input = input("username:")
        password_input = input("password:")
        if username_input == username and password_input == password:
            print("Welcome to login!")
            break
        else:
            print("Invalid username or password!")
            counter += 1
    else:
        print("Too many attemps! System Locked!")
        break


5.input函数注意事项:

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
name = input("input your name:")
age  = int(input("input your age :"))  # python3.0里input函数默认传递的是字符型
job  = input("input your job :")
msg= """
Information of user %s   # %s,%d,%f用于获取变量值
------------------------------
Name = %s
Age  = %d
Job  = %s
------------------------------
"""%(name,name,age,job)
print(msg)


6.Linux中的tab补全模块

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# python startup file
# tab补全模块
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter
#最后需要设置一下环境变量路径


7.pyc到底是什么   

        auth.py

        test.py中import auth

        执行test.py会生成一个auth.pyc字节码文件和__pycache__文件夹(python2.0版本中),python3.0版本中会把auth.pyc放在__pycache__文件夹中

        .pyc文件是python编译器编译出来的字节码文件,会传递给python解释器


8.字符串用+号拼接输出,占内存、效率低

#!/usr/bin/env python
# -*- coding:utf-8 -*-
name = 'bruce'
print ("i am %s " % name)   #只开辟一块内存空间
print ("my name is " + name + " ,and you ?")    #万恶的+号,开辟了三块内存空间,与上面比,效率低,速度慢

9.列表

       列表(Python中叫列表,其他语言中叫数组):为了一个变量可以存取更多的信息

        列表中取最后一个值时,下标(索引)为-1(倒数第二个索引为-2......)

        如:name = [1,2,3,4,5,6,7,8,'brucelee',100,111,1111,223,124]    

        print(name)

        则name[-1]的值为124

        name[0:1]表示取name[0]的值不取name[1]的值;如果要取列表中的第一二个,则name[0:2](顾首不顾尾)

        name[-3:]表示取倒数第三个到最后一个列表中的元素,即[1111,223,124];同理name[0:3]跟name[:3]值一样的

        name[:9][-1][2]则表示取'brucelee'的第三个字母即‘u’(切断)

        增:name.insert(2,“Alex”)在name[2]位置插入“Alex”元素

        增:name.append("hello")附加、追加一个元素在最后一个位置

        删:name.remove("Alex")删除一个元素(一次只能删除一个)

        删:del 删除,可删除变量、列表等等

        改:name[8]= 'brucelee(groupmaster)' 修改列表元素

        查:name[0:8:3] 后面一个':3'表示步长为3,表示从name[0]到name[7]中隔三个取一个,即[1,4,7,100,223]

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#查找列表中的某个元素,计算这个元素出现的次数,然后把它替换掉
name = [1,2,3,4,5,6,7,8,'brucelee',100,111,1111,3,223,124]
#print(name)
if 3 in name:if 3 in name:#判断数组中是否有3这个元素
   #position_of_ele = name.index(3)#找到元素3的索引,但是只会记录第一个找到的索引,所以使用循环来实现
   # print("[%s] 3 is/are in name"% ele_count)
    for i in range(name.count(3)):#name.count(3)表示对3这个元素进行计数
        ele_index = name.index(3)#name.index(3)表示获得3这个元素的索引
        name[ele_index] = 333333#把列表中的3替换为333333
    print(name)
name.extend(name2)#表示扩展进来一个新的列表,在name列表的元素最后加上name2列表的元素

name.reverse()#表示对name列表元素的顺序进行反转

name.sort()#表示对name列表进行分类排序。(3.0中字符和数字组成的列表不能排序,2.0中可以)

name.pop(i)#表示删除name表的第name[i]个元素,默认为最后一个元素

name.copy()#表示复制name表的全部元素,并且两个表不会有任何影响。但是,如果列表中内嵌列表,那么复制后,再更改内嵌表中的某个元素,则内嵌的列表中的元素就会“同步”。因为复制的只是第一层的数据,而没有复制第二层的内存地址指向的数据。如果要实现复制,且复制后完全独立,则要导入一个标准库import copy(其中copy.copy()相当于做了一个软链接,类似于copy(),)而copy.deepcopy()方法实现深copy,复制后完全独立

len(name)#查看列表的长度

#!/usr/bin/env python

# -*- coding:utf-8 -*-
list = [2,9,1,6,[9,2,9,4,8,7],'bruce4lee',9,25,110,'sm4tp',9,'pop9','onepiece',4]
#查找有几个9,并把它替换成9999
if 9 in list:
    ele_num = list.count(9)
    if ele_num == 1:
        v = "is"
    else:
        v = "are"
    print("[%s] 9 %s in list"%(ele_num,v))
    for i in range(ele_num):
        ele_index = list.index(9)
        list[ele_index] = 9999
    print(list)
else:
    print("There is no 9 in list")


#查找有几个4,并把它删除
if 4 in list:
    ele_num2 = list.count(4)
    if ele_num2 == 1:
        v2 = "is"
    else:
        v2 = "are"
    print("[%s] 4 %s in list"%(ele_num2,v2))
    for i in range(ele_num2):
        list.remove(4)
    print(list)
else:
    print("There is no 4 in list")
print(len(list))


10.字符串

#!/usr/bin/env python
# -*- coding:utf-8 -*-
name = "alex,dragon,goku,luffy"
name2 = name.split(",") #字符串分割,括号里的为分割标准,只能同时有一个标准。分割后的结果为列表
print(name2)

print("|".join(name2)) #字符串合并

print('' in name) #判断字符串有没有空格,有空格返回True,否则False

print(name.capitalize()) #字符串首字母大写

#字符串的格式化形式一
msg = "Hello, {name},{month} monthes time no see ..."
msg2 = msg.format(name='yqchenl',month=6)
print(msg2)
#字符串的格式化形式二
msg3 = "hahaha{0},dddd{1}"
print(msg3.format("Alex",45))

name3 = "bruce lee"
print(name3[2:4]) #字符串切片
print(name3.center(40,'-')) #字符串居中,40为总长度,用‘-’均匀填充
print(name3.find('e')) #查找元素所在的索引位置,有则返回第一个索引位置,没有则返回-1
age = input("your age:")
if age.isdigit(): #判断字符串是否数字类型
    age = int(age)
else:
    print("Invalid data type")

name4 = 'alexsdf'
print(name4.isalnum()) #判断是否有特殊字符,没有则返回True,否则返回-1
print(name4.endswith('sdf')) #判断是否以'sdf'结尾
print(name4.startswith('a1l')) #判断是否以'all'开始
print(name4.upper()) #把字符串全部大写
print(name4.lower()) #把字符串全部小写


11.数据运算

% 取模,常运用于求奇偶数

// 取整除,返回商的整数部分

计算机中能表示的最小单位,是一个二进制位

计算机中能存储的最小单位,是一个二进制位(bit)

异或运算:相同为0不同为1 

左移运算(<<)和右移运算(>>)是二进制算法,比除法要快


12.字典

#!/usr/bin/env python
# -*- coding:utf-8 -*-
id_db = {
    342401199812043423:{
        'name':"luffy",
        'age ':25,
        'addr':"shanghai"
    },
    342103452424323432:{
        'name':"bruce",
        'age ':27,
        'addr':"beijing"
    },
    3421032342424323435:{
        'name':"zoro",
        'age ':24,
        'addr':"onepiece"
    }
}
print(id_db[342103452424323432])
id_db[342103452424323432]['name'] = 'robin' #如果有,则修改该k的值
id_db[342103452424323432]['qq_of_wife'] = 53432545 #添加:如果没有,则创建一个新的
#id_db[342103452424323432].pop('addr')#删除
del id_db[342103452424323432]['addr']#也可以删除
print(id_db[342103452424323432]) #如果字典不存在,则会报错,所以一般选择下一种
print(id_db.get(3421032342424323435) )#返回字典的值,如果字典不存在,则返回None
#id_db.update(dic2)如果dic2中有跟id_db一样的k,则覆盖掉(完全覆盖)
print(id_db.items() ) #字典转换成元组,一般不这样做,很耗时
print(id_db.values()) #返回字典里的values值
print(id_db.keys()) #返回字典里的keys值
# 3421032342424323435 in id_db 判断字典里是否有某个key,适用于python3.0中
# id_db.has_key(3421032342424323435) python2.0里判断字典是否有key
print(id_db.setdefault(342103234242432343543,'hahaha') )  #取一个k,如果不存在,就设置一个默认k、v值
print(id_db)
print(id_db.fromkeys([1,2,3,4,5,6],'dddd'))#把列表里的每个值拿出来当字典里的k,跟id_db没有关系,借用这个字典调用这个方法

#字典的循环,用来返回k,v值
for k,v in id_db.items(): #效率低,因为要有一个dict to list的转换过程,一般用下面那个方法
    print(k,v)

for key in id_db: #效率高
    print(key,id_db[key])
#字典默认是无序的


13.完美购物车小程序

#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''需求:用户启动时先输入工资
用户启动程序后打印商品列表
允许用户选择购买商品
允许用户不断的购买各种商品
购买时检测余额是否够,如果够直接扣款,否则打印余额不足
允许用户主动退出程序,退出时打印已购商品列表
'''
salary = input("Input your salary:")
if salary.isdigit():
    salary = int(salary)
else:
    exit("Invalid data type...")

welcome_msg = 'Welcome to Bruce Shopping mall'.center(56,'-')
print(welcome_msg)
product_list = [
    ('Iphone',5999),
    ('Camaro',520000),
    ('Computer',4500),
    ('Meizu pro7',18.8),
    ('Mac pro',8900)
]

shop_car = []
exit_flag = False#设置flag标识,方便后面跳出循环
while exit_flag is not True:
    #for product_item in product_list:
    #    p_name,p_price = product_item
    print("product list".center(56,'-') )
    for item in enumerate(product_list):#枚举函数,获取列表的索引并返回下标加元素按序组成的元组
        index = item[0]
        p_name = item[1][0]
        p_price = item[1][1]
        print(index,'.',p_name,p_price)

    user_choice = input("[q=quit,c=check]What do you want to buy?:")
    if user_choice.isdigit():#肯定是选择商品
        user_choice = int(user_choice)
        if user_choice < len(product_list):#判断是否是商品清单中的序号
            p_item = product_list[user_choice]
            if p_item[1]<= salary:#买得起
                shop_car.append(p_item)#放入购物车
                salary -= p_item[1]#扣款
                print("Added [%s] into shop car,your current balance is "
                      "\033[31;1m[%s]\033[0m"%(p_item,salary) )#输出的信息加色
            else:
                print("Your balance is [%s], cannot afford this..."%salary)
        else:
            if user_choice == 'q' or user_choice == 'quit':
                print("Purchased products as below".center(40,'*'))
                for item in shop_car:
                    print(item)
                print("END".center(40,'*'))
                print('Your balance is [%s]'%salary)
                print("Bye")
                exit_flag = True#跳出while循环
            elif user_choice == 'c' or user_choice == 'check':
                print("Purchased products as below".center(40,'*'))
                for item in shop_car:
                    print(item)
                print("END".center(40,'*'))
                print('Your balance is \033[41;1m[%s]\033[0m'%salary)#输出的信息加色


14.集合

#!/usr/bin/env python
# -*- coding:utf-8 -*-
s1 = {'bruce',45,(34,12,'onepiece',7888,9090),(1,23,34,12,9090),89}
s2 = {45,89,'bruce',(1,2,3,4)}
# s1.add((12,34,89))#增加一个元素
s1.update('aeiou')#可批量增加元素,其实内部执行了for循环(int型是不可迭代的)
# s1.discard(45)#删除指定的一个元素,如果该元素不存在则不会报错,也不执行任何操作
# s1.pop()#随机删除一个元素
# s1.remove(45)#指定删除一个元素,如果该元素不存在则报错
# s1.clear()#清空集合
# s1.intersection(s2)#s1、s2两个集合的交集
# s1.difference(s2)#s1中有s2中没有的元素组成的集合
# s1.difference_update(s2)#s1中有s2中没有的元素组成的集合直接赋值给s1
# s1.symmetric_difference(s2)#对称差集合,s1中有s2中没有、s1中没有s2中有的元素组成的集合
# s1.symmetric_difference_update(s2)#对称差集合的值直接赋值给s1
# s1.copy()#浅copy
print(s1)
注:集合中不能嵌套列表,而字典中可以


15.lambda表达式

def f1(a1):
    return a1+100
ret = f1(1)
print(ret)


f2 = lambda a1,a2,a3=3:a1+a2+a3+100#lambda表达式,可以看成函数的简写形式
ret2 = f2(1,2)
print(ret2)


16.内置函数

    abs()绝对值

    all() #0,None,"",[],(),{}等的值都为False,除此之外的值为True.所有为真,才为真

    any() #只要有真,就为真

    #ascii() #自动执行对象的_str_方法

    bin() #二进制,0b

    oct() #八进制,0o

    hex() #十进制,0x,进制的转换

    ☆byte(要转换的字符串,编码标准) # 字符串转换字节类型

s = '张三'
n = bytes(s,encoding='utf-8')
print(n)
n2 = bytes(s,encoding='gbk')
print(n2)
    #字节转换成字符串

n3 = str(bytes('张三',encoding='utf-8'),encoding='utf-8')

    文件操作函数

-*- coding:utf-8 -*-
文件操作
1.打开文件
f = open('db','r')#只读
f = open('db','w')#只写,先清空原文件
f = open('db','x')文件存在,报错;不存在,创建并只写
f = open('db','a')追加
f = open('db','wb')#rb,wb,xb,ab表示用字节码
f.write(bytes('路飞',encoding='utf-8'))
# print(data,type(data))
f.close()

f = open('db','r+',encoding='utf-8')# r+表示可读可写
#如果打开模式无b,则read,按照字符读取
data = f.read(1) #read()按照字符标准读取的
print(f.tell()) #获取当前指针所在的位置(永远以字节的标准获取位置)
f.seek(f.tell()) #调整当前指针的位置(永远以字节的标准找位置)
f.write("8888") #当前指针位置开始向后覆盖
f.close()


2.操作文件
f.read() #无参数,表示读取全部
            有b,表示按照字节读取
            无b,表示按照字符读取
f.tell() #获取位置
f.seek() #查找位置
f.write() #b,字节;无b,字符
f.flush() #强刷
f.readline() #仅读取一行
f.truncate(3) #截断,指针之后的全部清除

for line in f:
    print(line)#☆循环文件对象,f=open(xxx),逐行循环读取


3.关闭文件
f.close()

with open ('xb') as f:
    pass  #代码块,代码运行完毕自动进行关闭(2.7及之后才支持同时打开两个文件)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:YanceChan
#内置函数2

# callable()#判断函数是否可调用
# chr()#asscii表里的对应关系,数字转字母
# ord()#asscii表里的对应关系,字母转数字


# 随机生成7位验证码
# import random
# li = []
# for i in range(7):
#     r = random.randrange(0,5)
#     if r ==2 or r ==4:
#         num = random.randrange(0,10)
#         li.append(str(num))
#     else:
#         tmp = random.randrange(65,91) #在括号后面的范围内随机获得,65-90为A-Z的ascii表对应数值
#         c = chr(tmp)
#         li.append(c)
# ret = "".join(li)
# print(ret)

# s = 'print(123)'
# ret = compile(s,'string','exec') #把字符串编译成python的代码,
                                   # single单行python代码、eval表达式代码、exec
# exec(ret) #执行python的代码没有返回值

# s = '7*8'
# ret = eval(s) #将字符串转换成python表达式代码并返回执行结果
# print(ret)

# dir()#快速查看对象都提供了哪些功能
# print(dir(dict))
# help()#查看对象提供的功能详细

# r = divmod(98,9)#常用于分页:共98页,每页需要9条,需要多少页
# print(r[0])#商
# print(r[1])#余数
# #或者用这种表达形式:
# n1,n2 = divmod(100,10)
# print(n1,n2)

# s = 'alex'#字符串'alex'就是一个对象,而它对应的类是str。
#            # 对象是类的实例,对象是具象化、实例化的;类是抽象的
# r = isinstance(s,str)#判断对象s是否是类str的实例
# print(r)

#格式:filter(函数,可迭代的对象),可迭代的对象包括列表、元祖、字典等
# def f2(a):
#     if a>22:
#         return True
# li = [11,22,33,44,55]
# ret = filter(f2,li)#筛选功能:filter内部,li里的每一个元素执行一遍f2,返回结果为True的添加进新的对象中
# print(list(ret))

# f1 = lambda a:a>20
# ret = f1(30)
# print(ret)#返回值为True而不是None,因为lambda自动return函数结果
# 所以上面filter需求可以优化成:
# li = [11,22,33,44,55]
# result = filter(lambda a:a>22, li) #简单的函数就用lambda表达式来实现
# print(list(result))

# map(函数,可迭代的对象(可以for循环的东西)),同filter功能类似
# li = [11,22,33,44,55]
# result = map(lambda a:a+100,li)
# print(list(result))

# filter、map本质的区别
# filter:函数返回True,将元素添加到结果中
#   map: 将函数返回值添加到结果中

# NAME = 'ALEX'
# def show():
#     a = 100
#     c = 230
#     print(locals()) #获得所有的局部变量
#     print(globals()) #获得所有的全局变量,包括python内部提供的
# show()

# hash()#将对象转换成hash值保存下来,一般用于字典的key用hash值来保存

# s = '李小龙'
# print(len(s)) #3.0中默认以字符为单位输出,2.7及前以字节为单位输出
#
# s= '李小龙'
# b = bytes(s,encoding='utf-8')
# print(len(b))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值