学习python--第四天

1.取字符串的方法

test="alexT"
v=test[0]#获取第一个元素
print(v)
v1=test[0:3]#获取从第一个元素到第2个元素的字符串--[0,3)
print(v1)
v2=test[0:-1]#获取从第一个元素到最后一个元素
print(v2)
v3=test[1:-1]#获取从第二个元素到最后一个元素
print(v3)

输出结果
a
ale
alex
lex

 2.用循环的方法取字符串

   test="郑建文妹子有种冲我来"

A.用while语句

 

test = "郑建文妹子有种冲我来"
index = 0
while index < len(test):
	v = test[index]
	print(v)
	index += 1
print('=======')

输出结果:
郑
建
文
妹
子
有
种
冲
我
来
=======

B.for循环

    for 变量名 in 字符串:
         变量名
    break
    continue

for index in test:#index不用声明
    print(index)

输出结果:
郑
建
文
妹
子
有
种
冲
我
来

 range() 函数可创建一个整数列表,一般用在 for 循环中。

 语法:range(start, stop[, step])

 参数说明:

  • start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
  • stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
  • step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

 备注:获取连续或不连续的数字

            Python2中直接创建在内容中
            Python3中只有for循环时,才一个一个创建

            帮助创建连续的数字,通过设置步长来指定不连续

            range(100):指0到99的数字

v = range(0, 50, 5)
for item in v:
	print(item)

输出结果:
0
5
10
15
20
25
30
35
40
45

 练习题:根据用户输入的值,输出每一个字符以及当前字符所在的索引位置

 

test = input(">>>")
print(test)   # test = qwe   test[0]   test[1]
l = len(test) # l = 3
print(l)
r = range(0,l) # 0,3
for item in r:
	print(item,test[item]) # 0 q,1 w,2 e

输出结果
>>>qwe
qwe
3
0 q
1 w
2 e

——————————————————————————
用另一种简洁的方法
test=input(">>>")
for item in range(0,len(test)):
	print(item,test[item])

 Pyhton 单行注释和多行注释分别用什么?

#单行注释

"""   """ 多行注释

 

#多行注释的方法
"""test=input(">>>")
for item in range(0,len(test)):
	print(item,test[item])
"""

 

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

# v = "李杰"
# for item in v:
#     print(item)
####################################################################################################
# str
# name = "alex"

# list  # 类,列表
# li = [1, 12, 9, "age", ["石振文", ["19", 10], "庞麦郎"], "alex", True]  # 通过list类创建的对象,li
# list 类
# list类的一个对象


#######################################灰魔法: list类中提供的方法 #######################################

# li = [11, 22, 33, 22, 44]
# 参数
# 1. 原来值最后追加
# 对象.方法(..)   # li对象调用append方法
# li.append(5)
# li.append("alex")
# li.append([1234,2323])
# print(li)
# 2 清空列表
# li.clear()
# print(li)

# 3 拷贝,浅拷贝
# v = li.copy()
# print(v)
# 4. 计算元素出现的次数
# v = li.count(22)
# print(v)

# 5. 扩展原列表,参数:可迭代对象
# li = [11, 22, 33, 22, 44]
# li.append([9898,"不得了"])
# [11, 22, 33, 22, 44, [9898, '不得了']]

# li.extend([9898,"不得了"])
# for i in [9898,"不得了"]:
#     li.append(i)
# [11, 22, 33, 22, 44, 9898, '不得了']
#
# li.extend("不得了")
# print(li)

# 6. 根据值获取当前值索引位置(左边优先)
# li = [11, 22, 33, 22, 44]
# v= li.index(22)
# print(v)

# 7. 在指定索引位置插入元素
# li = [11, 22, 33, 22, 44]
# li.insert(0,99)
# print(li)

# 8、 删除某个值(1.指定索引;2. 默认最后一个),并获取删除的值
# li = [11, 22, 33, 22, 44]
# v = li.pop()
# print(li)
# print(v)

# li = [11, 22, 33, 22, 44]
# v = li.pop(1)
# print(li)
# print(v)
# 9. 删除列表中的指定值,左边优先
# li = [11, 22, 33, 22, 44]
# li.remove(22)
# print(li)
# PS: pop remove del li[0]    del li[7:9]   clear

# 10 将当前列表进行翻转
# li = [11, 22, 33, 22, 44]
# li.reverse()
# print(li)

