python基础
print("Hello world!!!")
Hello world!!!
# string format
template = '{0:.2f} {1:s} worths {2:d} USD'
print(template.format(68, "RMB", 10))
print(template.format(112, "JPY", 1))
68.00 RMB worths 10 USD
112.00 JPY worths 1 USD
# dynamic reference
# python中变量的类型由数决定,变量无需声明即可赋值,变量的数据类型可动态改变
a = 1.4
a = "abc"
# strong type
a = 1.4
b = 5
c = "abc"
# type查看变量类型
print(type(a))
print(type(b))
print(type(c))
print(a + b)
try: print(a + c)
except TypeError as e: print(e)
print(str(a) + c)
6.4
unsupported operand type(s) for +: 'float' and 'str'
1.4abc
# python 定义函数
# 判断是否可以迭代
# duck type
def isIter(obj):
try:
iter(obj)
return True
except:
return False
print(isIter("string"))
print(isIter([1, 3, 6, 3]))
print(isIter(5))
True
True
False
# division 小数除法/ 整数除法//
print(5 / 3)
print(5.0 / 3.0)
print(5 // 3)
print(5.0 // 3.0)
1.6666666666666667
1.6666666666666667
1
1.0
# double v.s. int
# python中int无限大
#t = 2.0
t = 2
try: print(t**9999)
except OverflowError as e: print(e)
9975315584403791924418710813417925419117484159430962274260044749264719415110973315959980842018097298949665564711604562135778245674706890558796892966048161978927865023396897263382623275633029947760275043459096655771254304230309052342754537433044812444045244947419004626970816628925310784154736951278456194032612548321937220523379935813492726611434269080847157887814820381418440380366114267545820738091978190729484731949705420480268133910532310713666697018262782824765301571340117484700167967158325729648886639832887803086291015703997099089803689122841881140018651442743625950417232290727325278964800707416960807867294069628547689884559638900413478867837222061531009378918162751364161894635355186901433196515714066620700812097835845287030709827171162319400624428073652603715996129805898125065496430120854170403802966160080634246144248127920656422030768369475743557128157555544872757101656910101465820478798232378005202922920783036022481433508257530960315502093211137954335450287303208928475955728027534125625203003759921130949029618559027222394036453197621274169610991353702236581188380423306516889353019901706598566746827311350281584968727754120890486405491645657201785938762384254928638468963216610799699938443330404184418919013821641387586136828786372392056147194866905430803711626645987406560098802089140982848737949082265629217067979931392065064092703141738324544345260523790441307911980992885061203522165291537934519659802301702486578291604336052956650451876411707769872697198857628727645255106155473660805376737412870387636993174149249170378468977823319310937284749639508286051850682216567908607155895699111491922923667220135482091425502536463874182275289317250550426493906194736964349770417173079403521979559492907572889588571809849364065729741891601040737491085929005694535614125452913408718110288737960708826857843862807452291452496230514315040767791654065050993837928117171769477704587811700422443763081321784324416759731860188646620047228123461627175200339013636918877688203363449318120518745705483359278525379549050123394940089135962976690641210977014151379704224477507338334194848998443120818156688196951686727900703818370938855527692112869749555093234109848290825742565247111184973857381534577734108841438100181388628861890682665805598405640396334740943600649321830384275819930267301148935778758973692623184723461543947132974108504025560161182748144084517869560684169196795878209366925255485135806957719795495799077327208668155828468015561124968984999613390866179011555931322287649567879087504099919618142307624940544480116122181086885809043178507734242029311164896426937811743278220268481311009481785514406180783756271669151635014548834325284278578752758363759449597064855668845074958090657585772003864325286594778725460165092652423556909157703662026659519231042018210881851955775319894500371426836098140451738987266660234184397934290118976109314560040371409775658974078812224149259230754852444013637360787344065797375204866057540249095227901708413474893570658031605343195755840887152396298354688
# if-else-if
#a = None
#a = True
a = False
if a is None:
print("Null")
elif 0 < a < 10:
print("True")
else:
print("False")
False
# indentation 通过缩进控制代码
if True:
print("True")
else:
print("False")
print("End")
if True:
print("True")
else:
print("False")
print("End")
True
End
True
# for loop python中的for循环
# more from itertools
for s in "string":
print(s)
for i in range(10):
print(i)
for i in range(1, 10, 2):
print(i)
s
t
r
i
n
g
0
1
2
3
4
5
6
7
8
9
1
3
5
7
9
# while loop
i = 2
while True:
i = i * i
if i > 1000000: break
print(i)
4
16
256
65536
# list python的列表是可修改的
l = [0, 1, 2, 3]
print(l)
l.append("abc")
print(l)
# 用新列表扩展原来的列表(追加)
l.extend([9, 8, 7])
print(l)
# 修改下标1-4的列表值
l[1:4] = [9, 8, 7]
print(l)
# 修改后三个
l[-3:] = [1, 2, 3]
print(l)
# 修改前两个
l[:2] = [1,2]
print(l)
# 删除第4个
l.pop(4)
print(l)
[0, 1, 2, 3]
[0, 1, 2, 3, 'abc']
[0, 1, 2, 3, 'abc', 9, 8, 7]
[0, 9, 8, 7, 'abc', 9, 8, 7]
[0, 9, 8, 7, 'abc', 1, 2, 3]
[1, 2, 8, 7, 'abc', 1, 2, 3]
[1, 2, 8, 7, 1, 2, 3]
# tuple python的tuple不可修改,也不能增删
# Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。
# 元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可
t = (1, 2, 3, 4)
try: t[2] = 9
except TypeError as e: print(e)
try: t.apppend(5)
except AttributeError as e: print(e)
try: t.pop(1)
except AttributeError as e: print(e)
print(t)
'tuple' object does not support item assignment
'tuple' object has no attribute 'apppend'
'tuple' object has no attribute 'pop'
(1, 2, 3, 4)
# advance
l = [1, 4, 9, 16]
# enumerate枚举 index value
print(enumerate(l))
for i, j in enumerate(l):
print(i, j)
# python 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)
print(range(len(l))) # range(0, 4) 即默认start为0,stop为len(l) 即创建从0到4的一组数 0 1 2 3
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组tuple,然后返回由这些元组组成的对象,可以节约内存
for i, j in zip(range(len(l)), l):
print(i, j)
from math import sqrt
for i, j in zip(l, map(sqrt, l)):
print(i, j)
0 1
1 4
2 9
3 16
range(0, 4)
0 1
1 4
2 9
3 16
1 1.0
4 2.0
9 3.0
16 4.0
# dictionary
d = {"a": 0, "b": 1, "c": 2}
print(d)
print(d.keys()) # 获取字典key
print(d.values()) # 获取字典value
d["a"] = 9 # 修改某值
del d["b"] # 删除某值
print(d)
try: print(d["e"])
except KeyError as e: print("key error:", e)
print(d.get("e", 9))
print(d)
{'a': 0, 'b': 1, 'c': 2}
dict_keys(['a', 'b', 'c'])
dict_values([0, 1, 2])
{'a': 9, 'c': 2}
key error: 'e'
9
{'a': 9, 'c': 2}
# advance
# python是逐行执行的,所以尽量把可用代码写在同一行里
def genList(size):
return [i*i for i in range(size)] # more efficient
def genDict(size):
return {i+1: i*i for i in range(size)} # more efficient
for op in [genList, genDict]:
print(op(5))
[0, 1, 4, 9, 16]
{1: 0, 2: 1, 3: 4, 4: 9, 5: 16}
# file read/write
with open("input.txt") as f:
for l in f:
a, b, c = l.strip().split()
print(a)
with open("output.txt", "w") as f:
f.write("message\n")
print(f.closed)
1
2
3
4
5
6
True