编码格式: # -*- coding: UTF-8 -*-
写在第一行,py3默认编码格式是utf-8,你也可以指定其他格式
注释
单行注释: # 多行注释: ''' '''
编写格式
python中用 Tab键缩进
导入
导入模块: import time
导入方法: from time import sleep
list[ ] 列表及常用操作
#list是一种有序的集合,可以随时添加和删除其中的元素。 tset = ['a', 'b', 'c'] test ['a', 'b', 'c'] #test 用len()函数可以获得list元素的个数 len(test) 3 #用索引来访问list中每一个位置的元素,索引是从0开始的: test[0] 'a' test[1] 'b' test[2] 'c'
#添加元素有两种:1.append 2.insert test.append('d') #在末尾添加 test.insert(1,'d') #1是添加的位置,d是添加的内容 #要删除list末尾的元素,用pop()方法: test.pop() #指定删除则在pop中写入需要删除的位置 test.pop(1) #删除d #要把某个元素替换成别的元素,可以直接赋值给对应的索引位置: test[1] = 'B' test ['a', 'B', 'c']
#list里面的元素的数据类型也可以不同,比如: L = ['a', 1, 1.2,['-2','true']]
字典 { }
字典一般用大括号包裹起来,里面的元素都是有键和值组成
#创建一个字典 tem ={'北京':22,'上海':23,'深圳':24,'广州':25,'南京':[20,多云]} print(tem) # 打印南京天气 print(tem['南京'][1]) # 字典中添加一个元素 tem['重庆'] = 28 print(tem) # 删除上海 del tem['上海'] print(tem) # 更新某一个值 tem['北京'] = 28 print(tem)
数据类型和操作:
下文内容来自: http://cheat.sh/python/:learn, 有删减
#数字
3 # => 3
#算术
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
35 / 5 # => 7
# 除法默认是做整数除法,比如
5 / 2 # => 2
# 我们一般所认知的除法在python里其实就是浮点数除法,首先要了解什么是浮点数(floats)
2.0 # 这就是浮点数了
11.0 / 4.0 # => 2.75 嗯...好多了
# 可以强制返回整数,正数负数都可以了
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # 浮点数也行
-5 // 3 # => -2
-5.0 // 3.0 # => -2.0
11 / 4 # => 2.75 ...普通除法
11 // 4 # => 2 ...取整除法
# 模/取余操作
7 % 3 # => 1
# 乘方 (x 的 y 次方)
2 ** 4 # => 16
# 用括号强制改变算术的结合律
(1 + 3) * 2 # => 8
# 布尔值的操作或者叫逻辑运算
# 注意 "and" 和 "or" 是区分大小写的
True and False # => False
False or True # => True
# 注意布尔操作跟整数搅在一起的时候
0 and 2 # => 0
-5 or 0 # => -5
0 == False # => True
2 == True # => False
1 == True # => True
# 用not来逻辑取反
not True # => False
not False # => True
# 相等判断用 ==
1 == 1 # => True
2 == 1 # => False
# 不等用 !=
1 != 1 # => False
2 != 1 # => True
# 更多的比较
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
# 比较可以串起来
1 < 2 < 3 # => True
2 < 3 < 2 # => False
# 用 " 或 ' 来创建字符串
"This is a string."
'This is also a string.'
# 字符串也是可以相加的
"Hello " + "world!" # => "Hello world!"
# 不用 '+' 号也能加
"Hello " "world!" # => "Hello world!"
# ... 甚至可以相乘
"Hello" * 3 # => "HelloHelloHello"
# 字符串可以当成是字符组成的列表
"This is a string"[0] # => 'T'
# 可以拿到字符串的长度
len("This is a string") # => 16
# 可以用 % 来格式化字符串
# Even though the % string operator will be deprecated on Python 3.1 and removed
# 即使 % 操作在Python 3.1以后会被废弃和移除
# 不过知道这些代码是如何工作的总不是坏事
x = 'apple'
y = 'lemon'
z = "The items in the basket are %s and %s" % (x, y)
# 新一点的格式化字符串的方式是使用format方法
# 这个方法更好一些
"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# 如果你不想数数的话,你还可以使用关键字
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
# None是一个对象
# 所以你是有对象的
None # => None
# 不要使用 "==" 符号进行对象和None的比较
# 要使用 "is"
"etc" is None # => False
None is None # => True
bool(0) # => False
bool("") # => False