# 11 列表的排序
# li = [11,44, 22, 33, 22]
# li.sort()
# li.sort(reverse=True)
# print(li)
### 欠
# cmp
# key
# sorted

####################################### 深灰魔法 #######################################
# 1. 列表格式
# 2. 列表中可以嵌套任何类型
# 中括号括起来
# ,分割每个元素
# 列表中的元素可以是 数字,字符串,列表,布尔值..所有的都能放进去
# “集合”,内部放置任何东西
"""
# 3.
# 索引取值
print(li[3])
# 4 切片,切片结果也是列表
print(li[3:-1])

# 5 for循环
# while循环
for item in li:
    print(item)
"""
# 列表元素,可以被修改

# li = [1, 12, 9, "age", ["石振文", ["19", 10], "庞麦郎"], "alex", True]

############## 6 索引
# 修改
# li[1] = 120
# print(li)
# li[1] = [11,22,33,44]
# print(li)

# 删除,第一种方式
# del li[1]
# print(li)
############## 7 切片
# 修改
# li[1:3] = [120,90]
# print(li)
# 删除
# del li[2:6]
# print(li)

# 8 in 操作
# li = [1, 12, 9, "age", ["石振文", ["19", 10], "庞麦郎"], "alex", True]
# v1 = "石振文" in li
# print(v1)
# v2 = "age" in li
# print(v2)
###### 列表中的元素,

# 9 操作
# li = [1, 12, 9, "age", ["石振文", ["19", 10], "庞麦郎"], "alex", True]
# li[4][1][0]
# [1]

# li = [1, 12, 9, "age", ["石振文", ["19", 10], "庞麦郎"], "alex", True]

# s = "pouaskdfauspdfiajsdkfj"
# s = 123
# a = "123"
# int(a)
# a = 123
# str(a)
# 10 转换
# 字符串转换列表   li =  list("asdfasdfasdf"), 内部使用for循环
# s = "pouaskdfauspdfiajsdkfj"
# new_li = list(s)
# print(new_li)

# 列表转换成字符串,
# 需要自己写for循环一个一个处理: 既有数字又有字符串
# li = [11,22,33,"123","alex"]
# # r = str(li) # '[11,22,33,"123","alex"]'
# # print(r)
# s = ""
# for i in li:
#     s = s + str(i)
# print(s)
# 直接使用字符串join方法:列表中的元素只有字符串
# li = ["123","alex"]
# v = "".join(li)
# print(v)

### 补充:字符串创建后,不可修改
# v = "alex"
# v = v.replace('l','el')
# print(v)

# li = [11,22,33,44]
# li[0]
# li[0] = 999

# s = "alex"
# li[0]
# s[0] = "E"

# li = [11,22,33,44]
# print(li)
# print(li)
# print(li)
# print(li)
# print(li)
# print(li)
# print(li)
# print(li)
# 列表,有序;元素可以被修改

# 列表
# list
# li = [111,22,33,44]


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

# 元组,元素不可被修改,不能被增加或者删除
# tuple
# tu = (11,22,33,44)
# tu.count(22),获取指定元素在元组中出现的次数
# tu.index(22)

####################################### 深灰魔法 #######################################
# 1. 书写格式
# tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
# 一般写元组的时候,推荐在最后加入 ,
# 元素不可被修改,不能被增加或者删除
# 2. 索引
# v = tu[0]
# print(v)

# 3. 切片
# v = tu[0:2]
# print(v)

# 4. 可以被for循环,可迭代对象
# for item in tu:
#     print(item)

# 5. 转换
# s = "asdfasdf0"
# li = ["asdf","asdfasdf"]
# tu = ("asdf","asdf")
#
# v = tuple(s)
# print(v)

# v = tuple(li)
# print(v)

# v = list(tu)
# print(v)

# v = "_".join(tu)
# print(v)

# li = ["asdf","asdfasdf"]
# li.extend((11,22,33,))
# print(li)

# 6.元组的一级元素不可修改/删除/增加(二级元素有时候可以被修改,如是列表中的元素可以被修改)
# tu = (111,"alex",(11,22),[(33,44)],True,33,44,)
# # 元组,有序。
# # v = tu[3][0][0]
# # print(v)
# # v=tu[3]
# # print(v)
# tu[3][0] = 567
# print(tu)

