一、python编译方式
1.在线Python编译器
http://www.compileonline.com/execute_python_online.php
2.交互式编程
直接在终端命令行输入 python命令即可启动交互式编程。
[root@79 Desktop]# python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
[root@79 ~]# ipython
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
IPython 3.2.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: exit
3.脚本式编程
通过脚本参数调用解释器开始执行脚本,直到脚本执行完毕。以.py为扩展名
[root@79 ~]# cat hello.py
#!/usr/bin/python
# -*- coding: UTF-8 -*- ##中文可读
print "Hello,Python!"
- #!/usr/bin/python : 是告诉操作系统执行这个脚本的时候,调用 /usr/bin 下的 python 解释器;
- #!/usr/bin/env python(推荐): 这种用法是为了防止操作系统用户没有将 python 装在默认的 /usr/bin 路径里。当系统看到这一行的时候,首先会到 env 设置里查找 python 的安装路径,再调用对应路径下的解释器程序完成操作。
1.直接用python执行
[root@79 ~]# python hello.py
Hello,Python!
2.在终端输入命令解释器+执行文件
将命令解释器路径写在脚本内,用./ 命令执行。
[root@79 ~]# chmod +x hello.py
[root@79 ~]# ./hello.py
Hello,Python!
二、Python基本要素
python标示符
- 字母,数字,下划线,不能以数字开头。
- 区分大小写
- 以单下划线开头表示不能直接访问的类属性,需要通过类提供的接口进行访问,不能用from xxx import * 而导入
- 以双下划线开头代表类的私有成员
- 双下划线开头和结尾的代表特殊方法专用的标识
- python可以统一行显示多条语句,方法是用分号分开;
python 保留字符
- 这些保留字不能用作常数或变数,或任何其他标识符名称。
- 所有 Python 的关键字只包含小写字母。(具体可搜索)
行和缩进
- 学习 Python 与其他语言最大的区别就是,Python 的代码块不使用大括号 {} 来控制类,函数以及其他逻辑判断。python 最具特色的就是用缩进来写模块。
- 缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。
- 错误说明:IndentationError: unindent does not match any outer indentation level错误表明,你使用的缩进方式不一致,有的是 tab 键缩进,有的是空格缩进,改为一致即可。
多行语句
Python语句中一般以新行作为为语句的结束符。
使用斜杠( \)将一行的语句分为多行显示。
total = item_one + \
item_two + \
item_three
语句中包含 [], {} 或 () 括号就不需要使用多行连接符。
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Python 引号
Python 可以使用引号( ’ )、双引号( ” )、三引号( ”’ 或 “”” ) 来表示字符串,引号的开始与结束必须的相同类型的。
其中三引号可以由多行组成,编写多行文本的快捷语法,常用于文档字符串,在文件的特定地点,被当做注释。
Python空行
函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。
空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。
执行脚本参数传递
[root@79 ~]# cat hello.py
#!/usr/bin/python
import sys
print sys.argv
sys.argv 用来获取命令行参数
运行命令,执行结果:
[root@79 ~]# ./hello.py 'Vincent'
['./hello.py', 'Vincent']
sys.argv[0] 代表文件本身路径,所带参数从 sys.argv[1] 开始。
三、Python语句
if条件判断语句
i=int(raw_input("Value i="))
if (i==2):
print "YES"
else:
print "NO"
while循环
i=int(raw_input("Value i:"))
while (i!=2):
print "i doesnt equal 2"
i+=1 ##此行为了能够跳出循环
for循环
a=[1,2,3,5]
##list=('zhangsan','lisi',2,'nihao') ##元组用法
for item in a:
print item,
print a[0] ##输出第一个元素
print a[2:] ##输出第二个之后的元素
print a[:2] ##输出前两个元素
a[3]=7 ##更改元素内容
print a
1,2,3,5
1
[3, 5]
[1, 2]
[1, 2, 3, 7]
四、一些常用函数
range()函数
数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。
for i in range(5):
print i, ##添加,可以使输出不换行
0 1 2 3 4
同时,range()函数可以设置歩长,eg:
list(range(0, -10, -1)) ##range(0,-10)以-1为步长
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
len()函数
返回对象(字符、列表、元组等)长度或项目个数。
print(len(range(5)))
输出的结果就是:5
enumerate()函数
用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
list=[1,345,657]
for index,value in enumerate(list):
print index,value
这个的输出结果是:
0 1
1 345
2 657
3 68
In [3]: seasons=['Spring','Summer','Fall','Winter']
In [4]: list(enumerate(seasons))
Out[4]: [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
列表解析
squared=[ x ** 2 for x in range(5)]
print squared
输出:[0, 1, 4, 9, 16]
sqdEvens=[x ** 2 for x in range(8) if not x % 2]
print sqdEvens
输出:[0, 4, 16, 36]
open()函数
返回的是一个文件对象,类似的操作有:close(),readlines(),下面是具体用法。
[root@79 Desktop]# echo "OPEN() Function" > file
In [1]: f = open('file')
In [2]: f.read()
Out[2]: 'OPEN() Function\n'
split()函数
Sentence = 'Adorable Beautiful Cute Decent Elegant'
print Sentence.split()
print Sentence
['Adorable', 'Beautiful', 'Cute', 'Decent', 'Elegant']
Adorable Beautiful Cute Decent Elegant
函数“装饰器”
其实就是函数嵌套,将初始函数作为内部函数,进行增添新的功能模块或者函数,拼接成一个新的函数。
下面是一个简单的示例:
def PRINT():
print "WIND----"
def KEKE():
print "WHO ARE YOU"
def PRINT_PLUS(func,func2):
def inner():
print "WEATHER~~~~~"
func()
func2() ##就调用了上面两个函数而已~~~
return inner
a = PRINT_PLUS(PRINT,KEKE)
a()
下面再来两个例子:
def outer(func):
def inner(*args): ##多个无名参数
print "sada"
func(*args)
return inner
@outer ##相当于CCCC = outer(CCCC)
def CCCC(name, age):
print "The age of %s is %d " % (name, age)
CCCC('Vincnet', 12)
sada
The age of Vincnet is 12
判断用户成绩是否合格:
def outer(func):
def inner(name, score1):
if score1 > 60:
score1 = "SUCCESS"
else:
score1 = "FAILED"
func(name, score1)
return inner
@outer
def Score(name, score):
print "The score level of %s is %s" % (name, score)
Score('Vincent',90)
The score level of Vincent is SUCCESS
以上列举了一些Python中的内置函数,详情可参考:
Python函数传送门
另外,需要自定义函数的话,需要用到关键字def。
def hello():
print 'Hello,World'
hello()
Hello,World
五、列表、元组、字典
列表
I = [12,'321',432] ##定义列表
print I[1]
print type(I[0]) ##显示元素类型
I.append('as') ##添加列表元素
print I
del I[2] ##删除列表元素
# I.remove(432)
print I
b = ['b','c']
I.extend(b) ##拼接多项列表元素
I.count('32') ##统计元素出现次数
I.insert(1,'c') ##插入元素
I.reverse() ##反转元素顺序
I.sort() ##按字符串首个字符ASCII排序
print sorted(I) ##逆序输出,不改变元组
I.sort(reverse=True) ##逆序排列
c = I.pop(2)
321
<type 'int'>
[12, '321', 432, 'as']
[12, '321', 'as']
[12, '321', 'as', 'b', 'c', 'c']
eg:输出200内的完全平方数保存到列表中
List = []
for values in range(1,200):
if (values ** 0.5) == int(values ** 0.5):
List.append(values)
print List
元组
num_tuple = (1,2,'21') ##定义元组
print type(num_tuple)
num_tuple1 = (1)
print type(num_tuple1)
print type(list(num_tuple))
num_list = [1,3,'de']
print type(tuple(num_list))
<type 'tuple'>
<type 'int'>
<type 'list'>
<type 'tuple'>
字典
dictionary ={'Name':'瑞克','Job':'Scientist'}
print dictionary
print dictionary['Job']
dictionary['Job'] = 'Nuts'
dictionary.pop('Name')
print dictionary
print len(dictionary)
{'Job': 'Scientist', 'Name': '\xe7\x91\x9e\xe5\x85\x8b'} ##Python2.7不支持中文
Scientist
{'Job': 'Nuts'}
1
列表,元组,字典之间可以互相潜逃,
例如:
dictionary ={'Name':'Rick','Job':'Scientist'}
dictionary1 ={'Name':'Morty','Job':'Boy'}
D_L = [dictionary,dictionary1] ##列表嵌套字典
for i in D_L: ##遍历列表
print i
for i in range(len(D_L)): ##遍历字典
print "%s --> %s" % (i,D_L[i])
{'Job': 'Scientist', 'Name': 'Rick'}
{'Job': 'Boy', 'Name': 'Morty'}
0 --> {'Job': 'Scientist', 'Name': 'Rick'}
1 --> {'Job': 'Boy', 'Name': 'Morty'}
列表,元组,字典区别:
1.列表,字典可更改
元组不可更改
2.列表,元组有序
字典无序
六、字符串管理
1.截取字符串:
截取方式与元组中元素处理类似
In [1]: num='asddfghj' ##字符串创建方式:单引号,双引号,三引号
In [3]: num[-1] ##逆序从-1开始
Out[3]: 'j'
In [7]: num[:] ##输出全部字符
Out[7]: 'asddfghj'
In [8]: num[1:5:2] ##索引1~5,步长为2
Out[8]: 'sd'
In [9]: num[-3]
Out[9]: 'g'
In [10]: num[-1::-1] ##逆序输出
Out[10]: 'jhgfddsa'
In [11]: num[-1:2:-1]
Out[11]: 'jhgfd'
In [12]: num[2::2]
Out[12]: 'dfh'
2.字符串拼接:
str1 = "Linus Torvald"
print "UPDATE:" , str1[:5]+'\tTechTips' ##\t 横向制表符
UPDATE: Linus TechTips
3.判断字符是否存在/统计字符频数:
print 'rv' in str1 ##'rv'字符是否在str1中出现,返回值为boolean类型
True
In [10]: str.count('o')
Out[10]: 2 ##统计'o'出现次数
4.字符串内置函数:
函数名 | 实现功能 |
---|---|
str.isalnum() | 判断是否都是字母或数字 |
str.isalpha() | 判断是否都是字母 |
str.isdigit() | 判断是否都是数字 |
str.islower() | 判断是否都是小写 |
str.isspace() | 判断是否都是英文空格 |
str.istitle() | 判断是不是都是标题(有大小写) |
str.isupper() | 判断是不是都为大写字母 |
str.startswith() | 判断字符串是否以给定字符开头 |
str.endswith() | 判断字符串是否以给定字符结尾 |
5.字符串查找:
str.find(sub[,start[,end]])
- 判断sub是否在str中,存在返回索引值,不存在返回-1.
str.index(sub[,start[,end]])
- 与find方法函数功能相同,如果sub不存在时抛出ValueError异常;
In [2]: str ="""Hello world """
In [5]: str.find('hello',0,6) ##未查找到则返回-1
Out[5]: -1
In [6]: str.find('ello',1,6)
Out[6]: 1 ##返回值为查找字符的索引
In [7]: str.index('ello',1,6)
Out[7]: 1
6.字符串内置方法:(BIF-built-in function)
cmp(x, y) -> integer ##比较a和b的大小
In [11]: cmp(21,22)
Out[11]: -1
In [12]: cmp(21,2)
Out[12]: 1
In [13]: cmp(12.1,12.1)
Out[13]: 0
len(object) -> integer ##返回字符串长度
In [14]: len(str)
Out[14]: 12
max(str) , min(str) 分别表示:查找字符串str中最大最小ASCLL值的字符
In [15]: max(str)
Out[15]: 'w'
In [16]: min(str)
Out[16]: ' '
七、Python程序案例
1.打印菱形
LINE = int(raw_input("Lines:"))
for i in range(1,2*LINE): ##1到2n-1行
a=LINE-abs(i-LINE)
print " " * abs(LINE-i), ##每行有有|n-i|个空格 ##* 重复输出字符串
print "*" * (2*a-1) ##每行有2*(n-|i-n|)-1个星星
Lines:4
*
***
*****
*******
*****
***
*
2.浮点型变量输出处理
test=12
print 'my test is %07d' % test
price1=62.231
price2=62.2
print 'Price1: %.2f Price2: %f' % (price1,price2)
scale=0.32
print 'Scale: %.2f %%' % (scale*10)
print '%d ' % price2
my test is 0000012
Price1: 62.23 Price2: 62.200000
Scale: 3.20 %
62
3.猜数字游戏
#_*_ coding=UTF-8 _*_
from random import randint
import os
import datetime
game_times = 0 # 游戏次数
min_times = 0 # 历次游戏最小多少轮猜对
total_times = 0 # 历次游戏总共猜的轮数
game_save_file = "/mnt" + os.sep + "game"
scores = {} # 用字典保存不同玩家的记录
if os.path.exists(game_save_file):
player = raw_input("Player Name:")
f = open(game_save_file, 'r')
lines = f.readlines()[1:] # 文件第一行是时间
f.close()
for line in lines:
s = line.split()
scores[s[0]] = s[1:]
score = scores.get(player)
if score is None:
score = [0, 0, 0]
game_times = int(score[0])
min_times = int(score[1])
total_times = int(score[2])
else:
print("The Game file has been lost.Please create one firest!" + game_save_file)
exit(0)
if game_times > 0:
avg_times = float(total_times) / game_times # 平均猜对的轮数
else:
avg_times = 0
print("**********Guess Game(1-100)*********")
print("%s,You have played %d times,At least %d times to get the right answer,Average %.2f times" % (player, game_times, min_times, avg_times))
starttime = datetime.datetime.now()
timelabel = starttime.strftime("%Y-%m-%d %H:%M:%S %p\n")
num = randint(1, 100) # 电脑随机产生一个数
times = 0 # 记录本次游戏猜的轮数
print("Guess what I think?")
bingo = False
while not bingo:
times += 1
ans = int(input())
if ans < num:
print("too small!")
elif ans > num:
print("too big!")
else:
print("Bingo!")
bingo = True
# 猜对即退出游戏,并保存游戏记录到本地
if game_times == 0 or times < min_times: # 如果是第一次玩或者是times小于历史记录则更新
min_times = times
total_times += times # 游戏总轮数增加
game_times += 1 # 游戏总次数增加
scores[player] = [str(game_times), str(min_times), str(total_times)]
res = ""
# 本例的做法是把全部玩家的记录覆盖一遍
for i in scores:
line = i + " " + " ".join(scores[i]) + "\n"
res += line
res = timelabel + res
f = open(game_save_file, 'w')
f.write(res)
f.close()
Player Name:asd
**********Guess Game(1-100)*********
asd,You have played 0 times,At least 0 times to get the right answer,Average 0.00 times
Guess what I think?
56
too big!
34
too big!
15
too small!
26
Bingo!