PythonDay01

时间:2023-03-10 00:03:11
PythonDay01

》注释

  》》当行注视:# 被注释内容

  》》多行注释:""" 被注释内容 """

》执行脚本传入参数

  》》Python有大量的模块,从而使得开发Python程序非常简洁。类库有包括三中:

    》》》Python内部提供的模块

    》》》业内开源的模块

    》》》程序员自己开发的模块

  》》Python内部提供一个 sys 的模块,其中的 sys.argv 用来捕获执行执行python脚本时传入的参数

import sys

print(sys.argv)

》pyc 文件

  》》执行Python代码时,如果导入了其他的 .py 文件,那么,执行过程中会自动生成一个与其同名的 .pyc 文件,该文件就是Python解释器编译之后产生的字节码。

  》》ps:代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。

  》》python语言的执行:代码编译得到字节码 ,虚拟机执行字节码并转换成机器码再后在处理器上执行

》变量

  》》声明一个变量,变量名为: name,变量name的值为:"fury"

name = "fury"

  》》 变量的作用:昵称,其代指内存里某个地址中保存的内容

  》》变量定义的规则:

    》》》变量名只能是 字母、数字或下划线的任意组合

    》》》变量名的第一个字符不能是数字

    》》》以下关键字不能声明为变量名

      ['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']

》变量的赋值

  》》Python中变量的赋值同Java中字符串的操作差不多(详见Java字符串操作之常量池)

name1 = 'fury'
name2 = 'fury' #同一个字符串可以被不同的变量引用 #name2 = name1 也是同样的效果
id1 = id(name1) #通过内置函数id()来读取变量的内存地址
id2 = id(name2)
print(id1, id2)
name2 = "warrior" #改变name2的值时name2的地址也变了,但是name1的值和地址都没有变
print(name1, name2)
id1 = id(name1) #通过内置函数id()来读取变量的内存地址
id2 = id(name2)
print(id1, id2)
# PS: Python中字符串的赋值操作跟Java中的差不多 # x1 = 2
# x2 = x1
# id1 = id(x1)
# id2 = id(x2)
# print(x1, x2)
# print(id1, id2)
#
# x2 = 12343
# print(x1, x2)
# id1 = id(x1)
# id2 = id(x2)
# print(id1, id2)

》补充

  》#print "hello"            python2.x的print方法

  》#python2.x不支持中文,如果有中文,需要添加 #_*_coding:utf-8_*_

  在程序最开始指定解释器和编码规则

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

》输入

  在3.0中input输入的默认都是字符串形式

name = input("Please input your name: ")
print(name)
# print(input("Please input your name: ")) #上面两行的优化版本
# 在3.0中input输入的默认都是字符串形式 name = input("Please input your name: ")
age = int(input("Please input your age: ")) #convet string to int
salary = float(input("Please input your salary: "))
print("name:", name)
print("age:", age)
print("slary", salary) msg = """
=====start=====
Information of %s :
name : %s
age : %d
salary : %f
======end=======
""" %(name, name, age, salary)
print(msg)

》流程控制和缩进

  》》需求一:   

  # 提示输入用户名和密码
  # 验证用户名和密码
  # 如果错误,则输出用户名或密码错误
  # 如果成功,则输出 欢迎,XXX!
name = input("Please input your name: ")
passwords = input("Please input your passwords: ")
if name == "fury" and passwords == 123:
print("登录成功")
else:
print("用户名或者密码错误")

  》》需求二

    根据用户输入内容输出其权限

name = input("Please input your name: ")
passwords = input("Please input your passwords: ")
index = input("Please input you ID: ")
if index.isdigit():
index = int(index)
if passwords.isdigit():
passwords = int(passwords)
if name == "fury" and passwords == 123:
print("登录成功")
if index == 1:
print("你是博士")
elif index == 2:
print("你是硕士")
elif index == 3:
print("你是本科生")
else:
print("你是中学生")
else:
print("用户名或者密码错误")

》局部变量 VS 全局变量

  外层变量,可以被内层变量使用
  内层变量,无法被外层变量使用
  》》当局部变量和全局变量冲突时,以局部变量为准
 name = "fury"

 def test():
name = "warrior"
print("test函数:", name) def main():
test()
print("main函数", name) main()

  》》当想要在局部对全局变量进行修改是需要用到 global 关键字

 name = "fury"

 def test():
global name
name = "hello word"
print("test函数:", name) def main():
test()
print("main函数", name) main()

》初识基本数据类型

1、数字