####################################################################################################
# 字典
# dict
# dict
# dic = {
#     "k1": 'v1',
#     "k2": 'v2'
# }
# 1 根据序列,创建字典,并指定统一的值
# v = dict.fromkeys(["k1",123,"999"],123)
# print(v)

# 2 根据Key获取值,key不存在时,可以指定默认值(None)
# v = dic['k11111']
# print(v)
# v = dic.get('k1',111111)
# print(v)

# 3 删除并获取值
# dic = {
#     "k1": 'v1',
#     "k2": 'v2'
# }
# v = dic.pop('k1',90)
# print(dic,v)
# k,v = dic.popitem()
# print(dic,k,v)

# 4 设置值,
# 已存在,不设置,获取当前key对应的值
# 不存在,设置,获取当前key对应的值
# dic = {
#     "k1": 'v1',
#     "k2": 'v2'
# }
# v = dic.setdefault('k1111','123')
# print(dic,v)

# 5 更新
# dic = {
#     "k1": 'v1',
#     "k2": 'v2'
# }
# dic.update({'k1': '111111','k3': 123})
# print(dic)
# dic.update(k1=123,k3=345,k5="asdf")
# print(dic)

# 6 keys()  7 values()   8 items()   get   update
##########



# 1、基本机构
# info = {
#     "k1": "v1", # 键值对
#     "k2": "v2"
# }
#### 2 字典的value可以是任何值
# info = {
#     "k1": 18,
#     "k2": True,
#     "k3": [
#         11,
#         [],
#         (),
#         22,
#         33,
#         {
#             'kk1': 'vv1',
#             'kk2': 'vv2',
#             'kk3': (11,22),
#         }
#     ],
#     "k4": (11,22,33,44)
# }
# print(info)

####  3 布尔值(1,0)、列表、字典不能作为字典的key
# info ={
#     1: 'asdf',
#     "k1": 'asdf',
#     True: "123",
#     # [11,22]: 123
#     (11,22): 123,
#     # {'k1':'v1'}: 123
#
# }
# print(info)

# 4 字典无序

# info = {
#     "k1": 18,
#     "k2": True,
#     "k3": [
#         11,
#         [],
#         (),
#         22,
#         33,
#         {
#             'kk1': 'vv1',
#             'kk2': 'vv2',
#             'kk3': (11,22),
#         }
#     ],
#     "k4": (11,22,33,44)
# }
# print(info)

# 5、索引方式找到指定元素
# info = {
#     "k1": 18,
#     2: True,
#     "k3": [
#         11,
#         [],
#         (),
#         22,
#         33,
#         {
#             'kk1': 'vv1',
#             'kk2': 'vv2',
#             'kk3': (11,22),
#         }
#     ],
#     "k4": (11,22,33,44)
# }
# # v = info['k1']
# # print(v)
# # v = info[2]
# # print(v)
# v = info['k3'][5]['kk3'][0]
# print(v)

# 6 字典支持 del 删除
# info = {
#     "k1": 18,
#     2: True,
#     "k3": [
#         11,
#         [],
#         (),
#         22,
#         33,
#         {
#             'kk1': 'vv1',
#             'kk2': 'vv2',
#             'kk3': (11,22),
#         }
#     ],
#     "k4": (11,22,33,44)
# }
# del info['k1']
#
# del info['k3'][5]['kk1']
# print(info)

# 7 for循环
# dict
# info = {
#     "k1": 18,
#     2: True,
#     "k3": [
#         11,
#         [],
#         (),
#         22,
#         33,
#         {
#             'kk1': 'vv1',
#             'kk2': 'vv2',
#             'kk3': (11,22),
#         }
#     ],
#     "k4": (11,22,33,44)
# }
# for item in info:
#     print(item)
#
# for item in info.keys():
#     print(item)

# for item in info.values():
#     print(item)

# for item in info.keys():
#     print(item,info[item])

# for k,v in info.items():
#     print(k,v)

# True 1  False 0
# info ={
#     "k1": 'asdf',
#     True: "123",
#     # [11,22]: 123
#     (11,22): 123,
#     # {'k1':' v1'}: 123
#
# }
# print(info)

####################### 整理 #################

