首页 > 代码库 > python 笔记

python 笔记

                       第一周2016/9/11

 

Python 2.03.0的区别

3.0 的模块名改了和之前的2.0 不一样

#!/usr/bin/env python

# -*- coding:utf-8 -*-         utf8

>>> user="123"             2.0打印

>>> print user

123

Printuser)               3.0打印

变量

Name=”hanwei”   #姓名

name=”hanwei”    #姓名

注释 #  ‘’’  ‘’’ 

2.0

>>> a=raw_input("your name:")

your name:123

>>> print a

123

 

3.0

>>> a=input("your name:")

your name:123

>>> print a

123

格式化字符串

#!/usr/bin/env python

name=input("your name:")

age=int(input("your age:"))      %d代表小数必须像这样

job=input("your job:")

 

%s 小数或字符串    %f 浮点数   %d 小数

msg=‘‘‘

Name:%s

Age:%d

Job:%s

‘‘‘%(name,age,job)

print(msg) 

ASCI阿克斯码 

Ascl 本身没有加入utf8 加入utf8才有中文

8bi等于一个字节

1024个字节等于1kb

#####################

Ascl 查询 规律

Ab-----69----------ascl

输入密码不显示密码

 

import getpass

username = input("username:")

password = getpass.getpass()

print(username,password)

 

判断次数输入密码

user = "hanwei"
passwd = "789"

username = input("username")
password = input("password")