2 是一个整数的例子。
长整数 不过是大一些的整数。
3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
(-5+4j)和(2.3-4.6j)是复数的例子。

int(整型)

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
 class int(object):
"""
int(x=0) -> int or long
int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
"""
def bit_length(self):
""" 返回表示该数字的时占用的最少位数 """
"""
int.bit_length() -> int Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
"""
return 0 def conjugate(self, *args, **kwargs): # real signature unknown
""" 返回该复数的共轭复数 """
""" Returns self, the complex conjugate of any int. """
pass
#两个实部相等,虚部互为相反数的复数互为共轭复数(conjugate #complex number)
def __abs__(self):
""" 返回绝对值 """
""" x.__abs__() <==> abs(x) """
pass def __add__(self, y):
""" x.__add__(y) <==> x+y """
pass def __and__(self, y):
""" x.__and__(y) <==> x&y """
pass def __cmp__(self, y):
""" 比较两个数大小 """
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __coerce__(self, y):
""" 强制生成一个元组 """
""" x.__coerce__(y) <==> coerce(x, y) """
pass def __divmod__(self, y):
""" 相除,得到商和余数组成的元组 """
""" x.__divmod__(y) <==> divmod(x, y) """
pass def __div__(self, y):
""" x.__div__(y) <==> x/y """
pass def __float__(self):
""" 转换为浮点类型 """
""" x.__float__() <==> float(x) """
pass def __floordiv__(self, y):
""" x.__floordiv__(y) <==> x//y """
pass def __format__(self, *args, **kwargs): # real signature unknown
pass def __getattribute__(self, name):
""" x.__getattribute__('name') <==> x.name """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
""" 内部调用 __new__方法或创建对象时传入参数使用 """
pass def __hash__(self):
"""如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
""" x.__hash__() <==> hash(x) """
pass def __hex__(self):
""" 返回当前数的 十六进制 表示 """
""" x.__hex__() <==> hex(x) """
pass def __index__(self):
""" 用于切片,数字无意义 """
""" x[y:z] <==> x[y.__index__():z.__index__()] """
pass def __init__(self, x, base=10): # known special case of int.__init__
""" 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
"""
int(x=0) -> int or long
int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
# (copied from class doc)
"""
pass def __int__(self):
""" 转换为整数 """
""" x.__int__() <==> int(x) """
pass def __invert__(self):
""" x.__invert__() <==> ~x """
pass def __long__(self):
""" 转换为长整数 """
""" x.__long__() <==> long(x) """
pass def __lshift__(self, y):
""" x.__lshift__(y) <==> x<<y """
pass def __mod__(self, y):
""" x.__mod__(y) <==> x%y """
pass def __mul__(self, y):
""" x.__mul__(y) <==> x*y """
pass def __neg__(self):
""" x.__neg__() <==> -x """
pass @staticmethod # known case of __new__
def __new__(S, *more):
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __nonzero__(self):
""" x.__nonzero__() <==> x != 0 """
pass def __oct__(self):
""" 返回改值的 八进制 表示 """
""" x.__oct__() <==> oct(x) """
pass def __or__(self, y):
""" x.__or__(y) <==> x|y """
pass def __pos__(self):
""" x.__pos__() <==> +x """
pass def __pow__(self, y, z=None):
""" 幂,次方 """
""" x.__pow__(y[, z]) <==> pow(x, y[, z]) """
pass def __radd__(self, y):
""" x.__radd__(y) <==> y+x """
pass def __rand__(self, y):
""" x.__rand__(y) <==> y&x """
pass def __rdivmod__(self, y):
""" x.__rdivmod__(y) <==> divmod(y, x) """
pass def __rdiv__(self, y):
""" x.__rdiv__(y) <==> y/x """
pass def __repr__(self):
"""转化为解释器可读取的形式 """
""" x.__repr__() <==> repr(x) """
pass def __str__(self):
"""转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
""" x.__str__() <==> str(x) """
pass def __rfloordiv__(self, y):
""" x.__rfloordiv__(y) <==> y//x """
pass def __rlshift__(self, y):
""" x.__rlshift__(y) <==> y<<x """
pass def __rmod__(self, y):
""" x.__rmod__(y) <==> y%x """
pass def __rmul__(self, y):
""" x.__rmul__(y) <==> y*x """
pass def __ror__(self, y):
""" x.__ror__(y) <==> y|x """
pass def __rpow__(self, x, z=None):
""" y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
pass def __rrshift__(self, y):
""" x.__rrshift__(y) <==> y>>x """
pass def __rshift__(self, y):
""" x.__rshift__(y) <==> x>>y """
pass def __rsub__(self, y):
""" x.__rsub__(y) <==> y-x """
pass def __rtruediv__(self, y):
""" x.__rtruediv__(y) <==> y/x """
pass def __rxor__(self, y):
""" x.__rxor__(y) <==> y^x """
pass def __sub__(self, y):
""" x.__sub__(y) <==> x-y """
pass def __truediv__(self, y):
""" x.__truediv__(y) <==> x/y """
pass def __trunc__(self, *args, **kwargs):
""" 返回数值被截取为整形的值,在整形中无意义 """
pass def __xor__(self, y):
""" x.__xor__(y) <==> x^y """
pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分母 = 1 """
"""the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 虚数,无意义 """
"""the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 分子 = 数字大小 """
"""the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
""" 实属,无意义 """
"""the real part of a complex number""" int
long(长整型)
  跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
  注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。
float(浮点型)
  浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
complex(复数)
  复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
注:Python中存在小数字池:-5 ~ 257
2、布尔值
  真或假
  1 或 0
3、字符串
"hello world"

  》》万恶的字符串拼接:

  python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。(PS:同Java的字符串拼接相同)
 name = "fury"
age = 23
print("The age of that fellow named %s is %d" %(name, age))
print("The age of that fellow named {0} is {1}".format(*[name, age]))
print("The age of that fellow named {name} is {age}".format(**{"name" : "warrior","age" : 123}))
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
# strip() 方法会去掉字符串前后的空格、tab键、换行等等
print("===start===")
# userName = input("Please input your name: ")
# if userName.strip() == "fury":
# print("Welcome to the city of Chongqing! ")
#将字符串切成列表
print("===one===")
name = "One,Two,Three"
name1 = name.split(",")
print(name1)
# 将列表合成一个字符串
print("===two===")
name2 = "|".join(name1)
print(name2)
# 判断一个字符串里面有没有空格
print("===three===")
name3 = "fury wArrior"
print(" " in name3)
# 将字符串的首字母大写,其余的全部小写
print("===four===")
print(name3.capitalize())
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
# 字符串的格式
print("===start===")
msg = "Hello, {name}. Your age is {age}."
print(msg.format(name = "fury", age = )) msg1 = "Hello, {0}. Your age is {1}."
print(msg1.format("warrior",))
# 切片
print("===one===")
name = "Thinking in Java"
print(name[:])
# len() 字符串长度
print("===two===")
print(len(name))
# center() 将字符串放在自定宽度的中间,多余的位置用指定的字符进行填充
print("===three===")
print(name.center(,"-"))
print(name.center(len(name) + ,"&"))
# find() 做出指定字符串的索引
print("===four===")
print(name.find("T"))
print(name.find("")) #没有返回 -
# 判断输入的是否是数字
print("===five===")
age = input("Please input your age: ")
if age.isdigit():
age = int(age)
else:
print("Invalid input")
print("===six===")
name1 = "furywarrior"
print(name1.endswith("warrior")) # 结束判断
print(name1.startswith("fury")) #开始判断
print(name1.upper()) #全部转换成大写
print(name1.lower()) #全部转换成小写

》列表

Python 中的list 就相当于 Java 中的数组;但是Python中的list可以存储不同的数据类型
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
# Python 中的list 就相当于 Java 中的数组;但是Python中的list可以存储不同的数据类型
name = ["fury", "warrior",,,,,"peter","bob"]
print(name[])
print(name[-])
print(name[:]) #切片 注意:和Java一样,取首不取尾
print(name[-:-]) #没取到最后一个 ,原因:取首不取尾
print(name[-:]) #不写后面这个参数,就默认取到最后一个并且包含最后一个
print(name[:])
print(name[:])
print(name[:])
print(name[:][:])
print(name[:][:][])
print("====")
print(name[:][:][][])
print("===")
name2 = list(["warrior", "fury"])
print(name2[:])
# print(name2[:][]) #切分到只有两个元素后,就不要再进行切分啦,直接利用下标进行引用
print(name2[][])
print("===start===")
print(name2)
print("===one===")
name2[] = "peter" #修改元素的值
print(name2)
print("===two===")
name2.insert(,"bob") #插入一个元素到列表中
print(name2)
print("===three===")
name2.append("hello") #追加一个元素到最后
print(name2)
print("===four===")
name2.remove("bob") #删除一个元素
print(name2)
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
name = ["fury",'warrior',,,,,,,,,"bob","fury"]
if "fury" in name: #判断"fury" 是否在列表name中
num_of_ele = name.count("fury") #算出"fury"在列表中的个数
positionOfEle = name.index("fury") #找到第一个"fury"的位置
print("[%d] \"fury\" is in the list of name and the first position is [%d]." %(num_of_ele, positionOfEle))
print(name[positionOfEle])
name[positionOfEle] = "peter" #修改元素的值
print(name[positionOfEle])
print("===one===")
#怎么改变一个列表中所有的相同元素 name1 = list([,,,,,,,,,,,,])
print(name1)
#同时改变相同元素的值
if in name1:
numOf1 = name1.count()
print("%d 1 is in the list of name1." %(numOf1))
for i in range(numOf1):
posOf1 = name1.index()
name1[posOf1] = "" print(name1)
print( in name1)
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
"""
作业要求:
写一个列表,列表包含本组所有成员
往中间插入两个临组成员的名字
取出两个临组成员
删除第12个人
把刚才加入的那2个其它组的人一次性删除
把组长的名字加上组长备注
每隔一个人打印一个人
"""
name2 = [, , , ]
name1 = [, , , ]
name3 = [, , , ]
print("===start===")
for i in range():
if i < :
name2.insert( + i, name1[i])
else:
name2.insert( + i, name3[-( - i)])
print(name2)
print("===one===")
name4 = name2[:] # 切片处理
print(name4)
print("===two===")
name2.remove() #删除一个元素
print(name2)
print("===three===")
del name2[:] # del 是全局的,什么都可以删 #删除多个元素
print(name2)
print("===four===")
name2[] = "组长" #改变元素的值
print(name2)
print("===five===")
print(name2[::]) #间隔打印列表的元素
print("===six===")
x =
print(x)
del x
# print(x) #经过del删除后变量x就不存在啦
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
# 经一个列表整体加载到另一个列表的后面
print("===start===")
name1 = [,,,,,,]
name2 = [,,]
print(name1)
name1.extend(name2)
print(name1)
print(name2)
print("===one===")
# 将一个列表进行反转处理
name2.reverse()
print(name2)
# 排序:在3.5中不同的数据类型不能够混合排序
name1.sort()
print(name1)
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
import copy
# 利用pop删除元素
print("===start===")
name = ["fury","warrior","peter","bob"]
print(name)
name.pop() #默认删除最后一个
print(name)
name.pop() #参数是元素的位置
print(name)
# copy方法_1
print("===one===")
name1 = ["fury","warrior","hello"]
name2 = name1.copy()
name1[] = "FURY"
print(name1)
print(name2)
# copy_2 : copy没有办法copy第二层,即如果列表中有一个元素是列表类型,那么copy过来的是
# 这个列表的地址,而不是这个列表中真正的值,所以会形成一改全改的结果
print("===two===")
lis1 = ["fury","warrior",[,,]]
lis2 = lis1.copy()
print(lis1)
print(lis2)
lis1[][] = "hello"
print(lis1)
print(lis2)
lis2[][] = "world"
print(lis1)
print(lis2)
#解决办法利用copy库
print("===three===")
lis3 = lis1.copy()
print(lis3)
# print("浅copy")
# lis3 = copy.copy(lis1)
# lis1[][] = "NeverCtrl_C"
# print(lis3)
print("深copy")
lis3 = copy.deepcopy(lis1)
lis1[][] = "NeverCtrl_C"
print(lis3)
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
# 找出所有的9并且改成999
# 找出所有的34并且直接删掉
lis = [,,,,,,,,,]
print(lis.count())
print(lis.count())
print(lis)
print("长度为:%d" %len(lis))
for i in range(lis.count()):
lis[lis.index()] =
print(lis)
for i in range(lis.count()):
lis.remove(lis[lis.index()])
print(lis)
print("长度为:%d" %len(lis))
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
list = ["fury","warrior","peter"]
print("===one===")
for item in enumerate(list):
print(item)
# enumerate() 是一个枚举,它返回的是一个元组,元组的第一个元素是
# 从0开始的下标,元组的第二个元素是内容
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
lis01 = [,[,,"warrior"],("warrior",),,"fury"]
print("\033[41;1m%s\033[0m" %lis01[])
# print("%s %s %s" %lis01[]) # 错误的输出方法
print("%s \033[31;1m%s\033[0m" %lis01[])
# print("%s" %lis01[]) # 错误写法 # 在利用 print("%类型" %(变量)) 这种类型进行打印输出时,列表中的元素看成
# 是一个整体,前提是列表中的元素不是元组类型的数据;如果是元组类型的数据,
# 那么就必须根据该元组中元素的个数在“”里面添加相同数量的%数据类型个数 # \[;1m%s\[0m 添加颜色
# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
"""
》购物小程序
》》用户启动时先输入工资
》》用户启动程序后打印商品列表
》》允许用户选择购买商品
》》允许用户不断的购买各种商品
》》购买时检测余额是否足够,如果足够直接扣款,否则打印余额不足
》》允许用户主动退出,退出时打印已购商品列表
"""
salary = input("Please input your salary: ")
if salary.isdigit():
salary = int(salary)
else :
exit("Invalid data type ...") welcom_msg = "Welcome to ShoppingStore".center(50,"=")
print(welcom_msg)
products_list = [
("A" , 1000),
("B" , 2000),
("C" , 3000),
("D" , 4000),
("E" , 5000)
]
shop_car = [] # print(products_list[1][0],products_list[1][1]) exit_flag = False
while not exit_flag :
for products_item in enumerate(products_list) : #类似于Java中for循环的简便写法
print(products_item)
p_choice_index = input("[q:quit; c:check]What kind of products do you want to purchase?")
if p_choice_index.isdigit():
p_choice_index = int(p_choice_index)
if p_choice_index < len(products_list):
p_choice = products_list[p_choice_index]
if salary >= p_choice[1]: #买得起
shop_car.append(p_choice) #加入购物车
salary -= p_choice[1] #减钱
print("The product you chose just now is [%s %d] " %(p_choice[0],p_choice[1]))
print("Your banance is \033[31;1m[%s]RMB\033[0m " %salary)
else:
for shop_item in enumerate(shop_car):
print(shop_item)
print("Your banance is [%s] , failling to affort ...." %salary)
else:
if p_choice_index == "q" or p_choice_index == "quit":
print("You choose to quit.")
else:
print("Your input is wrong.") print("Purchaseed products as follow:".center(40,"="))
for shop_item in shop_car:
print(shop_item)
print("Goodbye".center(40, "="))
print("Your banance is [%s] " % salary)
exit_flag = True """
优化购物程序,购买时允 许用户购买多件商品
允许多用户登录,下一次登录后,继续按上一次的余额继续购买(可以充值)
允许用户查看之前的购买记录(记录要显示商品购买的时间)
商品里列表分级展示
"""

购物小程序

》元组

  就是不能改变元素值得列表

tup01 = (1,"fury",3)
print(tup01, type(tup01))
# tup01[0] = "fury" #错误写法:元组的元素值不能够被更改

元组

tup01 = (1,"fury",3,1)
print(tup01, type(tup01))
# tup01[0] = "fury" #错误写法:元组的元素值不能够被更改
print(tup01.count(1))
print(tup01.index("fury"))

元组的方法

lass tuple(object):
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
"""
def count(self, value): # real signature unknown; restored from __doc__
""" T.count(value) -> integer -- return number of occurrences of value """
return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0 def __add__(self, y): # real signature unknown; restored from __doc__
""" x.__add__(y) <==> x+y """
pass def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x """
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__
"""
x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported.
"""
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass def __hash__(self): # real signature unknown; restored from __doc__
""" x.__hash__() <==> hash(x) """
pass def __init__(self, seq=()): # known special case of tuple.__init__
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object.
# (copied from class doc)
"""
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass def __mul__(self, n): # real signature unknown; restored from __doc__
""" x.__mul__(n) <==> x*n """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __rmul__(self, n): # real signature unknown; restored from __doc__
""" x.__rmul__(n) <==> n*x """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" T.__sizeof__() -- size of T in memory, in bytes """
pass tuple

