lxy777 发表于 2015-12-15 12:43:02

python基本语法

python:跨平台、面向对象的动态编程语言
发布时间:1991年
发明:guidovan rossum


python的语言特点
1、开源免费
2、脚本语言,解析执行
3、跨平台
4、简洁美观
5、一切皆对象
6、可扩展的胶水语言

解析执行原理:
1、编辑文本文件
2、意识编译字节码,形成pyc源码
3、在pvm虚拟机执行
4、在cpu执行,打印到屏幕
解析器cpython、jpython、ironpython


------------------------------------------------------------------------------------------------------------------
1、python环境准备
执行命令:python--version 打印出版本号
2、python安装
1、预安装:linux、unix、macos一般都是自带安装python
2、源码安装
3、安装包安装rpm、msi(windows)
a)、源码编译安装
wget http://python.org/ftp/python/3.3.2/pyton-3.3.2.tar.bz2
tarxjvf python-3.3.2.tar.bz2
cdpython-3.3.2
./configure
make
makeinstall
ln-s /usr/loacl/bin/python3 /usr/bin/python


3、基本语法
1、>>>print('hello')
>>>是主提示符
2、... print 'hello'   
...是辅助提示符
3、>>>exit()
退出




root@localhost#python

>>>print('hello')
hello

>>>if1 + 1 == 2: 冒号不是分号
...                print'hello'
...
hello
>>>exit()   就退出来了。


4、python的自省

>>>help(str)遇到问题可以help
>>>type('hello')
>>>isinstance('hello',str)
>>>dir(str)



5、模块导入
1、importm
   print m.plus(1,2)
2、fromm import plus
printplus(1,2)
示例:                                             m.py ,               new.py
def plus(a,b):            import m
      return a + b            print m.plus(1,2)
def plus2():               
exit()                  打印结果 3

6、导入系统模块
1、importsys.path
   from os import *
   
7、导入私有模块
1、          import sys
2、      path= '/root/dir/' 把模块的目录添加到path中,方便查找加载
3、      sys.path.append(path)   或者直接sys.path.append("root/dir/")
4、      fromm import plus2

-------------------------------------------------------------------------------------------------------------------

8、变量的使用
内建数据类型:
1、boolean--> exam_is_pass = true
2、integer--> person_number = 100
3、float    --> weight = 65.18
4、string   --> greet_msg = "welcome to visititercast"
5、list   --> score_list =    顺序存储相当于数组,字符串和数字混合
6、tuple      -->index_tuple(0, 1, 2, 3, 4)      不能改变的数组
7、dict                -->age_dict= { 'bob': 18, 'lucy': 16} 字典
8、set      --> index_set = set()      集合,和数学里面的集合一样没有顺序
9、none空字符串‘ ’ 、空元组()、空列表[]、空字典{} ,在逻辑判断的时候都是false
>>>'i love "itercast"'
          'i love "itercast"'
>>>"i love \"itercast\""
'ilove "itercast"'
>>>str1 = '''i love
..."itercast"
...'''
>>>str1
'ilove \n"itercast"\n'


字符串和list之间的转换:
>>>list1 = str1.split()
>>>list1
>>>['i', 'love', '"itercast"']

往list里面添加字符串
list1.append('!')or ("!")

往list里面添加数字
list1.append(8)

