首页 > 技术文章 > Python学习之路第二周汇总

source12 2018-09-09 16:20 原文

# Author:Source
#-*-coding:utf-8 -*-
#使用第三方库,import 库名
'''import getpass
password=getpass.getpass('Please input your password:')
print(password)'''
#自己建一个库,要让其生效要放在同一目录,或者放在site-packages(第三方库)。若是在不同目录,需要添加新路径。
'''account=input('input account!'.capitalize())
password=input('import something'.capitalize())'''
#模块初识(os模块)os模块就是对操作系统进行操作
import os
os.system('dir')#打印当前目录名称信息,结果是直接输出到屏幕,不能保存。
cmd_res=os.popen('dir')#内存的对象地址
#os.mkdir('attempt')#创建文件夹
#print(cmd_res.read())
#模块初识(sys模块)
import sys
print(sys.path)#打印环境变量,模块的地址
print(sys.argv)#脚本相对路径 ,取参数
#编译型语言是在程序执行之前,先通过编译器将高级语言转化为机器所能读懂的机器语言。在执行时不需要翻译,直接执行就可以了。
#典型的例子是C语言。解释型语言是在程序执行时解释器逐行对程序进行解释,然后直接运行。python也是一门先编译后解释的语言。
#Python运行过程:python程序运行时先将编译结果保存到位于内存的PyCodeObject,运行结束时python解释器将结果写到pyc文件中。
#下次运行程序时,python程序会先检查硬盘中的pyc文件,否则再重复上面动作。当程序更新时,会检查pyc文件与源程序的更新时间。
#数据类型。整数,长整数是比较大的数字。3.24是浮点数,5.24E-4指的是5.24*10^-4。
#int类型。在32位中-2**32——2**32-1,在64为-2**63——2**63-1。
#long(长整型),在python2.2起没了。
#三元运算
'''number=input('Please input a number:')
if number.isdigit():
    number=int(number)
result = 'adult'.capitalize() if number>=18 else 'nonage'.capitalize()
print(result)'''
#进制转换
#1、二进制转化为十六进制,取四合一法,即从二进制的小数点为分界点,向左(或向右)每四位取成一位。当取到最高位(最低位)如果
#无法凑足四位,就可以在小数点的最左边(或最右边)补0,进行换算。
#十六进制用字母H表示,也可以用0X前缀表示,比如0X。
#十六进制转二进制。方法是一份四,即一个十六进制数分为四个二进制数。
'''number_decimalism=input('Please input a decimalism numeral:')
if number_decimalism.isdigit():
    number_decimalism=int(number_decimalism)
    print('十进制数为:',number_decimalism)
    print('转换为二进制数:',bin(number_decimalism))
    print('转换为八进制数:',oct(number_decimalism))
    print('转换为十六进制:',hex(number_decimalism))
else:
    print('\033[31;1mPlease input legal numeral!\033[0m')'''