list

》字典

  字典是无序的,也是没有下标的

 # Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
dic = {
"name" : "fury",
"age" : 123,
"salary" : 15600 }
print(dic) # 打印整个字典
print(dic["name"]) # 打印字典中指定关键字所对应的内容
# 字典时没有下标的,故字典是无序的;所以打印字典的全部内容时是要变化的

字典的创建和打印

# Keep Calm and Carry on
# _*_coding:utf-8_*_
# Author: NeverCtrl_C
"""
"""
dic = {
1 : {"name" : "fury1","age" : 21 , "salary" : 15601},
2 : {"name" : "fury2","age" : 22 , "salary" : 15602},
3 : {"name" : "fury3","age" : 23 , "salary" : 15603},
}
print(dic)
#增加一个K-V值
print("===start===")
dic[4] = {"name" : "fury4","age" : 24 , "salary" : 15604}
print(dic)
#删除字典中的所有内容,key 和 value一起删掉
print("===one===")
print(dic)
# dic.clear()
print(dic)
# 浅复制(类似于列表list)
print("===two===")
dic1 = dic.copy()
print(dic1)
# dic1[1]["name"] = "fury" # value值是一个字典时会是一改全改(类似于列表)
# dic1[1] = "hello" # value值不是字典时,改的谁就是改的谁
print(dic)
print(dic1)
print("===three===")
dic2 = dic.fromkeys()
print(dic2)

