Skip to content

Python 学习笔记(一)【基础语法学习】

轩辕十四
Published date:
# coding: utf-8

如果想让代码中可以输入中文,必须要加上这一句。

def add_function(a, b):
    c = a + b
    print c

Python 中定义一个函数用 def 关键字,函数没有大括号,用tab空格代表方法体。

num = 100
tempC = "Number: "
print tempC + `num`
print tempC + str(num)
print tempC + repr(num)

str和repr结果都一样,区别: str是 对象类型 ;repr是 函数

print "one is %s"%num
print "tempA: %s, tempB: %s"%(tempA, tempB)

如果是两个占位符,要写在括号内,用逗号隔开。

wordsA = " this is a book "
print wordsA[0]
print wordsA[-3]

# 截取字符串
print wordsA[1:4]
print wordsA[1:] # 表示从a[1]开始,一直到字符串的最后
print wordsA[:] # 表示截取全部
print wordsA[:4] # 表示从字符串开头一直到a[4]前结束
print wordsA.strip()
print wordsA.lstrip()
print wordsA.rstrip()

strip() 去掉字符串左右的空格,lstrip() 去掉左侧的空格,rstrip() 去掉右侧的空格。

print divmod(5, 2) # 输出(2, 1)

表示5除以2,返回了商和余数

print 10 ** 2 # 100
print 9 // 2 # 4

** 幂 - 返回 x 的 y 次幂 // 取整除 - 返回商的整数部分

# 布尔运算,与、或、非
print 4 > 3 and 4 < 2 # False
print 4 > 3 or 4 < 2 # True
print not(4 < 2) # True

and ,或 or ,非 not

if 4 > 2:
    print "4 > 2"
elif 4 == 2: # 注意这里的else if
    print "4 == 2"
else:
    print "4 < 2"

python 中的 else if 写成 elif

ary = [1, 2, 3, 4]
print type(ary) # <type 'list'>

python 的数组叫做 list

ary.append("Test")
print ary
ary2 = ["Test1", "ddd"]
ary.extend(ary2)
print ary

python list 类型添加一个元素 append() ,合并两个 list extend()

print ary.count("ddd")
print ary[4:]
print ary[4]
print ary.index("ddd")
ary.insert(2, 2.3)
print ary

count() 用于计算某个元素出现的次数,这里计算 ddd 出现了几次。 index() 查看 ddd 的下标。 insert() 在指定地方插入元素。

if 2.3 in ary:
    ary.remove(2.3)
    print "2.3在list中:"
    print ary
else:
    print "2.3不在list中"

# 输出 
# 2.3在list中:
# [1, 2, 3, 4, 'Test', 'Test1', 'ddd']
ary.pop()
print ary
ary.pop(3)
print ary

# 输出
# [1, 2, 3, 4, 'Test', 'Test1']
# [1, 2, 3, 'Test', 'Test1']

pop() 删除list中的最后一个元素。 pop(3) 删除list中3这个元素,如果有多个,就删除最前面的一个。

print range(9)
print range(2, 10, 2) # step=2,每个元素等于start + i * step
print range(0, 10, 3)
print range(5, 100, 5)

print range(0, -9, -1)

range(start, stop[, step]) start:开始数值,默认为0,也就是如果不写这项,就是认为start=0 stop:结束的数值,必须要写的。 step:变化的步长,默认是1,也就是不写,就是认为步长为1。坚决不能为0

# 排序
number = [1, 4, 6, 2, 9, 7, 3]
number.sort()
print number
print sorted(number)
number.sort(reverse=True)
print number
print sorted(number, reverse=True)

reverse=True 倒序排列

power = []
for x in range(9):
    power.append(x ** 2)

在Python中,上面的代码可以改成如下形式:

print [x ** 2 for x in range(9)]

类似的,还有如下的形式:

print [n for n in range(3, 100) if n % 3 == 0] # 被3整除的正整数 

mybag = [' glass',' apple','green leaf ']              
print [one.strip() for one in mybag] # 去掉每个元素前后的空格     
weak = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
for (idx, item) in enumerate(weak):
    print "idx: " + str(idx) + "; item: " + item

list中的迭代器

dicNum = {}
print type(dicNum)
dicNum["name"] = "Tom"
dicNum[1] = "Tom"
dicNum[2] = 90
print dicNum

字典类型,用大括号表示。 也可以这样创建字典

name = (["first", "Google"], ["second", "Yahoo"])
webSite = dict(name)
print webSite		
# {'second': 'Yahoo', 'first': 'Google'}

webSiteTest = {}.fromkeys(("third", "forth"), "facebook")
print webSiteTest
# {'forth': 'facebook', 'third': 'facebook'}

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
print a		# {'three': 3, 'two': 2, 'one': 1}
print b		# {'three': 3, 'two': 2, 'one': 1}
print c		# {'three': 3, 'two': 2, 'one': 1}
print d		# {'three': 3, 'two': 2, 'one': 1}
print e		# {'one': 1, 'three': 3, 'two': 2}
dicNum.update(webSiteTest)

将 webSiteTest 合并到 dicNum。

t = 1, 3, 4, 123, "test"
# (1, 3, 4, 123, 'test')

自动封装成元组类型,元组类型是不可变的。

元组的使用:

一般认为,tuple有这类特点,并且也是它使用的情景:

set可以用{}定义;

  1. 元素没有序列,不能重复(类似于dict);
  2. 可以原处修改,但是不能通过下标的方式修改(类似于list,事实上是一种特别的set可以原处修改,另一种是不可以的);
s1 = set("qiwsir")
print s1

输出内容:set(['q', 'i', 's', 'r', 'w']) 将字符串拆开,并且没有重复的字母。

s3 = {"abc", "abc", "21", 33}
print s3

s4 = {} # 这样建立的是dict,并不是set
s6 = set(['a', 'b'])
s7 = set(['github', 'qiwsir'])
s6.update(s7)

合并s7到s6, s7不变。

print s6.pop()

从set中任意选择一个删除,并返回该值, pop() 不能有参数。

if "github" in s6:
    s6.remove("github")
print s6

想要删除特定的元素,需要使用 remove(obj) 函数。 并且obj必须在set中是存在的,否则报错。

s6.discard("github")

discard(obj) 跟remove类似,不同之处在于,如果删除的元素在set中不存在则 discard(obj) 函数什么也不做。

在Python中变量有如下特殊的赋值方式:

name, web = "qiwsir", "qiwsir.github.io" # 多个变量,按照顺序依次赋值,少了或者多了,都会报错

one, two, three, four = "good" # 拆分
Previous
Python 学习笔记(二)【文件的简单操作】