#字符串str与二进制bytes转换
#string通过encode变成bytes
conding='s12'.encode('utf-8')
print(conding)
#bytes通过decode编程string
print(conding.decode())
#列表元组操作
#创建列表,列表中的内容用逗号隔离
list=['datou','erbai','sanmao','lisi','wangwu']
#切片操作,顾头不顾尾
print(list)
print(list[2])#切片第三个
print(list[0:2])#切片前两个
print(list[:2])#切片前两个
print(list[1:4])#切片中间三个
print(list[2:5])#切片最后三个
print(list[2:])#切片最后三个
print(list[-1])#切片最右边一个
print(list[-3:])#切片最右边三个
#增添操作
list.append('liuliu')#直接添加
list.insert(1,'erB')#指定位置添加
print(list)
#修改列表值
list[1]='ZhenErB'
print(list)
#删除
list.remove("lisi")
print(list)
del list[1]
print(list)
list.pop(0)
print(list)
#查找
print(list.index("wangwu"))#显示查询数据在列表位置,用列表的下标表示
print(list[list.index("wangwu")])
#统计
print(list.count('liuliu'))
#清空
print(list.clear())
#添加
list.append("jiaren")
print(list)
list.insert(0,'jialing')
print(list)
#反转
list.reverse()
print(list)
#排序,排序规则可能是头字符的类型,一部分特殊字符>数字>另一部分特殊字符>英文>汉语
list.append('12a')
list.append('a2')
list.append('>a1')
list.append('b2')
list.append('&a2')
list.append('2b')
list.append('<s2')
list.append('中文')
list.append('翻译')
list.sort()
print(list)
#反转
fake_list=['wanglaoban',['lidatou','找到我了'],'xiaxiage']
print(list)
print(fake_list)
print(fake_list[1][1])
list.extend(fake_list)
print(list)
#浅COPY
import copy
new_list=['dageda',['xiaobudian','dabudian'],'sanmaoge','zaodiansi','wanglaowu']
shallow1=copy.copy(new_list)#方法一
copy_new_list=new_list.copy()#方法二
shallow2=new_list[:]#方法三
print(copy_new_list)
print(new_list)
copy_new_list[1][1]='改了就一块改'
print(copy_new_list)
print(new_list)
print(shallow1)
print(shallow2)
#深copy
import copy
deep_copy_new_list=copy.deepcopy(new_list)
print(deep_copy_new_list)
print(new_list)
deep_copy_new_list[1][1]='这个时候可以改了'
print(deep_copy_new_list)
print(new_list)
#字符串操作
attempt='gJy121'
print(attempt.capitalize())#将首字母变为大写
print(attempt.casefold())#将大写字母全部变为小写字母
print(attempt.center(50,'.'))#设置一个范围,然后用符号填充剩余的空间
print(attempt.count('g'))#统计字符出现的次数,可以选择开始结束为位置
print(attempt.encode('GB18030'))#指定编码编译
print('gJy121\t gg'.expandtabs(40))#指定空格的长度
print(attempt.endswith('1'))#结束的标志是否是该字符。是则True,错则False
print('My Name is {Name} and my occupation is {occupation}.'.format(Name='GJY',occupation='habitual loafer'))#Methods 1
print('My Name is {0} and my occupation is {1}.'.format('GJY','habitual loafer'))#Methods 2,{}得从0开始
print(attempt.find('2',0,5))#Python find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,
# 则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
print('My Name is {Name} and my occupation is {occupation}.'.format_map({'Name':'GJY','occupation':'habitual loafer'}))
print(attempt.index('g'))#查询目标的第一个下标,不存在会报错
print(attempt.isdigit())#查询是否是数字
print(attempt.isalnum())#检测字符串是否由字母和数字组成。
print(attempt.isalpha())#所有字符都是字母则True
print(attempt.isdecimal())#Python isdecimal() 方法检查字符串是否只包含十进制字符
print(attempt.isidentifier())#检测字符串是否是字母开头
print(attempt.islower())#Python islower() 方法检测字符串是否由小写字母组成。
print(attempt.isnumeric())#Python isnumeric() 方法检测字符串是否只由数字组成。这种方法是只针对unicode对象。
print(attempt.isprintable())#判断是否为可打印字符
print(attempt.isspace())#Python isspace() 方法检测字符串是否只由空格组成。
print(attempt.istitle())#Python istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。
print(attempt.isupper())##Python isupper() 方法检测字符串中所有的字母是否都为大写。
print('+'.join(['24','6','98']))#Python isupper() 方法检测字符串中所有的字母是否都为大写。
print('+'.join('246810'))
print(attempt.ljust(50,'$'))#Python ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字
# 符串的长度则返回原字符串。
print(attempt.rjust(50,'%'))#Python rjust() 方法返回一个原字符串右对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字
# 符串的长度则返回原字符串。
print(attempt.lower())#Python lower() 方法转换字符串中所有大写字符为小写。
print(attempt.swapcase())#swapcase() 方法用于对字符串的大小写字母进行转换。
print('     \nstrip'.lstrip())#Python lstrip() 方法用于截掉字符串左边的空格或指定字符。
print('strip\n        '.rstrip())#Python rstrip() 方法用于截掉字符串右边的空格或指定字符。
print('     \nstrip     \n'.strip())#截断字符串左右两边的空格或指定字符。
#Python maketrans() 方法用于创建字符映射的转换表,对于接受
#两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
plaintext='123456'
encrypt='abcdef'
a=str.maketrans(plaintext,encrypt)
example='852643'
print(example.translate(a))
print('source123'.partition('1'))#partition() 方法用来根据指定的分隔符将字符串进行分割。
#Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
print('source123'.replace('so','re'))
print('heafafaeh'.rfind('h'))#Python rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
print('finally'.rindex('lly'))#Python rindex() 返回子字符串 str 在字符串中最后出现的位置,
# 如果没有匹配的字符串会报异常,你可以指定可选参数[beg:end]设置查找的区间。
print('fadf12sa1'.rpartition('1'))#partition() 方法用来根据指定的分隔符将字符串进行分割。从右向左。
#与partition区别
print('fadf12sa1'.partition('1'))
#Python rsplit() 方法通过指定分隔符对字符串进行分割并返回一个列表,默认分隔符为所有空字符,
#包括空格、换行(\n)、制表符(\t)等。类似于 split() 方法,只不过是从字符串最后面开始分割。
print('faf\tafd\n123 44'.rsplit())
#Python splitlines() 按照行('\r', '\r\n', \n')分隔,
# 返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
print('faf\rafd\n123\r\n44'.splitlines(True))
print('fadf12sa1'.split('1'))#Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串
#与partition的区别:split不包含分割符
#Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,
# 否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。
print(attempt.startswith('gJy'))
print('hello world!'.title())#Python title() 方法返回"标题化"的字符串,就是说所有单词的首个字母转化为大写,其余字母均为小写
print(attempt.upper())#Python upper() 方法将字符串中的小写字母转为大写字母。
print(attempt.zfill(50))#Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0
#字典操作
dictionary={
    'casual1':'number1',
    'casual2':'number2',
    'casual3':'number3',
    'casual4':'number4'
}
print(dictionary)
#查字典
print(dictionary['casual3'])#要去键值要正确
print(dictionary.get('casual2'))
print('casuall' in dictionary)
#改字典
dictionary['casual1']='Yanghuizhen'
dictionary['cannot help but']='yang hui zhen'.title()#不存在则添加
print(dictionary)
#删除
dictionary.pop('cannot help but')
del dictionary['casual4']
print(dictionary)
dictionary.popitem()#重新运行会重新随机删除
print(dictionary)
#多级字典嵌套操作
'''message={
    'Source':{
        'age':['23'],
        'education background':{'Yango University ':['graduate']}
    },
    'Yang':{
        'age':['23'],
        'interset':['To you i know nothing about.']
            }
}
#查字典
print(message.get('Source'))
print(message['Yang']['age'])
print('Source'in message)
#改字典
message['Source']['AGE'.lower()]='24'
message.setdefault('Hero',{
    'age':['20'],
    'significance':['i don not know.'.capitalize()]
})#添加
print(message)'''
print(dictionary)
print(dictionary.values())
print(dictionary.keys())
Reserve={
    'Pengfei':'zui shuai'.capitalize()
}
dictionary.update(Reserve)
print(dictionary,'\n',Reserve)
#items将字典转化为列表
print(dictionary)
print(dictionary.items())
#fromkeys()函数用于创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值。
dictionary2=dict.fromkeys([1,2,3],['a','b','c'])
print(dictionary2)
dictionary2[1][1]='x'
print(dictionary2)
#循环dict
dictionary.items()
for items in dictionary:
    print(items,dictionary[items])
