1.python基础入门

作者:刘耀 出处:http://www.yaomr.com 欢迎转载

提示:

  1. 语法基于python3.5版本(会提示2.7版本和3.5版本的区别)
  2. Python命令行将以>>>开始,比如 >>>print ('Hello World!')
  3. window上会使用JetBrains PyCharm 5.0.2专业版

  4. Python官网:http://www.python.org/

    Python文档下载地址:www.python.org/doc/

一.python简介

Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在大多数平台上的许多领域都是一个理想的脚本语言,特别适用于快速的应用程序开发。 Python可以应用于众多领域,如:数据分析、组件集成、网络服务、图像处理、数值计算和科学计算等众多领域。

Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。 

Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具有比其他语言更有特色语法结构。(引用于菜鸟教程)

二、Python 发展历史

 

Python 是由 Guido van Rossum 在八十年代末和九十年代初,在荷兰国家数学和计算机科学研究所设计出来的。

Python 本身也是由诸多其他语言发展而来的,这包括 ABC、Modula-3、C、C++、Algol-68、SmallTalk、Unix shell 和其他的脚本语言等等。

像 Perl 语言一样,Python 源代码同样遵循 GPL(GNU General Public License)协议。

现在 Python 是由一个核心开发团队在维护,Guido van Rossum 仍然占据着至关重要的作用,指导其进展。(引用于菜鸟教程)

三、Python 特点

 

  • 1.易于学习:Python有相对较少的关键字,结构简单,和一个明确定义的语法,学习起来更加简单。

  • 2.易于阅读:Python代码定义的更清晰。

  • 3.易于维护:Python的成功在于它的源代码是相当容易维护的。

  • 4.一个广泛的标准库:Python的最大的优势之一是丰富的库,跨平台的,在UNIX,Windows和Macintosh兼容很好。

  • 5.互动模式:互动模式的支持,您可以从终端输入执行代码并获得结果的语言,互动的测试和调试代码片断。

  • 6.可移植:基于其开放源代码的特性,Python已经被移植(也就是使其工作)到许多平台。

  • 7.可扩展:如果你需要一段运行很快的关键代码,或者是想要编写一些不愿开放的算法,你可以使用C或C++完成那部分程序,然后从你的Python程序中调用。

  • 8.数据库:Python提供所有主要的商业数据库的接口。

  • 9.GUI编程:Python支持GUI可以创建和移植到许多系统调用。

  • 10.可嵌入: 你可以将Python嵌入到C/C++程序,让你的程序的用户获得"脚本化"的能力。(引用于菜鸟教程)

四、python版本区别

1.print使用方法

1
2
2.7 版本 print "yaoyao" or print ( "yaoyao" )
3.x 版本 print ( "yaoyao" )

2.Py3.X源码文件默认使用utf-8编码

3.模块命名修改


 

注:(twisted模块还未完全支持python3)
4. 语法 
1)去除了<>,全部改用!= 
2)去除``,全部改用repr() 
3)关键词加入as 和with,还有True,False,None 
4)整型除法返回浮点数,要得到整型结果,请使用// 
5)加入nonlocal语句。使用noclocal x可以直接指派外围(非全局)变量 
6)去除print语句,加入print()函数实现相同的功能。同样的还有 exec语句,已经改为exec()函数
7)改变了顺序操作符的行为,例如x<y,当x和y类型不匹配时抛出TypeError而不是返回随即的 bool值  
8)输入函数改变了,删除了raw_input,用input代替: 
9)去除元组参数解包。不能def(a, (b, c)):pass这样定义函数了 
10) 新式的8进制字变量,相应地修改了oct()函数。 
11). class Foo:这种写法不能用了,改成class Foo(object)

 

五、Python解释器

1.Cpython

    Python的官方版本,使用C语言实现,使用最为广泛,CPython实现会将源文件(py文件)转换成字节码文件(pyc文件),然后运行在Python虚拟机上

1
程序----(c解释器)----(字节码)----(机器码)-----cpu

2.Jyhton

    Python的Java实现,Jython会将Python代码动态编译成Java字节码,然后在JVM上运行。

1
程序 - - - - (java解释器) - - - - (字节码) - - - - (机器码) - - - - - cpu

3.IronPython

    Python的C#实现,IronPython将Python代码编译成C#字节码,然后在CLR上运行。(与Jython类似)