# 一、数字
# int(..)
# 二、字符串
# replace/find/join/strip/startswith/split/upper/lower/format
# tempalte = "i am {name}, age : {age}"
# # v = tempalte.format(name='alex',age=19)
# v = tempalte.format(**{"name": 'alex','age': 19})
# print(v)
# 三、列表
# append、extend、insert
# 索引、切片、循环
# 四、元组
# 忽略
# 索引、切片、循环         以及元素不能被修改
# 五、字典
# get/update/keys/values/items
# for,索引

# dic = {
#     "k1": 'v1'
# }

# v = "k1" in dic
# print(v)

# v = "v1" in dic.values()
# print(v)
# 六、布尔值
# 0 1
# bool(...)
# None ""  () []  {} 0 ==> False

 

Python 字典(Dictionary)

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。

>>>dict = {'a': 1, 'b': 2, 'b': '3'} >>> dict['b'] '3' >>> dict {'a': 1, 'b': '3'}

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

一个简单的字典实例:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

也可如此创建字典:

dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 }

访问字典里的值

把相应的键放入熟悉的方括弧,如下实例:

实例

#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Name']: ", dict['Name'] print "dict['Age']: ", dict['Age']

以上实例输出结果:

dict['Name']:  Zara
dict['Age']:  7

如果用字典里没有的键访问数据,会输出错误如下:

实例

#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print "dict['Alice']: ", dict['Alice']

以上实例输出结果:

dict['Alice']: 
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print "dict['Alice']: ", dict['Alice']
KeyError: 'Alice'

 


修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

实例

#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8 # 更新 dict['School'] = "RUNOOB" # 添加 print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School']

以上实例输出结果:

dict['Age']:  8
dict['School']:  RUNOOB

 


删除字典元素

能删单一的元素也能清空字典,清空只需一项操作。

显示删除一个字典用del命令,如下实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name'] # 删除键是'Name'的条目 dict.clear() # 清空词典所有条目 del dict # 删除词典 print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School']

但这会引发一个异常,因为用del后字典不再存在:

dict['Age']:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print "dict['Age']: ", dict['Age'] 
TypeError: 'type' object is unsubscriptable

注:del()方法后面也会讨论。

 

字典键的特性

字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。

两个重要的点需要记住:

 

1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:

 

实例

#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} print "dict['Name']: ", dict['Name']

以上实例输出结果:

dict['Name']:  Manni

2)键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行,如下实例:

实例

#!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7} print "dict['Name']: ", dict['Name']

以上实例输出结果:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Zara', 'Age': 7} 
TypeError: list objects are unhashable

 


字典内置函数&方法

Python字典包含了以下内置函数:

序号函数及描述
1 cmp(dict1, dict2)
比较两个字典元素。
2 len(dict)
计算字典元素个数,即键的总数。
3 str(dict)
输出字典可打印的字符串表示。
4 type(variable)
返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:

 

序号函数及描述
1 dict.clear()
删除字典内所有元素
2 dict.copy()
返回一个字典的浅复制
3 dict.fromkeys(seq[, val])
创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
4 dict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值
5 dict.has_key(key)
如果键在字典dict里返回true,否则返回false
6 dict.items()
以列表返回可遍历的(键, 值) 元组数组
7 dict.keys()
以列表返回一个字典所有的键
8 dict.setdefault(key, default=None)
和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9 dict.update(dict2)
把字典dict2的键/值对更新到dict里
10 dict.values()
以列表返回字典中的所有值
11 pop(key[,default])
删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12 popitem()
随机返回并删除字典中的一对键和值。

#集合的特点:
1.不用的元素组成
2.无序的
3.集合中的元素必须是不可变类型(数字、字符、元祖)

# s=set('hello')
# print(s)
#
# s=set(['alex','alex','sb'])
# print(s)

# s={1,2,3,4,5,6}

#添加
# s.add('s')
# s.add('3')
# s.add(3)
# print(s)

# s.clear()
# print(s)

# s1=s.copy()

s={'sb',1,2,3,4,5,6}
#随机删
# s.pop()

#指定删除
# s.remove('sb')
# s.remove('hellol') #删除元素不存在会报错
# s.discard('sbbbb')#删除元素不存在不会报错
# print(s)


