变量和数据类型
在 Python 中 我们不需要为变量指定数据类型。所以你可以直接写出 abc = 1 ,这样变量 abc 就是整数类型。如果你写出 abc = 1.0 ,那么变量 abc 就是浮点类型。
number = int(input(“Enter an integer: “))从键盘上输入一个整数 注意转换成int 类型。
查看数据类型type(num).
运算符和表达式
与C语言差不多。
1. 与,或,非用 and,or,not
表示
2. 22//12 ,表示除不尽时保留整数部分
3. 类型转换
类型转换函数 转换路径
float(string) 字符串 -> 浮点值
int(string) 字符串 -> 整数值
str(integer) 整数值 -> 字符串
str(float) 浮点值 -> 字符串
控制流
number = int(input("Enter a number: "))
if number < 100: #注意有冒号
print("The number is less than 100")
else: #注意
print("The number is greater than 100")
循环
while循环:求n个数的平均值
n=5
sum=0
i=0
while i < n:
number=float(input()) #循环体缩进
sum=sum+number
i=i+1
average=sum/n
print("n={},sum={}".format(n,sum)) #字符串格式化,大括号,被替换.format的参数
print("average={:.2f}".format(average)) #2为小数的float类型
打印斐波那契(Fibonacci)数列
a, b = 0, 1
while b < 100:
print(b)
a, b = b, a + b #这里注意意思为a=b,b=a+b;
#print自动换行,可以使用print(b, end=' '),代替换行
for 循环
1 a=['i','am','good'] //一个列表
2 for x in a: //遍历每个元素
3 print(x)
列表
>>> a = [ 1, 342, 223, 'India', 'Fedora'] #可以类型不同
>>> a
[1, 342, 223, 'India', 'Fedora']
#python是以0为开始索引的,注意
>>> a[0]
1
>>> a[4]
'Fedora'
>>> a[-1] #从末尾开始计数
'Fedora'
#切片,其与c++中STL类似,左闭右开
#切片的索引是在两个元素之间
>>> a[0:-1] #不包括最后一个元素
[1, 342, 223, 'India']
>>> a[:] #所有元素
[1, 342, 223, 'India', 'Fedora']
>>> a[1::2] #表示从索引1开始,到最后,间隔为2
[342, 'India']
>>> a + [36, 49, 64, 81, 100] #支持连接操作
[1, 342, 223, 'India', 'Fedora', 36, 49, 64, 81, 100]
>>> a = ['ShiYanLou', 'is', 'cool'] #检验某个元素是否在列表中
>>> 'cool' in a #非常简单的操作
True
>>> 'Linux' in a
False
>>> len(a) #获得长度
3
#列表允许嵌套
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]] #感觉像是二维数组
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
#range生成等差数列
>>> range(1, 5)
range(1, 5)
>>> list(range(1, 5))
[1, 2, 3, 4]
>>> list(range(1, 15, 3)) //以3为间隔
[1, 4, 7, 10, 13]
>>> list(range(4, 16, 2)) //特别注意,左闭右开
[4, 6, 8, 10, 12, 14]
#列表支持append操作
>>> a = [23, 45, 1, -3434, 43624356, 234]
>>> a.append(45)
>>> a
[23, 45, 1, -3434, 43624356, 234, 45]
#insert操作
>>>a.insert(0, 1) # 在列表索引 0 位置添加元素 1
>>> a
[1, 23, 45, 1, -3434, 43624356, 234, 45]
#count操作
>>> a.count(45) #列表中45出现的个数
2
#remove操作
>>> a.remove(234)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 45]
#reverse操作
>>> a.reverse()
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111]
#以一个列表扩展另一个列表
>>> b = [45, 56, 90]
>>> a.extend(b) # 添加 b 的元素而不是 b 本身
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, 45, 56, 90]
#sort操作
>>> a.sort()
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356]
#del关键字,注意他与remove的不同
>>> del a[-1]
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111]
#列表中pop()的用法
a.pop() #弹出最后一个元素
a.pop(0) #弹出第一个元素
Loops: You can loop over the elements of a list like this:
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print animal
# Prints "cat", "dog", "monkey", each on its own line.
如果想获得每一个元素的索引在循环中,可以用enumerate
animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
print '#%d: %s' % (idx + 1, animal)
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
列表推导式
列表推导式为从序列中创建列表提供了一个简单的方法。
#列表创建的一般方式
>>> squares = []
>>> for x in range(10):
... squares.append(x**2) # x**2为x的二次方
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#列表推导式
squares = [x**2 for x in range(10)] #[]开头为表达式
同时列表推到式可以包含条件:
nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print even_squares # Prints "[0, 4, 16]"
更复杂一点的例子:
#其中,(x,y)为所要生成的数据 (神奇)
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
#上式等同于
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
元组
元组是由数个逗号分割的值组成
>>> a = 'Fedora', 'ShiYanLou', 'Kubuntu', 'Pardus'
>>> a
('Fedora', 'ShiYanLou', 'Kubuntu', 'Pardus')
>>> a[1]
'ShiYanLou'
>>> for x in a:
... print(x, end=' ') #这样会输出成一行
...
Fedora ShiYanLou Kubuntu Pardus
>>> x, y = divmod(15,2) #divmod,第一个参数为结果,第二个为余数
>>> x
7
>>> y
1
#注意元组不可改变,不能删除,修改等
字典
字典是是无序的键值对(key:value)集合,等同于c++中的unordered_map
哈希表。同一个字典内的键必须是互不相同的。
其形式为 :键:值
#创建字典
>>> data = {'kushal':'Fedora', 'kart_':'Debian', 'Jace':'Mac'}
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian'}
>>> data['kart_'] #用键值,搜索值
'Debian'
#添加新的键值
>>> data['parthan'] = 'Ubuntu'
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
#del删除键值对
>>> del data['kushal']
>>> data
{'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'
#查询是否在字典中,查询的是键值,其实和c++类似
>>> 'ShiYanLou' in data
False
#遍历字典,使用字典的 items()方法
>>> data
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
>>> for x, y in data.items(): #注意
... print("{} uses {}".format(x, y))
...
Kushal uses Fedora
Jace uses Mac
kart_ uses Debian
parthan uses Ubuntu
#试图索引一个不存在的键将会抛出一个 keyError 错误。
#可以使用 dict.get(key, default) 来索引键
>>> data['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>> data.get('foo', 0) #dict.get(key,default)索引键值
0
#需要同时遍历两个序列类型,你可以使用 zip() 函数。
>>> a = ['Pradeepto', 'Kushal']
>>> b = ['OpenSUSE', 'Fedora']
>>> for x, y in zip(a, b):
... print("{} uses {}".format(x, y))
...
Pradeepto uses OpenSUSE
Kushal uses Fedora
Loops: It is easy to iterate over the keys in a dictionary:
这里遍历的是键值。
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal in d: #key
legs = d[animal] #value
print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
如果要获得键值对,可以使用iteritems
方法:
d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.iteritems():
print 'A %s has %d legs' % (animal, legs)
# Prints "A person has 2 legs", "A spider has 8 legs", "A cat has 4 legs"
字典的解析式
同列表一样,非常的简单:
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print even_num_to_square # Prints "{0: 0, 2: 4, 4: 16}"
集合
集合,也就是没有顺序的,同时所有的元素都不相同的集合。A set is an unordered collection of distinct elements,用英文更好的表达其含义。集合同样是用花括号创建:
animals = {'cat', 'dog'}
print 'cat' in animals # Check if an element is in a set; prints "True"
print 'fish' in animals # prints "False"
animals.add('fish') # Add an element to a set
print 'fish' in animals # Prints "True"
print len(animals) # Number of elements in a set; prints "3"
animals.add('cat') # Adding an element that is already in the set does nothing
print len(animals) # Prints "3"
animals.remove('cat') # Remove an element from a set
print len(animals) # Prints "2"
集合的循环很列表一致:
animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
print '#%d: %s' % (idx + 1, animal)
# Prints "#1: fish", "#2: dog", "#3: cat"