for items,i in dictionary.items():
    print(items,i)
#New shopping:
# Author:Source
file_money=open('money.txt',mode='r')
read_file_moeny=file_money.read()
print('Your balance have:',read_file_moeny)
if read_file_moeny=='' :
    while True:
        salary=input("Please you input your salary:")
        if salary.isdigit():
            salary=int(salary)
            break
        else:
            print('text is not a legal character.'.capitalize())
            continue
else:
    if read_file_moeny.isdigit():
        read_file_moeny=int(read_file_moeny)
        salary=read_file_moeny
    else:
       print("text is not a legal character.".capitalize())
commodity=[
("iphoneX".title(),8388),
("ipad mini4".title(),2400),
("dragon fruit".title(),6),
("alkaline mineral water".title(),2),
("toothpaste".title(),12),
]
shopping_cart=[]
#print(commodity)
while True:
    for item in commodity:
        print(commodity.index(item),item)
    #for i,item in  enumerate(commodity):#python 的for in
     #   print(i,item)
    number=input("Fancy a commodity:")
    if number.isdigit():
        number=int(number)
        print(len(commodity))
        if number<len(commodity) and number>=0:
            list_price=commodity[number]
            if list_price[1] <= salary:
                shopping_cart.append(list_price)
                salary-=list_price[1]
                print("You aleady buy %s and your balance have \033[31;1m%s\033[0m."%(shopping_cart,salary))
            else:
                print("\033[31;1mYour balance is not enough.\033[0m")
                if commodity[3][1]>salary:
                    while True:
                        print('\033[31;1mYou don\' not have much monty.Do you want to increase your savings?\033[0m'.capitalize())
                        Increase=input('Y or N')
                        if Increase=='Y':
                            while True:
                                salary=input('how much money do you want to deposit? '.capitalize())
                                if salary.isdigit():
                                    salary=int(salary)
                                    break
                                else:
                                    print("\033[31;1millegal character.\033[0m".capitalize())
                                    continue
                        elif Increase=='N':
                            break
                        else:
                            continue

        else:
            print("\033[41;1mFollow option\033[0m")
    elif number=='q':
        print("You aleady buy %s and your balance have \033[31;1m%s\033[0m."%(shopping_cart,salary))
        file_money=open('money.txt',mode='w')
        file_money.write(str(salary))
        file_commodity=open('commodity.txt',mode='a')
        file_commodity.write(str(shopping_cart))
        exit()
    else:
        print("\033[31;1mInput error!\033[0m")

  

推荐阅读