Python 探坑
@ Hanks
-
简单、易学、免费、开源 。
-
高层语言
-
可移植性
-
扩展性
-
丰富的库
- 运行慢
Hello world
# Python 2
print 'Hello World!'
# Python 3
print('Hello World!')
语法
print "hello world"
# data type
a = 1
b = 1.0
c = "xitu.io"
d = False and True
# muilt-lines
s = """ The big brown fox
quickly jump ed over the wall
and ran away.
"""
print r"Use \n fox new line" # raw string
print s
print 40 + 42.67
print int(67.879)
print float(12)
print long(345353524253453453453)
print "" + str(2)
# list tuple dict
e = [a,b,c,d]
f = (a,b,c,d,e)
xiaoming = {'name':'XiaoMing', 'age':10, 'weight':12.3, 'like':['sport','music'] }
print e # [1, 1.0, 'xitu.io', False]
print f # (1, 1.0, 'xitu.io', False, [1, 1.0, 'xitu.io', False])
print xiaoming # {'age': 10, 'name': 'XiaoMing', 'weight': 12.3, 'like': ['sport', 'music']}
e[0] = 99
print e[0] # 99
print 1 in e # True
xiaoming['like'].append('sleep')
f[4][0] = 199
print f # (1, 1.0, 'xitu.io', False, [199, 1.0, 'xitu.io', False])
# if for while
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print name
# 0 ~ 20
nums = [ i*2 for i in range(21) ]
print nums
a,b = b,a # swap
for key,value in xiaoming.items():
print key
print value
# function
def my_abs(x):
if x >= 0:
return x
else:
return -x
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
def calc(*numbers): # numbers is tuple
sum = 0
for n in numbers:
sum += n
print sum
return sum
calc(1, 3, 5, 7)
def person(name, age, **kw): # kw is dict
print 'name:', name, 'age:', age, 'other:', kw
person('Michael', 30)
person('Bob', 35, city='Beijing')
# class
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print '%s: %s' % (self.name, self.score)
# def __str__(self):
# return 'Student object (name: %s)' % self.name
# def __len__(self):
# return 100
bart = Student('Bart Simpson', 59)
bart.print_score()
print bart
# print len(bart)
# 1
a=[2,3,4,5]
b=[2,5,8]
tmp = [val for val in a if val in b]
print tmp
# 2
print list(set(a).intersection(set(b)))
Python
By Hanks
Python
- 8,192