字典元素的增加、删除、字典复制

class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
""" def clear(self): # real signature unknown; restored from __doc__
""" 清除内容 """
""" D.clear() -> None. Remove all items from D. """
pass def copy(self): # real signature unknown; restored from __doc__
""" 浅拷贝 """
""" D.copy() -> a shallow copy of D """
pass @staticmethod # known case
def fromkeys(S, v=None): # real signature unknown; restored from __doc__
"""
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
"""
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" 根据key获取值,d是默认值 """
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def has_key(self, k): # real signature unknown; restored from __doc__
""" 是否有key """
""" D.has_key(k) -> True if D has a key k, else False """
return False def items(self): # real signature unknown; restored from __doc__
""" 所有项的列表形式 """
""" D.items() -> list of D's (key, value) pairs, as 2-tuples """
return [] def iteritems(self): # real signature unknown; restored from __doc__
""" 项可迭代 """
""" D.iteritems() -> an iterator over the (key, value) items of D """
pass def iterkeys(self): # real signature unknown; restored from __doc__
""" key可迭代 """
""" D.iterkeys() -> an iterator over the keys of D """
pass def itervalues(self): # real signature unknown; restored from __doc__
""" value可迭代 """
""" D.itervalues() -> an iterator over the values of D """
pass def keys(self): # real signature unknown; restored from __doc__
""" 所有的key列表 """
""" D.keys() -> list of D's keys """
return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__
""" 获取并在字典中移除 """
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass def popitem(self): # real signature unknown; restored from __doc__
""" 获取并在字典中移除 """
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass def update(self, E=None, **F): # known special case of dict.update
""" 更新
{'name':'alex', 'age': 18000}
[('name','sbsbsb'),]
"""
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass def values(self): # real signature unknown; restored from __doc__
""" 所有的值 """
""" D.values() -> list of D's values """
return [] def viewitems(self): # real signature unknown; restored from __doc__
""" 所有项,只是将内容保存至view对象中 """
""" D.viewitems() -> a set-like object providing a view on D's items """
pass def viewkeys(self): # real signature unknown; restored from __doc__
""" D.viewkeys() -> a set-like object providing a view on D's keys """
pass def viewvalues(self): # real signature unknown; restored from __doc__
""" D.viewvalues() -> an object providing a view on D's values """
pass def __cmp__(self, y): # real signature unknown; restored from __doc__
""" x.__cmp__(y) <==> cmp(x,y) """
pass def __contains__(self, k): # real signature unknown; restored from __doc__
""" D.__contains__(k) -> True if D has a key k, else False """
return False def __delitem__(self, y): # real signature unknown; restored from __doc__
""" x.__delitem__(y) <==> del x[y] """
pass def __eq__(self, y): # real signature unknown; restored from __doc__
""" x.__eq__(y) <==> x==y """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, y): # real signature unknown; restored from __doc__
""" x.__ge__(y) <==> x>=y """
pass def __gt__(self, y): # real signature unknown; restored from __doc__
""" x.__gt__(y) <==> x>y """
pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass def __le__(self, y): # real signature unknown; restored from __doc__
""" x.__le__(y) <==> x<=y """
pass def __lt__(self, y): # real signature unknown; restored from __doc__
""" x.__lt__(y) <==> x<y """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __ne__(self, y): # real signature unknown; restored from __doc__
""" x.__ne__(y) <==> x!=y """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__
""" x.__setitem__(i, y) <==> x[i]=y """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None dict

list

》enumrate

  为可迭代的对象添加序号:返回值是序号和值,但是如果是字典类型的数据返回的值只是key值,没有value值

lis = ["warrior", "fury", "happy"]
for item1 in enumerate(lis):
# print(item1[0],item1[1])
# 优化:
print(item1) dic = {
1: "warrior",
2: "fury",
3: "happy",
} for item in enumerate(dic):
print(item[0], item[1])