# python_l=['lcg','szw','zjw','lcg']
# linux_l=['lcg','szw','sb']
# p_s=set(python_l)
# l_s=set(linux_l)
# #求交集
# print(p_s,l_s)
# print(p_s.intersection(l_s))
# print(p_s&l_s)
# #求并集
# print(p_s.union(l_s))
# print(p_s|l_s)
# #差集
# print('差集',p_s-l_s)
# print(p_s.difference(l_s))
# print('差集',l_s-p_s)
# print(l_s.difference(p_s))





#交叉补集
# print('交叉补集',p_s.symmetric_difference(l_s))
# print('交叉补集',p_s^l_s)

python_l=['lcg','szw','zjw','lcg']
linux_l=['lcg','szw','sb']
p_s=set(python_l)
l_s=set(linux_l)
print(p_s,l_s)
# print('差集',p_s-l_s)
# p_s=p_s-l_s
p_s.difference_update(l_s)
print(p_s)

# s1={1,2}
# s2={2,3,5}
# print(s1.isdisjoint(s2))

s1={1,2}
s2={1,2,3}
print(s1.issubset(s2))#s1 是s2 的子集
print(s2.issubset(s1))#False

print(s2.issuperset(s1))#s1 是s2 的父集

s1={1,2}
s2={1,2,3}
# s1.update(s2) #更新多个值

# s1.add(1,2,3,4) #更新一个值
# s1.union(s2) #不更新

print(s1)


s=frozenset('hello')
print(s)
names=['alex','alex','wupeiqi']

names=list(set(names))
print(names)

 浮点数:

# msg='i am %s my hobby is %s' % ('lhf','alex')--%s可以接收任意类型的值,%d只能接收数字类型的值
# print(msg)
#
# msg='i am %s my hobby is %s' % ('lhf',1)
# msg='i am %s my hobby is %s' % ('lhf',[1,2])
# print(msg)
# name='lhf'
# age=19
# msg='i am %s my hobby is %s' % (name,age)
# print(msg)

#打印浮点数
tpl = "percent %f" % 99.976234444444444444
print(tpl)
输出结果:
percent 99.976234
#说明:%f 表示保留小数点后6位,并四舍五入

tpl = "percent %.2f" % 99.976234444444444444 print(tpl)
输出结果:
percent 99.98
#说明:%.2f 表示保留小数点后2位,并四舍五入
#打印百分比 tpl = 'percent %.2f %%' % 99.976234444444444444 print(tpl) 输出结果:
percent 99.98 %
#说明:%%可以打印出%
tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18} print(tpl) 输出结果:
i am alex age 18
msg='i am %(name)+60s my hobby is alex' %{'name':'lhf'} print(msg) 输出结果:
i am                                                          lhf my hobby is alex
#说明:+60s代表向右对齐,且占60位,-60s代表向左对齐且占位60位
msg='i am \033[43;1m%(name)+60s\033[0m my hobby is alex' %{'name':'lhf'} print(msg) 输出结果:

    #说明:\033[43代表颜色

print('root','x','0','0',sep=':')
输出结果:
root:x:0:0
#说明:用参数sep来区分每个字符串输出间隔的符号如(冒号:)
# print('root'+':'+'x'+':'+'0'+':'+'0')也可实现间隔是冒号的功能,但这写法太繁琐,不如用sep好用

 format字符串格式化

tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
print(tpl )
输出结果:
i am seven, age 18, really seven
#表示已字典的方式赋值
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18}) print(tpl )
输出结果:
i am seven, age 18, really seven
#说明:要以key:value的方式赋值的话,前面加上**
tpl = "i am {0}, age {1} , sex {2}".format("denny",44,"男")
print(tpl)
输出结果:
i am denny, age 44 , sex 男
#说明:可以根据元组的下标来赋值
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
print(tpl)
输出结果:
i am seven, age 18
#说明:要以列表的方式赋值,前面要加*

tpl = "i am {:s}, age {:d}".format("seven", 18) #["seven", 18] 输出结果:
i am seven, age 18 tpl = "i am {:s}, age {:d}".format('seven',18)
print(tpl) 输出结果:
i am seven, age 18

l=["seven", 18]
tpl = "i am {:s}, age {:d}".format(*l)
print(tpl)
输出结果:
i am seven, age 18
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{}".format(15, 15, 15, 15, 15, 15.87623, 2) print(tpl)
输出结果:
numbers: 1111,17,15,f,F, 1587.623000%,2
#说明::b代表二进制 :o代表八进制 :d代表整数 :x代表十六进制 :X代表十六进制,输出字母是大写字母
:%代表百分比,(默认小数点后面6位数字)

