版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZZh1301051836/article/details/81605170
本文中的内容,有的是python3.5较之前版本的改变,有个则是笔者自己的易错点,仅作个人笔记,若有误,请指出,谢谢。
1 字典
1.1 使用dict()函数创建字典
dict()函数的参数可以是
(1) 其他映射,比如其他字典。(注意:字典是python中唯一内建的映射类型)。
>>> d = dict(name='stephen',age=24)
>>> d
{'name': 'stephen', 'age': 24}
>>> p=dict(d)
>>> p
{'name': 'stephen', 'age': 24}
(2)(键,值)对的序列。
items = [('john',21),('stephen',23)]
student = dict(items)
print(student)
(3)关键字参数。
>>> d = dict(name='stephen',age=24)
>>> d
{'name': 'stephen', 'age': 24}
(4)为空,返回一个新的空字典。
>>> d = dict()
>>> d
{}
1.2 多层嵌套字典
>>> people = {
'stephen':{
'phone':'111',
'addr':'aaa'
},
'John':{
'phone':'222',
'addr':'bbb'
},
'Alice':{
'phone':'333',
'addr':'ccc'
}
}
>>> people['stephen']['phone']
'111'
其中,people是一个字典,’stephen’:{‘phone’:’111’, ‘addr’:’aaa’}是其中的一个项,每一个项的结构是,键是字符串,值又是一个字典。以此形式构成了一个嵌套字典。
2 获取输入 input && raw_input
注意,在python3.0版本后,用input替换了raw_input()。
若是继续使用raw_input(),会提示错误:
NameError: name ‘raw_input’ is not defined
3 条件语句if
if语句的格式
if 表达式 :
语句1
elif 表达式 :
语句2
else :
语句3
特别注意,表达式后一定要跟一个冒号
。
4 输出函数print()
Python3中的print,和之前版本的有较大不同。
python3中的print需要使用括号。其用法要点可大致分为两类:
- 直接输出
所有变量(数值、列表、元组、字典等)和常量(数值常量、字符串常量等)均可以直接输出。
>>> print(1)##数值
1
>>> print('Hello Python')##字符串
Hello Python
>>> x = 12
>>> print(x) #数值变量
12
>>> str = 'hello'
>>> print(str) #字符串常量
hello
>>> L = [1,2,'a']
>>> print(L) #列表
[1, 2, 'a']
>>> t = (1,2,'a')
>>> print(t) #元组
(1, 2, 'a')
>>> d = {'a':1,'b':2}
>>> print(d) #字典
{'a': 1, 'b': 2}
- 格式化输出
类似C中的printf()
>>> str
'hello'
>>> length = len(str)
>>> print('The length of %s is %d'% (str,length))
The length of hello is 5
>>> print('The length of %s is %d', (str,length))
The length of %s is %d ('hello', 5)
注意:print()中的格式字符串和变量之间,用**%**隔开。并且,所有变量以元组形式表示。