1
程序 - - - - (c #解释器)----(字节码)----(机器码)-----cpu

4.PyPy(特殊)

    Python实现的Python,将Python的字节码字节码再编译成机器码。

1
程序 - - - - (c #解释器)----(字节码)----(机器码)-----cpu

 

  • 六.pyc文件
  • 执行Python代码时,如果导入了其他的 .py 文件,那么,执行过程中会自动生成一个与其同名的 .pyc 文件,该文件就是Python解释器编译之后产生的字节码。
  • ps:代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。

 

七.python安装

1.window

(1)进入官网下载安装包:

    https://www.python.org/downloads/

2.linux

注:新版本的Ubuntu和centos7默认为2.7版本

    以下为升级到3.4版本

(1)安装3.x包:

1
2
3
sudo apt - get install python3. 4
python3. 4
>>>

. 用户交互

 1:linux

(1)输出

 

1
2
3
python3. 4
>>> print ( 'Hello World!' )
Hello World!

print是一个常用函数,其功能就是输出括号中得字符串。(在Python 2.x中,print还可以是一个关键字,可写成print 'Hello World!')

写入以下内容,保存并且退出。

1
2
3
4
5
6
7
8
9
$vim HelloWorld.py
#!/usr/bin/env python  #必须声明是什么解释器来解释此脚本
print ( 'Hello World!' #保存退出
#python HelloWorld.py  #运行py
Hello World!
或者给该文件增加可执行权限
chmod a + x HelloWorld.py
. / HelloWorld.py
Hello World

(2)输入

Python提供了一个input(),可以让用户输入字符串,并存放到一个变量里。比如输入用户的名字:

1
2
3
4
5
6
7
>>> name = input ( '您的名字' )
您的名字
>>> name = input ( '您的名字' )
您的名字yaoyao
>>> name
'yaoyao'
>>>

九、注释

1.单行注释

注释符#

例:

1
#代码代码代码被注释

2.多行注释

'''

'''

例:

 

1
2
3
4
'''第一句
第二句
第三句
'''

十、行与缩进

 

学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。python最具特色的就是用缩进来写模块。

缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
if True :
     print "True"
else :
     print "False"
   
  
以下代码将会执行错误:
  
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:test.py
  
  if True :
     print "Answer"
     print "True"
else :
     print "Answer"
     # 没有严格缩进,在执行时保持
   print "False"
  #提示以下错误
$ python test.py 
   File "test.py" , line 5
     if True :
     ^
IndentationError: unexpected indent

十一、变量与赋值

1.声明变量

 

1
2
3
>>> name = 'yaoyao'
>>> name
'yaoyao'

声明一个变量为name 值为:yaoyao

1
2
3
4
>>> name = "yaoyao"
>>> age = 20
>>> print (name,age)
( 'yaoyao' , 20 )

查看变量内存地址

1
2
>>> id (age)
43102336

2.变量声明要求

  • 变量名只能是 字母、数字或下划线的任意组合
  • 变量名的第一个字符不能是数字
以下关键字不能声明为变量名(keyword模块,可以输出当前版本的所有关键字)
1
2
3
>>> import keyword
>>> keyword.kwlist
[ 'False' , 'None' , 'True' , 'and' , 'as' , 'assert' , 'break' , 'class' , 'continue' , 'def' , 'del' , 'elif' , 'else' , 'except' , 'finally' , 'for' , 'from' , 'global' , 'if' , 'import' , 'in' , 'is' , 'lambda' , 'nonlocal' , 'not' , 'or' , 'pass' , 'raise' , 'return' , 'try' , 'while' , 'with' , 'yield' ]
十二、数据类型

1.数字

 int  (整数型)

    在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647

    在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

float (浮点型)

   浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下  的一位表示符号。

long(长整型)

跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。

 

2.布尔值

布尔值和布尔代数的表示完全一致,一个布尔值只有TrueFalse两种值,要么是True,要么是False,在Python中,可以直接用TrueFalse表示布尔值(请注意大小写),也可以通过布尔运算计算出来:

 

1
2
3
4
>>> True
True
>>> False
False

3.字符串 (即不能修改的字符list)

 

字符串是一个整体。如果你想直接修改字符串的某一部分,是不可能的。但我们能够读出字符串的某一部分。  

 

字符串包含判断操作符:

 

1
2
3
例: in not in 
"He" in str 
"she" not in str

字符串常用功能:

 

字符串格式化输出

 

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
name = input ( "name:" )
age  = input ( "age:" )
job  = input ( "job:" )
print ( '''
     Infomation of %s
              name:%s
               age:%s
               job:%s
     ''' % (name,name,age,job))

十三、列表

 

Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。

创建列表:

比如列出日本的美女:

 

1
2
3
>>> gril = [ 'cangjingkong' , 'xiaoze' , 'tenglan' , 'sondaofeng' ]
>>> gril
[ 'cangjingkong' , 'xiaoze' , 'tenglan' , 'sondaofeng' ]

用dir()函数可以查看此列表能使用的方

1
2
>>> dir (gril)
[ '__add__' , '__class__' , '__contains__' , '__delattr__' , '__delitem__' , '__dir__' , '__doc__' , '__eq__' , '__format__' , '__ge__' , '__getattribute__' , '__getitem__' , '__gt__' , '__hash__' , '__iadd__' , '__imul__' , '__init__' , '__iter__' , '__le__' , '__len__' , '__lt__' , '__mul__' , '__ne__' , '__new__' , '__reduce__' , '__reduce_ex__' , '__repr__' , '__reversed__' , '__rmul__' , '__setattr__' , '__setitem__' , '__sizeof__' , '__str__' , '__subclasshook__' , 'append' , 'clear' , 'copy' , 'count' , 'extend' , 'index' , 'insert' , 'pop' , 'remove' , 'reverse' , 'sort' ]

基本操作:

          索引. index

      用索引来访问list中每一个位置的元素,索引是从0开始的

1
2
3
4
5
6
>>> gril = [ 'cangjingkong' , 'xiaoze' , 'tenglan' , 'sondaofeng' ]
>>> gril.index( 'cangjingkong' )
0
>>> gril.index( 'xiaoze' )
1
>>>

  切片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> gril = [ 'cangjingkong' , 'xiaoze' , 'tenglan' , 'sondaofeng' # 切割列表并返回新的列表
>>> gril[ 1 : 2 ]
[ 'xiaoze' ]
>>> gril[ 0 : 3 ]
[ 'cangjingkong' , 'xiaoze' , 'tenglan' ]
>>> gril[: 3 ]
[ 'cangjingkong' , 'xiaoze' , 'tenglan' ]
>>> gril[: - 1 ]
[ 'cangjingkong' , 'xiaoze' , 'tenglan' ]
>>> gril[: 1 ]
[ 'cangjingkong' ]
>>> gril[ - 2 ]
'tenglan'
>>>

追加

1
2
3
>>> gril.append( 'zaochuan' )
>>> gril
[ 'cangjingkong' , 'xiaoze' , 'tenglan' , 'sondaofeng' , 'zaochuan' ]

 删除

1
2
3
>>> gril.pop()   #返回最后一个元素,并从list中删除
>>> gril
[ 'cangjingkong' , 'xiaoze' , 'tenglan' , 'sondaofeng' ]
1
2
3
>>> gril.remove( 'xiaoze' )   #remove删除指定值
>>> gril
[ 'cangjingkong' , 'tenglan' , 'sondaofeng' , 'zaochuan' ]
插入.insert
1
2
3
>>> gril.insert( 2 , 'mahuateng' )
>>> gril
[ 'cangjingkong' , 'tenglan' , 'mahuateng' , 'sondaofeng' , 'zaochuan' ]

 统计.count

1
2
3
>>> gril.insert( 2 , 'mahuateng' )
>>> gril
[ 'cangjingkong' , 'tenglan' , 'mahuateng' , 'sondaofeng' , 'zaochuan' ]

反转

  
1
2
3
4
5
>>> gril
[ 'cangjingkong' , 'tenglan' , 'mahuateng' , 'sondaofeng' , 'zaochuan' , 'tenglan' ]
>>> gril.reverse()
>>> gril
[ 'tenglan' , 'zaochuan' , 'sondaofeng' , 'mahuateng' , 'tenglan' , 'cangjingkong' ]

十四、元祖

 

Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

 

创建元祖:

 

1
2
3
>>> boy=( 'mayun' , 'aobama' , 'liyanhong' , 'mahuateng' )
>>> boy
( 'mayun' , 'aobama' , 'liyanhong' , 'mahuateng' )

支持的方法:

1
2
>>> dir(boy)
[ '__add__' , '__class__' , '__contains__' , '__delattr__' , '__dir__' , '__doc__' , '__eq__' , '__format__' , '__ge__' , '__getattribute__' , '__getitem__' , '__getnewargs__' , '__gt__' , '__hash__' , '__init__' , '__iter__' , '__le__' , '__len__' , '__lt__' , '__mul__' , '__ne__' , '__new__' , '__reduce__' , '__reduce_ex__' , '__repr__' , '__rmul__' , '__setattr__' , '__sizeof__' , '__str__' , '__subclasshook__' , 'count' , 'index' ]

创建空元组

1
2
3
4
>>> boy.index( 'mayun' )
0
>>> boy.index( 'liyanhong' )
2

基本操作:

索引
1
2
3
4
>>> boy.index( 'mayun' )
0
>>> boy.index( 'liyanhong' )
2

切片

1
2
tuple(gril)  
list(boy)

长度

1
2
tuple(gril)  
list(boy)

list 和 tuple 的相互转化  

1
2
tuple(gril)  
list(boy)

十五、字典

 

字典是另一种可变容器模型,且可存储任意类型对象,如其他容器模型。

字典由键和对应值成对组成。字典也被称作关联数组或哈希表。

 

创建字典:

 

1
2
3
>>> dict = { 'name' : 'liuyao' , 'age' : '20' , 'job' : 'it' }
>>> dict
{ 'job' : 'it' , 'age' : '20' , 'name' : 'liuyao' }

每个键与值用冒号隔开(:),每对用逗号分割,整体放在花括号中({})。

 

键必须独一无二,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

注:type()可以查看变量类型

十六、运算符

1.算术运算符

以下假设变量a为10,变量b为20:


 

2.比较运算符

 

以下假设变量a为10,变量b为20:


3.赋值运算符

以下假设变量a为10,变量b为20:


 

4.位运算

按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如下:

 

5.逻辑运算符

Python语言支持逻辑运算符,以下假设变量a为10,变量b为20:


6.成员运算符


7.身份运算符

身份运算符用于比较两个对象的存储单元


8.运算符优先级


十七、字符编码

ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言,其最多只能用 8 位来表示(一个字节),即:2**8 = 256,所以,ASCII码最多只能表示 256 个符号。

Unicode Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。 Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每 个字符设定了统一并且唯一的二进制编码,规定虽有的字符和符号最少由 16 位 来表示(2个字节),即:2 **16 = 65536

UTF-8 utF-8,是对Unicode编码的压缩和优化,他不再使用最少使用2个字节,而是将 所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个 字节保存,东亚的字符用3个字节保存...

十八、判断

 

 

1
2
3
4
5
条件判断 if ... else
if <条件判断 1 >:
     <执行 1 >
else :
     <执行 4 >

例:

1
2
3
4
5
6
7
8
9
10
11
12
13
if sex ==  "girl" :
     print( '正确' )
else :
     print( '错误' )
 
if sex == "gril" :
     print( 'gril' )
elif sex == "man" :
     print( 'man' )
elif sex == "ren" :
     print( 'ren' )
else :
     print( 'no' )

十九.循环

 

1.while 

 while 判断条件:

执行语句……

 

1
2
3
4
5
6
7
8
9
10
LuckyNum = 6
while True:
   InLuckyNum = int (input( 'please your lucky number:' ))
   if InLuckyNum == LuckyNum:
       print( 'bingo ' )
       break
   elif InLuckyNum < LuckyNum:
      print( 'please input big' )
  else :
       print( 'please input small' )
1
2
3
4
5
6
#!/usr/bin/python
count = 0
while (count < 9 ):
    print (count)
    count = count + 1
print "Good bye!"

while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,

break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:

 

1
2
3
4
5
6
7
8
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for letter in 'Python' :     # 第一个实例
    print '当前字母 :' , letter
fruits = [ 'banana' , 'apple' 'mango' ]
for fruit in fruits:        # 第二个实例
    print '当前字母 :' , fruit
print "Good bye!"

无限循环

1
2
3
4
5
6
7
8
#!/usr/bin/python
# -*- coding: UTF-8 -*-
for letter in 'Python' :     # 第一个实例
    print '当前字母 :' , letter
fruits = [ 'banana' , 'apple' 'mango' ]
for fruit in fruits:        # 第二个实例
    print '当前字母 :' , fruit
print "Good bye!"

2.for循环

1
2
3
4
5
6
7
8
#!/usr/bin/python
# -*- coding: UTF- 8 -*-
for letter in 'Python' :     # 第一个实例
    print '当前字母 :' , letter
fruits = [ 'banana' , 'apple' 'mango' ]
for fruit in fruits:        # 第二个实例
    print '当前字母 :' , fruit
print "Good bye!"
1
2
3
4
5
6
7
8
9
10
11
12
luckynum = 20
for i in range( 3 ):
     input_num= int (input( 'please your lucky number:' ))
     if input_num == luckynum:
         print( 'bingo' )
         break
     elif input_num < luckynum:
         print( 'please input big' )
     else :
         print( 'plase input small' )
else :
     print( 'too many retrys' )

二十、文件操作

打开文件:

 

1
file = open( '文件路径' '模式' )

 

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/liu-yao/p/5145828.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值