:%代表

 函数:

使用函数的优点:

1.代码重用

2.保持一致性,易维护

3.可扩张性

 

'''
y=2*x+1
x=3
y->7
x=3
y->7
'''
(说明:以上是数学层面上描述的函数)

python中函数的定义方法 def test(x):
'''
2*x+1
:param x:整形数字
:return: 返回计算结果
'''
y=2*x+1
return y

def test():
'''
2*x+1
:param x:整形数字
:return: 返回计算结果
'''
x=3
y=2*x+1
return y
a=test()
print(a)
#过程:就是没有返回值的函数 # def test01(): # msg = 'test01' # print(msg) # # # def test02(): # msg = 'test02' # print(msg) # return msg # # def test03(): # msg = 'test03' # print(msg) # return 1,2,3,4,'a',['alex'],{'name':'alex'},None # # def test04(): # msg = 'test03' # print(msg) # return {'name':'alex'} # t1=test01() # t2=test02() # t3=test03() # t4=test04() # print(t1) # print(t2) # print(t3) # print(t4) # def calc(x,y): #x=2,y=3 # res=x**y # return x # return y # res=calc(2,3) # # print(x) # # print(y) # print(res) # # a=10 # # b=10 # # calc(a,b) # def test(x,y,z):#x=1,y=2,z=3 # print(x) # print(y) # print(z) #位置参数,必须一一对应,缺一不行多一也不行 # test(1,2,3) #关键字参数,无须一一对应,缺一不行多一也不行 # test(y=1,x=3,z=4) #位置参数必须在关键字参数左边 # test(1,y=2,3)#报错 # test(1,3,y=2)#报错 # test(1,3,z=2) # test(1,3,z=2,y=4)#报错 # test(z=2,1,3)#报错 # def handle(x,type='mysql'): # print(x) # print(type) # handle('hello') # handle('hello',type='sqlite') # handle('hello','sqlite') # def install(func1=False,func2=True,func3=True): # pass #参数组:**字典 *列表 def test(x,*args): print(x) print(args) # test(1)
输出结果:
1
()
# test(1,2,3,4,5)
输出结果:
1
(2, 3, 4, 5)
# test(1,{'name':'alex'})
输出结果:
1
({'name': 'alex'},)

# test(1,['x','y','z'])
输出结果:
1
(['x', 'y', 'z'],)

# test(1,*['x','y','z'])
输出结果:
1
('x', 'y', 'z')

# test(1,*('x','y','z'))
输出结果:
1
('x', 'y', 'z')

# def test(x,**kwargs): # print(x) # print(kwargs) # test(1,y=2,z=3)
输出结果:
1
{'y': 2, 'z': 3}
# test(1,1,2,2,2,2,2,y=2,z=3)
输出结果:
Traceback (most recent call last):
  File "G:/python_project/python_s3/day10/s1.py", line 35, in <module>
    test(1,1,2,2,2,2,2,y=2,z=3)
TypeError: test() takes 1 positional argument but 7 were given
# test(1,y=2,z=3,z=3)#会报错 :一个参数不能传两个值
输出结果:
  File "G:/python_project/python_s3/day10/s1.py", line 35
    test(1,y=2,z=3,z=3)
                  ^
SyntaxError: keyword argument repeated

def test(x,*args,**kwargs): print(x) print(args,args[-1]) print(kwargs,kwargs.get('y')) # test(1,1,2,1,1,11,1,x=1,y=2,z=3) #报错
输出结果:
Traceback (most recent call last):
  File "G:/python_project/python_s3/day10/s1.py", line 41, in <module>
    test(1,1,2,1,1,11,1,x=1,y=2,z=3)
TypeError: test() got multiple values for argument 'x'

# test(1,0,2,3,4,11,5,y=2,z=3)
输出结果:
1
(0, 2, 3, 4, 11, 5) 5
{'y': 2, 'z': 3} 2 # test(1,*[2,3,4],**{'y':5})
输出结果:
1
(2, 3, 4) 4
{'y': 5} 5

 

 

posted on 2019-01-08 14:16  denny_djl  阅读(198)  评论(0)    收藏  举报

导航