本节所讲内容

 

python基础

公开发布时间1991年

是一种面向对象、解释型计算机程序设计语言由Guido van Rossum于1989年发明第一个公开发行版发行于1991年。

 

优点

简单                                        Python是一种代表简单主义思想的语言。

易学                                        Python极其容易上手因为Python有极其简单的说明文档

速度快                                     Python的底层是用 C 语言写的很多标准库和第三方库也都是用                                           C 写的运行速度非常快。

免费开源                                  Python是FLOSS自由/开放源码软件之一

轻松拿高薪

 

Python用来做什么

软件开发游戏、搜索、嵌入式、网站、C/S软件

系统管理脚本、运维自动化工具

 

编程要求

缩进统一

python中的语法格式没有结束符统一通过缩进进行确定不同的执行流程和语句同一流程和语句应保持缩进统一

 

在Linux系统中使用python首先确定python软件已经安装

[root@localhost ~]# rpm -qf`which python`
python-2.7.5-16.el7.x86_64


 

如果没有安装可执行以下命令进行安装

[root@localhost ~]# yum -yinstall python


 

win7x64位 python 2.7.10

链接http://pan.baidu.com/s/1sjuv5rn密码i5su

 

python源码包下载地址

https://www.python.org/

wKiom1aP2bGhkoWrAAFraBoS21Y812.png

 

1、交互式解释器

[root@localhost ~]# python
Python 2.7.5 (default, Feb 112014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat4.8.2-13)] on linux2
Type "help","copyright", "credits" or "license" for moreinformation.
>>> print"Hello,world!"
Hello,world!


 

wKiom1aP2YvBgj1aAADFF6EFX1c195.png

 

退出方法
>>> exit()
或者
>>> quit()
或者
Ctrl+D


 

2、算法的使用

基本运算符 +  - *  /

特殊运算符

//取整运算

%取余运算

**幂值运算

 

>>> 2 + 2
4
>>> 7 // 3                          #7整除3得2
2
>>> 7 % 3                          #7除以3余数为1
1
>>> 7 ** 3                          #7的3次幂343
343


 

注乘法运算的特例

>>> 1 * 10
10
>>> '1' * 10
'1111111111'


 

小数运算

如果参与运算的两个数中有一个为小数那么结果也是小数

>>> 3.0 * 2.0
6.0
>>> 3.0 / 2
1.5
>>> 3.0 - 2.0
1.0


 

3、变量的赋值

变量名可以包括字母数字和下划线变量不能以数字开头

与shell脚本不同python在引用变量时不需要加上$符号便可以直接引用

>>> x = 2
>>> x * 2
4


 

对于字符串的赋值需要加上引号

>>> rm =ZhaoXiangJie
Traceback (most recentcall last):
  File "<stdin>", line 1, in<module>
NameError: name'ZhaoXiangJie' is not defined
>>> rm ='ZhaoXiangJie'
>>> rm
'ZhaoXiangJie'
>>> RM=rm
>>> RM
'ZhaoXiangJie'
>>> RM='rm'
>>> RM
'rm'


 

4、语句操作

>>> print 2 * 2
4


 

5、获取用户输入

>>> x =input("x: ")
x: 33
>>> y =input("y: ")
y: 44
>>> print x * y
1452


 

6、函数

函数就像小程序一样可以用来实现特定的功能。Python中有很多函数用户也可以自定义函数

常见函数

pow       幂值运算

abs       绝对值运算

round   四舍五入

floor    返回值下舍整数

ceil         返回值上入整数

sqrt        平方根运算

int          取整运算

 

>>> pow(7,3)
343
>>> abs(-10)
10


 

对于不能直接调用的函数可以插入对应的模块进行调用

>>> import math                                    #插入math模块
>>> math.floor(32.9)                               #使用floor函数
32.0
>>> int(math.floor(32.9))
32


 

如果不希望每次调用函数的时候都写上模块的名称可以结合from进行实现

>>> from mathimport sqrt
>>> sqrt(9)
3.0


 

也可以通过变量来引用函数

>>> foo = math.sqrt
>>> foo(9)
3.0


 

如果模块的名称比较长使用起来不方便也可以通过以下方法进行设置

>>> from math importsqrt as a
>>> a(9)
3.0


 

同时导入多个模块

>>> import sys,os


 

7、字符串的引用

单引号和双引号都可以引用字符串使用时应避免出现混乱

>>>"Hello,world!"
'Hello,world!'
>>> 'Hello,world!'
'Hello,world!'
>>>'"Hello,world!" she said'
'"Hello,world!" shesaid'


 

针对以下这种情况显然使用单引号是不行的

>>> 'I'm a boy'
  File "<stdin>", line 1
    'I'm a boy'
       ^
SyntaxError: invalid syntax
>>> "I'm aboy"
"I'm a boy"
 
或者通过 \ 对单引号进行转义
>>> 'Let\'s go'
"Let's go"


 

如果要引用数值可以通过函数str 和 repr来实现

repr      返回值的字符串表示形式

str        将值转换为字符串

 

>>> police = 110
>>> print "报警请拨" + police                          #直接引用会报错
Traceback (most recent calllast):
  File"<stdin>", line 1, in <module>