------------------------------------------------------------------------------------------------------------
9、 字典使用:
字典名 ={’关键字‘:值,...}
字典名.get('关键字',默认值)
赋值:自顶名['关键字']= 值
字典名.keys()         将关键字返回出一个列表
字典名.values()         将字典的值返回出一个列表
字典名.copy()          age_dict2 = age_dict.copy()
>>>del age_dict['bob']
>>>age_dict2.popitem()      弹出第一项
>>>bob in age_dict2
在脚本里面写:
dirt = {'bob':10, 'lucy':20, 'jim':30}      定义字典
print dirt['bob']
dirt['abc']=40   添加元素
printdirt
deldirt['bob']
字典内置函数&方法
Python字典包含了以下内置函数:
1、cmp(dict1,dict2):比较两个字典元素。
2、len(dict):计算字典元素个数,即键的总数。
3、str(dict):输出字典可打印的字符串表示。
4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。
Python字典包含了以下内置方法:
1、radiansdict.clear():删除字典内所有元素
2、radiansdict.copy():返回一个字典的浅复制
3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4、radiansdict.get(key,default=None):返回指定键的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
6、radiansdict.items():以列表返回可遍历的(键,值) 元组数组
7、radiansdict.keys():以列表返回一个字典所有的键
8、radiansdict.setdefault(key,default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
10、radiansdict.values():以列表返回字典中的所有值


false

实例:
>>>dirt= { 'bob':10, 'lucy':20, 10:10}
>>>dirt['jim'] = 30
返回关键字的列表
>>>dirt.keys()
['jim','bob', 10, 'lucy']
返回值得列表
>>>dirt.values()

list复制:
>>>dir1 = dirt.copy()
>>>dir1.values()

>>>dir1.keys()
['bob','jim', 10, 'lucy']
list删除关键字
deldirt['bob']
list弹出第一个关键字
dirt.popitem()

Python 表达式:

=                     赋值
==                   等于
>,=,>>for i in ['bob', 'lucy', 'jim']:
...   print i,
...
boblucy jim
>>>for i in ['bob', 'lucy', 'jim']:
...   print i
...
bob
lucy
jim

例二:
for name,age in (('afe',18), ('fleajf',16)):
>>>for name,age in (('afe',18), ('fleajf',16)):
...   print name,age
...
afe 18
fleajf16

While 循环:
>>>i = 0
>>>while i < 10:
...   print i,
...   i += 1

迭代器:
>>>obj = range(5)
>>> itera = iter(obj)   相当于 obj._iter_()
>>>try:
...   while True:
...             print itera.next(),
...except StopIteration:
...   pass
...
0 1 23 4



python 函数定义:
1、不带参数函数的定义

函数定义
函数调用
def 函数名()
函数体 。 。 。
函数名()
实例: defwelcome():
print( ' I love it')

2、带参数函数的定义

函数定义
函数调用
def 函数名(参数列表):
函数体 。。。
函数名(参数列表)
例子:
>>> defwelcome(who,action):
...   print(who + ' ' + action)
...
>>>welcome('wang','nihao')
wang nihao

3、Python变成参数:参数会自动转变成一参数命名的元组或字典

函数定义1
函数定义2
def 函数名(*args):转换成元组
函数体 。。 。
函数名(v1,v2,v3)
def 函数名(**args):转换成字典
函数名 。 。 。
函数名(k1=v1,k2=v2)


例1:
例2
例1:
>>> defwelcome(*args):
...   print args
...
>>>welcome('jim','is','thinking')
('jim', 'is','thinking')
>>> defwelcome(**args):
...   print args
...
>>>welcome(who='jim',state='is',action='thinking')
{'action': 'thinking','state': 'is', 'who': 'jim'}



4、参数默认值
>>>def welcome(who,state='is',action='sleeping'):
...   print who,state,action
...
>>>welcome('jim','was')
jimwas sleeping

第一个参数必须有,第二个和第三个可以没有,没有就用默认值

5、函数的返回值

def 函数名(函数列表)
def 函数名(参数列表)
def 函数名(参数列表)
函数体 。 。 。
函数体。 。 。
函数体 。 。 。
returnobj
return

返回 obj对象
返回none
返回none





面向对象基础--类
Python种一切都是对象,雷和对象是面向对象的基础


定义类
类的实例化
class 类名称():默认继承object
· · · · ·
class 类名称(father):
· · · · ·

实例名=类名称()

例子:

定义一个类
实例化monk类
查看实例化类的类型
class monk:
      def __init__(self,name,age):
                self.name = name
                self.age = age

yc_monk= mokn('yancan',20)
yc_monk.name #成员变量

yc_monk._class_
type(yc_monk)
类的方法:


类的方法
实例化方法的调用
class 类名称
。 。 。
def 方法名(self,参数列表)
。。。

实例名.方法名(参数列表)


例子
class monk:
def__init__(self, name, age):
self.name= name
self.age= age
defnet(self):
print"i love webo"
defplay(self, str):
print"play with",str
m1 =monk("yancan", 19)
print m1.name
m1.net()
m1.play("monkey")


python文件IO
print方法:输出数据到标准输出
raw_ipnut方法:从标准输入读数据

从标准输入读取内容
将用户输入的信息输出到标准输出
>>>input = raw_input('prompt@ ')
prompt@nihaowoshi
>>>print(input)
nihaowoshi


file类-读文件


创建一个file类实例f,以只读模式打开文本文件
>>>f = file('1.txt', 'r')
通过f实例读取文件内容
>>>f.read()
关闭文件实例,释放资源
>>>f.close()
使用open函数打开文件,返回一个file类实例
>>>f= open('1.txt', 'r')
读取全部,返回字符串
>>>f.read()
一次只读取一行
>>>f.readline()
读取全部返回列表
>>>f.readlines()
已追加模式打开文件,返回一个file类实例
>>>f = file('1.txt','a')
向文件写入字符串
>>>f.write('I love you\nEnd')
刷新缓冲区
>>>f.flush()   
>>>f.close()
"r"   ------->   只读

"w"------->   只写

"a"   ------->   追加

"b"   ------->   二进制

"r+","a+"-------> 更新

页: [1]
查看完整版本: python基本语法