if user == username:
    print("username is corerct....")
    if password == passwd:
        print("Wlecome login....")
    else:
        print("password is invalid...
else:
    print("no no no") 

判断输入密码器

user = "hanwei"
passwd = "789"
username = input("username:")
password = input("password:")

if username == user and password == passwd:
    print("Welcome login")
else:
    print("mima huo yonghu mong cuowu")

                                

猜数字

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

age = 22
guess_num = int(input("input your guess num:"))  init 转为数字
if guess_num == age:
    print("you git lt")
elif guess_num > age:
    print("da le")
else:
    print("xiaole")

 

猜数字2

age = 22

for i in range(10):

    if i <3:

        guess_num = int(input("input your guess num:"))

        if guess_num == age:

            print("you git lt")

            break

        elif guess_num > age:

            print("da le")

        else:

            print("xiaole")

    else:

        print("cishi taiduo")

        break

 

列表---其他叫做数组

 

定义数组

name=["zhangsan","lisi","wangwu","liu","xie","zhou"]

打印

name[1:3][1][3]

name[1:3]

name[-2:]

name[-1]

name[4]

name[:2]

修改

name[4] = "xietingfeng"

插入

name.insert(4,‘hanwei‘)

删除

name.remove("liu")

打印所有

>>> name

[‘zhangsan‘, ‘lisi‘, ‘wangwu‘, ‘hanwei‘, ‘xietingfeng‘, ‘zhou‘, ‘alix‘]

 

if 9 in name:
    num = name.count(9)  统计9的个数
    pos = name.index(9)  找出索引
    name[pos] = 999      改
  
    print(name)    

 

循环改改所有
name = ["zhangsan","lisi","wangwu","sunliu","liu0",1,1,3,5,4,8,98,9,10,11,9,9,9]
for i in range(name.count(9)): 
    ele = name.index(9)
    name[ele] = 9999999999
    print name

扩展


name = ["zhangsan","lisi","wangwu","sunliu","liu0"]
name2 = ["hanweiu","lini"]

name.extend(name2)
print(name)

打印嵌套

name = ["zhangsan","lisi",["li","a"],"wangwu","sunliu","liu0"]

print name [2][0]

反向排序

name = ["zhangsan","lisi",["li","a"],"wangwu","sunliu","liu0"]
name.reverse()
print name

排序

name = ["zhangsan","lisi",["li","a"],"wangwu","sunliu","liu0"]
name.sort()
print name

考被列表

name = ["zhangsan","lisi",["li","a"],"wangwu","sunliu","liu0"]
name2 = name.copy()
print(name2)

 

删除

name = ["zhangsan","lisi",["li","a"],"wangwu","sunliu","liu0"]
name.pop(2)
print name

 

不长 (比如 1.3.5排序)

name = ["zhangsan","lisi",["li","a"],"wangwu","sunliu","liu0"]

print (name[::2])

删除

name = ["zhangsan","lisi",["li","a"],"wangwu","sunliu","liu0"]
del name[1]
print (name[::2])

完全拷贝

name = ["zhangsan","lisi","wangwu","sunliu","liu0"]

name4 = copy.deepcopy(name)
print(name4)

猜数字2

age = 22
count = 0
for i in range(10):
    if count<3:
        print(count)
        guess_num = int(input("input your guess num:"))
        if guess_num == age:
            print("you git lt")
            break
        elif guess_num > age:
            print("da le")
        else:
            print("xia ole")
    else:
        con = input("hai yao ji xu ma:")
        if con == ‘y‘:
            count = 0
            continue
        else:

            print("exit")
            break
    count += 1

 

字符串处理

name = "alex,jack,rain"

name2 = name.split(",")  转换成列表

print(name2)   

print("|".join(name2)) 换成 |

删掉多余前后空格

username=input("user:")

if username.strip() == ‘alex‘:
    print("welcome")‘‘‘

 

name = "alex li"

 

print(name[2:4])              打印指定字符


print(name.center(40,‘-‘))    打印40不满40 前后加—

print(name.find("li"))        查找

print(‘‘ in name)             查找空格

print(name.capitalize())     第一个字母换成大写

 

变量

msg="Hello, {name}, it‘s been along {age} since last tiem...."
msg2=msg.format(name=‘mimng hu‘,age=‘33‘)
print(msg2)

变量
msg2="hahah {0}, dddd {1}"
print(msg2.format(‘alex‘,‘aa‘))

避免输入的不是数字报错

age = input("your age:")

‘‘‘if age. isdigit():      避免  
    age = int(age) 
else:
    print("nono")‘‘‘

 

name=‘alex3sdf‘
print(name.isalnum())       判断是否是字母或者数字
print(name.endswith(‘f‘))   判断结尾是否是f
print(name.startswith(‘a‘)) 判断开头是否是a
print(name.upper().lower())  大小写转换

 

While 死循环

count=0
while True:

    count+=1
    if count>50 and count<60:   50-60之间退出循环
        continue
    print("你是风儿我是沙")
    print(count)

    if count == 100:
        print("穿上裤子走天涯")
        print(count)
        break

 

字典

id_db = {
     412728199004125331:{
         ‘name‘:"hanwei",
         ‘age‘: 18,
         ‘addr‘:‘henan‘
     },
     41272819900512331: {
         ‘name‘:"shanpao",
         ‘age‘:24,
         ‘addr‘:‘shandong‘
     },
}

#print(id_db[412728199004125331])  打印k值

#id_db[41272819900512331][‘name‘]="minghu" 修改

#del id_db[41272819900512331]          删除


#id_db[41272819900512331].pop("addr")  删除

#v=id_db.get(41272819900512331)  判断是否存在

#v=id_db[41272819900512331]     负值k值

 

 


#print(id_db)
dic2={
    ‘name‘:‘hanhanhan‘,
    222012000:{‘name‘:‘wang‘},
}
#print(dic2)

#id_db.update(dic2)   更新如果只存在覆盖不存在追加
#print(id_db)

#print(id_db) # 打印字典

#print(id_db.items()) 转换成元祖
#print(id_db.values())  打印values

#print(id_db.keys())  打印keys

#41272819900512331 in id_db   判断一个值是否存在

#print(id_db.setdefault(41272819900412533,"hhh"))   判断一个不存在就追加

 


循环字典
for key in id_db:
    print(key,id_db[key])

  

购物车

salary=input("input your salery:")

if salary.isdigit():
    salary=int(salary)
else:
    exit("shu ru cuo wu")

welcom_msg="welcom wo hanwei shopping mall".center(50,-)
print(welcom_msg)

exit_flag = False
product_list=[
    (iphoen,5888),
    (mac air,8000),
    (mac pro,9000),
    (xiaomi 2,19.9),
    (tesla,820000),
    (bike,700),
    (cloth,200),
    (coffee,30),
]

shop_car=[]
while exit_flag is not True:
    print("product list".center(50,-))
    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 your 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,you current balance is \033[31:1m[%s]"
                  %( p_item,salary))
        else:
               print("your balance is [%s], nono.." % salary)
    else:
        if user_choice == q or user_choice == quit:
            print("ni yi tui chu".center(40,*))
            for item in shop_car:
                 print(item)
            print("END".center(40,*))
            print("nide yu ge shi [%s]" % salary)
            print("Bye")
            exit_flag = True
        elif user_choice == c or user_choice == check:
            print("ni yi tui chu".center(40, *))
            for item in shop_car:
                print(item)
            print("END".center(40, *))
            print("nide yu ge shi [%s]" % salary)
            print("Bye")

 

 

Set


s1={11,22,33}
s2={22,33,44}
#s3=s1.difference(s2)   a中存在b中不存在
#s3=s1.symmetric_difference(s2) a中不存在和b中不存在

#s1.difference_update(s2)    a中存在b中不存在跟新到a中

#s3=s1.intersection(s2)  找出a和b相同的   叫做交集

#s1.symmetric_difference_update(s2)   a和b中不存在德跟新到a中

#s1.discard(11)  删除不存在不报错

#s1.remove(22) 删除不存在报错

#s1.pop()      随机删除

#s1.intersection_update(s2)  把a和b相同的更新到a中

#s3=s1.union(s2)  并集

#{33, 22, 11, 44}

添加
#s1.add(99)

#li=[88,66,99]
#s1.update(li)


练习题


old_dict={
    "#1":8,
    "#2":4,
    "#4":2,
}

new_dict={
    "#1":4,
    "#2":4,
    "#3":2,
}

 

拿到keys
new_set=set(new_dict.keys())
old_set=set(old_dict.keys())

remove_set=old_set.difference(new_set)   需要删除的
add_set=new_set.difference(old_set)      需要添加的
update_set=old_set.intersection(new_set) 需要更新的  

 

 

#!/usr/bin/env python

http://www.cnblogs.com/spykids/p/5163108.html
shopping_list = [
    [Iphone 6s plus,5800],
    [Lumia,3800],
    [Charge,45],
    [Data line,35],
    [MI 5 PRO,2299],
    [MI 4,1999],]

salary = 100000

total = 0

shop_list = []

while True:
    welcom_1 = "XXX购物商城欢迎你"
    we_1 = welcom_1.center(30,*)
    print(we_1)

    choice_1 = "1.注册 2.登录 q。退出"
    ch_1 = choice_1.center(30,*)

    exit_1 = "谢谢使用,欢迎下次光临"
    ex_1 = exit_1.center(30,*)

    error_1 = "你输入的用户已存在,请重新输入"
    e_1 = error_1.center(30,*)

    error_2 = "密码不能为空,请重新输入"
    e_2 = error_2.center(30,*)

    error_3 = "输入的密码太短,请重新输入"
    e_3 = error_3.center(30,"*")

    error_4 = "你输入有误,请重新输入"
    e_4 = error_4.center(30,*)

    error_5 = "你的账号已锁定,请联系管理员"
    e_5 = error_5.center(30,*)

    print(ch_1)
    sr_1 = input("Please input:")
    if sr_1 == 1:
        while True:
            with open(ming.txt,r)as r_1:
                temp = r_1.readlines()
                tlist = []

            for tline in temp:
                  tline = tline.strip().split(:)
                  tlist.append(tline[0])
            useradd = input("Please create user:")
            s_1 = 成功创建用户:%s %(useradd)

            if useradd in tlist:
                print(e_1)
            elif useradd == exit:
                break
            else:
                  passwd = input(Please create a password:)
                  lenth = len(passwd)
                  if lenth == 0 :
                      print(e_2)
                  elif lenth > 7:
                      with open(ming.txt,a)as r_3:
                          w_1 = %s:%s:0\n  %(useradd,passwd)
                          r_3.write(w_1)
                          s_1 = s_1.center(30,*)
                          print(s_1)
                          break
                  else:
                      print(e_3)

    elif sr_1 == 2:
        flag = False
        while True:
            username = input("Please enter a  user name:")
            l = open(lock.txt,r)
            for lline in l.readlines():
                lline = lline.strip()
                if username == lline:
                    print("账号已经锁定")
                    flag = True
                    l.close()
                    break
            if flag == True:
                break

            u = open(ming.txt,r)
            for uline in u.readlines():
                user,password,mony = uline.strip().split(:)
                if username == user:
                  i = 0
                  while i < 3:
                    passwd = input(Please enter a password:)
                    i +=1
                    if passwd == password:
                        print(你好欢迎登陆购物平台)
                        flag = True
                        u.close()
                        break
                    else:
                        if i >= 3:
                            with open(lock.txt,a) as l_2:
                                l_2.write(username + \n)
                                l_2.close()
                            exit("错误过多,账号已锁定,请联系管理员")
                        print(密码输入错误,还有%d次机会%(3 - i))
                  break
            else:
                print("用户输入错误,请重新输入")
                break
            while True:

                print("1.购物 2.查看购物车 3.查看余额 4.充值 b.返回 q.退出")
                print("--------------------------------------------------")
                choice_2 = input(请选择)
                flag_1 = False
                while True:
                    if choice_2 == "1":
                        while True:
                            for index,g in enumerate(shopping_list):
                                print(index,g[0],g[1])
                            print(--------------)
                            print(c.查看购物车 b.返回 q.退出)
                            choice = input(请选择商品:).strip()
                            if choice.isdigit():
                                choice = int(choice)
                                p_price = shopping_list[choice][1]
                                if p_price < salary:
                                    shop_list.append(shopping_list[choice])
                                    total += p_price
                                    salary -= p_price
                                    print(------------------)
                                    print(你购买了%s,余额%s%(shopping_list[choice][0],salary))
                                    print(------------------)
                                else:
                                    print(--------------------)
                                    print(余额不足,请充值)
                                    print(--------------------)
                            elif choice == "c":
                                while True:
                                    print(-------你已进入购物车-------)
                                    for k,v in enumerate(shop_list):
                                        print(k,v[0],v[1])
                                        print("已消费金额为:%s"%total)
                                        print("你的余额为:%s"%salary)
                                        print(--------------------------)
                                        print("d.删除商品,b.返回 q.退出")
                                        print(--------------------------)
                                        choce_1 = input(请选择)
                                        print(--------------------------)
                                        if choce_1 == d:
                                            print(-------------------------)
                                            print(选择要删除的商品 b.返回购物车:)
                                            print(-------------------------)
                                            while True:
                                                choice_2 = input(请选择:)
                                                if choice_2.isdigit():
                                                    choice_2 = int(choice_2)
                                                    d_price = shop_list[choice_2][1]
                                                    shop_list.remove(shop_list[choice_2])
                                                    total -= d_price
                                                    salary += d_price
                                                    print(----------------)
                                                    print("商品%s删除成功,余额为%s"%(shop_list[choice_2][0],salary))
                                                    print(-----------------)
                                                elif choice_2 == b:
                                                    break
                                        elif choice_1 == b:
                                            flag = True
                                            break
                                        else:
                                            print(-----购物清单------)
                                            for k,v in enumerate(shop_list):
                                                print(k,v[0],v[1])
                                                print(总消费金额为:%s%total)
                                                print(你的可用余额:%s%salary)
                                                print(-----欢迎下次再来-----)
                                                exit(0)
                            elif choice == "b":
                                break
                            elif choice == q:
                                print(------购物清单------)
                                for k,v in enumerate(shop_list):
                                    print(k,v[0],v[1])
                                print(消费金额为:%s%total)
                                print(你的可用余额为:%s%salary)
                                print(------欢迎再次光临------)
                                exit(0)
                            else:
                                print(----------------)
                                print(你输入错误,请重新输入!)
                                print(-------------------)
                        if flag == True:
                            break
                    elif choice_2 == 2:
                        print(-----购物车-------)
                        for k,v in enumerate(shop_list):
                            print(k,v[0],v[1])
                        print(已消费金额为:%s%total)
                        print(你的余额为:%s%salary)
                        print(--------------------)
                        break
                    elif choice_2 == 3:
                        with open(ming.txt,r)as m_1:
                            mony_1 = m_1.readlines()
                        for mline in mony_1:
                            (user,password,mony) = mline.strip().split(:)
                            print(salary)
                            flag_1 = True
                            break
                        break
                    elif choice_2 == 4:
                        z = 0
                        while z < 1:
                            chongzhi = int(input(输入金额:))
                            passwd_1 = input(输入密码:)
                            m = open(ming.txt,r+)
                            m_2 = m.readlines()
                            for mline in m_2:
                                (user,password,mony) = mline.strip().split(:)
                                if passwd_1 == password:
                                    mony_2 = (chongzhi + int(mony))
                                    w_2 = %s:%s:%s%(username,password,mony_2)
                                    m.write(w_2)
                                    print(充值成功)
                                    print(mony)
                                    flag = True
                                    break
                                continue
                            break
                        if flag == True:
                            break
                    elif choice_2 == b:
                        flag = True
                        break
                    elif choice_2 == q:
                        exit(ex_1)
                    else:
                        print(e_4)
                        break
                    break
                if flag == True:
                    break
            break
    elif sr_1 == q:
        exit(ex_1)
    else:
        print(e_4)
        print(--------------------------------)

 

三级菜单

http://www.2cto.com/kf/201512/453371.html

 1 import re
 2 memu = {
 3     东北:{
 4         吉林省:{
 5             吉林市:[吉林市1,吉林市2],
 6             长春:[长春1,长春2],
 7         },
 8         辽宁省:{
 9             沈阳:[沈阳1,沈阳2],
10             大连:[大连1,大连2],
11 
12         },
13     },
14     华北:{
15         河北:{
16             廊坊:[廊坊1,廊坊2],
17             保定:[保定1,保定2],
18         },
19         内蒙古:{
20             呼和浩特:[呼和浩特1,呼和浩特2],
21             包头:[包头1,包头2]
22         },
23     },
24 }
25 
26 flag = True
27 while flag:
28     for i,v in enumerate(memu.keys()):
29         print(i,v)
30     num_1 = input(请输入一级菜单号 q.退出:)
31     if num_1 == q:
32         flag = True
33         break
34     if num_1.isdigit():
35         num_1 = int(num_1)
36         if num_1 <= len(memu):
37             key_1 = list(memu.keys())[num_1]
38             while flag:
39                 for i1,v1 in enumerate(memu[key_1]):
40                     print(i1,v1)
41                 num_2 = input(请输入二级菜单号 q.退出 b.返回:)
42                 if num_2 == q:
43                     flag = False
44                     break
45                 if num_2 == b:
46                     break
47                 if num_2.isdigit():
48                     num_2 = int(num_2)
49                     if num_2 <= len(memu[key_1]):
50                         key_2 = list(memu[key_1].keys())[num_2]
51                         while flag:
52                             for i2,v2 in enumerate(memu[key_1][key_2]):
53                                 print(i2,v2)
54                             num_3 = input(请输入三级菜单号 q.退出 b.返回:)
55                             if num_3 == q:
56                                 flas = False
57                                 break
58                             if num_3 == b:
59                                 break
60                             if num_3.isdigit():
61                                 num_3 = int(num_3)
62                                 if num_3 <= len(memu[key_1][key_2]):
63                                     key_3 = list(memu[key_1][key_2].keys())[num_3]
64                                     while flag:
65                                         print(最后一页!)
66                                         for i3,v3 in enumerate(memu[key_1][key_2][key_3]):
67                                             print(i3,v3)
68                                         num_4 = input(q.退出 b.返回:)
69                                         if num_4 == q:
70                                             flag = False
71                                             break
72                                         if num_4 == b:
73                                             break 

购物车
http://www.cnblogs.com/spykids/p/5163108.html 

python 笔记