TypeError: cannot concatenate'str' and 'int' objects
 
>>> print "报警请拨" + repr(police)
报警请拨110
 
>>> print "报警请拨" + str(police)
报警请拨110


 

长字符串的引用

如果需要写一个非常非常长的字符串它需要跨多行可以使用三个引号代替普通引号

>>> print '''This isa very long string.
... It continues there
... And it's not over yet
... "Hello,world!"
... Still here.'''
This is a very long string.
It continues there
And it's not over yet
"Hello,world!"
Still here.


 

原始字符串的使用

原始字符串对于反斜线并不会特殊对待。原始字符串以r开头

例打印windows系统的C:\nowhere这样的路径

>>> print'C:\nowhere'
C:
owhere


当然可以通过转义符 “\”进行转义

>>> print'C:\\nowhere'
C:\nowhere


但是相对于一个更长的目录这个时候就很不方便

>>> print'C:\\Program Files\\fonrd\\foo\\bar\\baz\\frozz\bozz'
C:\ProgramFiles\fonrd\foo\bar\baz\frozozz


通过原始字符串的方式可以很轻松的实现

>>> print r'C:\ProgramFiles\fonrd\foo\bar\baz\frozz\bozz'
C:\ProgramFiles\fonrd\foo\bar\baz\frozz\bozz


 

8、input和raw_input 的比较

input会默认用户输入的是合法的Python表达式而raw_input会把所有的输入当做原始数据进行处理

例一使用input进行输入时输入的代码内容需加上引号才能进行执行

>>> name =input("What is your name? ")
What is your name? zxj
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
  File "<string>", line 1, in<module>
NameError: name 'zxj' is notdefined
>>> name =input("What is your name? ")
What is your name? 'zxj'
>>> print name
zxj


 

例二使用raw_input进行输入时输入的代码内容不需要加引号

>>> name =raw_input("What is your name? ")
What is your name? zxj
>>> print"Hello, "  +  name + "!"
Hello, zxj!


 

用Python编写脚本

首行加上python命令的执行路径可以使python脚本直接就能执行不需要通过python  脚本名这种方式也能执行当然前提是脚本要有x权限脚本的后缀名为 .py

脚本中#开头为注释行

 

[root@localhost ~]# vimhello.py
#!/usr/bin/python
name = raw_input ("Whatis your name ?")
print 'Hello,' + name + '!'


 

执行脚本文件

方法一python  + 脚本名

[root@localhost ~]# pythonhello.py
What is your name?RM
Hello, RM!


 

方法二给脚本加上x权限直接执行

[root@localhost ~]# chmod u+xhello.py
[root@localhost ~]# ./hello.py
What is your name?MK
Hello, MK!


 

在脚本中如果需要同时引用很多变量时可以通过%s 和%d 来实现

%s 用来引用字符串

%d 用来引用数字

 

实战

1、写一个统计人员信息的python脚本

#!/usr/bin/env python
name = raw_input('your name:')
age = raw_input('your age: ')
job = raw_input('your job: ')
 
print"***********************"
print "*****  your info *****"
print"***********************"
 
#print '\t'"Name: "+ name
#print '\t'"Age: " +age
#print '\t'"Job: " +job
print '''\tName: %s
\tAge: %s
\tJob: %s''' % (name,age,job)


 

2、python中插入tab模块实现tab自动补全

脚本内容

[root@xuegod163 ~]# vim tab.py
#!/usr/bin/python
# python startup file
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion 
readline.parse_and_bind('tab:complete')
# history file 
histfile = os.path.join(os.environ['HOME'],'.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file,histfile)
del os, histfile, readline,rlcompleter


 

插入tab模块

>>> import tab
>>> import sys
>>> sys.
sys.__class__(              sys.builtin_module_names    sys.last_type(
sys.__delattr__(            sys.byteorder               sys.last_value


 

查询python版本

>>> sys.version_info
sys.version_info(major=2,minor=7, micro=5, releaselevel='final', serial=0)


扩展

插入模块时出现以下报错信息原因tab模块的路径不正确

>>> import tab
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
ImportError: No module namedtab
 
解决方法
>>>sys.path.append('/etc/sysconfig/network-scripts/')
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
NameError: name 'sys' is notdefined
>>> import sys
>>>sys.path.append('/etc/sysconfig/network-scripts/')


 

>>> sys.path
['','/usr/lib64/python27.zip', '/usr/lib64/python2.7','/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk','/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload','/usr/lib64/python2.7/site-packages','/usr/lib64/python2.7/site-packages/gtk-2.0','/usr/lib/python2.7/site-packages', '/etc/sysconfig/network-script/','/etc/sysconfig/network-scripts/']


 

>>> import tab
>>> sys.
sys.__class__(              sys.builtin_module_names    sys.last_type(
sys.__delattr__(            sys.byteorder               sys.last_value


 

os.system可以直接调用shell中的命令

>>> import os
>>> os.system('uname-r')
3.10.0-229.el7.x86_64


 

学习过程中如果问题请留言。更多内容请加
学神IT-linux讲师-RM老师QQ2805537762
学神IT-戚老师QQ3341251313
学神IT-旭斌QQ:372469347
学神IT教育RHEL7交流群468845589