半天光速入门Python(上)

写在前面

  • 时隔4个月后,再次回到这里,因为一直忙于比赛(虽然现在也在还忙~~~)和学习,所以很少有时间再写博客。难得因为购买的元件还没到,项目没法推进,空出来一天时间,所以就想写点东西,一方面是想打发时间,另外也当做学习笔记,将一些要点记录下来。
  • 本片博客内容是关于Python基础的,由于做项目需要,所以就花了半天时间学了一下Python。之前我一直觉得用Python写的代码看起来很不舒服,但是回过头来我发现,Python语法真的很简单,对比C++复杂的语法,简直是降维打击。它没有那些花里胡哨的奇技淫巧,更近乎以一种有点无赖的方式去实现一些东西。如果你有C/C++基础的话,那么Python对你来说应该很容易入门。
  • 最后,感谢Swaroop.C.H先生所著的《A Byte of Python》,正是这本书让我在半天时间内光速入门Python,也感谢上海交通大学研究生沈洁元针对此书做了翻译。 接下来我们进入正题。

一、Python环境

Python解释器与编辑器

  • 在学Python编程前,需要先确保电脑上安装有Python的解释器,用Python编写的脚本(程序、软件)在执行过程中是靠Python解释器边解释(将Python程序翻译为机器语言)边执行的,这一点不像C/C++程序,是先编译后才能执行。
  • 除了需要Python解释器以外,还需要一款用着比较顺手的编辑器用来编写Python程序,这个编辑器可以是IDLE,VIM,VSCode,Eclipse甚至是一个记事本都可以。但最好使用一个可以对语法高亮的编辑器。

WinDows用户

Linux用户

  • 如果用的是Linux操作系统,那么就不需要自己手动安装Python,因为Linux系统默认已经安装了Python,只需要打开terminal,然后输入Python -v即可查看Python版本。输入Python,即可运行Python解释器。输入exit()或quit()或按快捷键Ctrl+D即可退出Python解释器
    在这里插入图片描述

二、基础概念、运算符与表达式

常量

  • 像 1 ,2.2, 3.25E-3,‘this is a python program’,都是常量。

数类型

  • Python中包含了整数,长整数、浮点数、复数四种数类型。
  • 整数和长整数浮点数与C语言中类似
  • 复数表示为(x+yj)

字符串

  • Python中使用单引号’ ’ 、双引号" “,来表示一个字符串,两者用法相同,如‘this is a program’和"this is a program” 表示的意义相同
  • 三引号(三个单引号或三个双引号)’’’ ‘’’ 、 “”" “”",使用三引号时语句里面可以随意使用单引号和双引号,并且字符串可以换行.
  • 转义符,如果想在字符串中表示单引号、双引号、三引号,可以使用转义字符\,其用法与C相似,并且转义字符可以用来连接两行字符串,如下图所示。
  • Python中没有字符,只有字符串
  • 程序
s1 = ' use \' signal quote '
s2 = " use \" double quotes "
s3 = ''' use ' three ''  quotes'''
s4 = 'this is first line\
    this is first line also'
s5 = '''this is first line
this is second line'''
print s1
print s2
print s3
print s4
print s5
  • 输出结果
 use ' signal quote 
 use " double quotes 
 use ' three ''  quotes
this is first line    this is first line also
this is first line
this is second line

变量与标识符

  • 与C/C++不同,Python中变量不需要声明类型,只需要在使用的时候赋值即可,Python中标识符的规范与C/C++相同
  • 程序
i = 5
print i
i = i+1
print i
s = 'this is a string'
print s
  • 输出结果
5
6
this is a string

对象

  • Python将程序中用到的东西包括数、字符串都称为对象。

逻辑行与物理行

  • Python建议程序每一行只有一个语句,一行后面一般不加 ; 号,如果一行多于一个语句,则用 ; 号隔开。
  • 一个物理行就是编辑器中的一行,逻辑行则是编码人员认为的一行
  • 程序
print 'this is a physical line'
print 'this is a logical line'; print 'it has two sentences'
  • 输出结果
this is a physical line
this is a logical line
it has two sentences

缩进

  • C/C++中利用{} 来划分代码块,而Python则利用缩进来划分代码块。同一层次的语句需要有相同的缩进。一般在每个缩进层次上用一个Tab或两个空格或四个空格,注意不要混合使用,在一个程序中使用一个缩进风格。

运算符

  • Python中的运算符大部分与C中的一样,这里仅列举与C中不一样的
  • 逻辑与:在C语言中用&&来表示,Python中用 and 来表示
  • 逻辑或:在C语言中用 || 来表示,Python中用 or 来表示
  • 逻辑非:在C语言中用 !来表示,Python中用 not 来表示
  • 乘幂:C语言中乘幂用连乘或pow计算,而Python中用 ** 来计算
  • 整除:取商的整数部分,C语言中两个整数相除即为取整数部分,Python中用 // 来取整数部分
  • 在C语言中用0表示逻辑假,1表示逻辑真,而Python中用False和True
  • 程序
i=3
j=2
print 'and:',i>0 and j>3
print 'or:',i>0 or j>3
print 'not:',not(i>0 and j>3)
print '**:',i**j
print '//:',i//j
  • 运算结果
and: False
or: True
not: True
**: 9
//: 1

注释方法

  • Python使用#号来对单行做注释

与C语言区别

  • 下表总结了C语言与Python的一些区别
项目 C Python
数据类型 短整型、整型、长整型、浮点型、字符型等 整型、长整型、复数、字符串
变量 需要声明类型 不需要声明类型,只需要赋值
代码块 以{} 来划分代码块 用缩进划分
代码行 每个语句都需要加分号 单行语句一般不加分号
运算符 &&,||,!,pow and , or , not ,**
注释 //,/**/ #

三、三种程序结构

  • 与C语言类似,Python也有三种程序结构,这三种程序结构与C语言的语法有些许差别。Python中没有switch和do while 语句。

if

  • Python中if语句格式为,if…elif…else
  • 程序
i = int(raw_input('Enter :'))
if i == 10:
    print 'right'
elif i<10:
    print 'it\'s to little'
else:
    print 'it\'s to big'
  • 输入
python if.py
Enter :11
  • 输出
it's to big

for

  • for语句格式:for x in range( a, b, c),即x在区间(a,b)中以步长c开始循环。注意a,b, c均为整数。当然 循环对象不一定是这种整数序列,也可以是字符串。并且 for循环结束后可以跟一个else从句。
  • 程序
for i in range(1,5,2):
    print i,
else:
    print ''
for j in ['abc','defg','hijkl','mnopqr']:
    print j,
else:
    print '\nover'
  • 输出结果
1 3 
abc defg hijkl mnopqr 
over

while

  • while语句与for语句类似,其后面也可以跟一个else从句。
  • 程序
i=23
j=12
running=True
while running:
    if j<i:
        print j,
        j=j+1
    elif j>i:
        j=j-1
        print j,
    else:
        running=False
else:
    print '\n done'

输出结果:

12 13 14 15 16 17 18 19 20 21 22 
 done

break和continue

  • break和continue的用法与C语言中相同,在此不再赘述。

与C语言区别

  • Python不支持i++这类语句。
  • 三种结构后面需要加 :来表示下面后面是程序内容
  • 利用缩进来表示代码块
  • for和while语句后面都可以跟一个else从句,即当循环结束后就执行else中的内容

四、函数

定义函数

  • Python定义函数很简单,只需要一个关键字def,即def functionName (FormalParam)。
  • 函数返回值可以有可以没有,有的话只需要用return语句返回一个值即可,如果没有返回值,每个函数结尾也会暗含一个return None语句
  • Python还支持文档字符串,即可以将字符串添加到文档中,帮助程序文档更加简单。添加的文档通过 functionName.__doc__来调用。
  • 程序
def Max(a,b):
    '''This function is returns the max value between two value '''#This is DocString
    if a>b:
        return a
    else:
        return b

print Max(2,3) #print the max in 2 and 3
print Max.__doc__ #print the DocString in function
  • 输出结果
3
This function is returns the max value between two value 

局部变量与全局变量

  • 如果在函数中声明的变量,如果未使用global关键字说明,那么这个变量仅作用与函数内,如果想要在函数外使用函数中的变量,就需要加上global,声明为全局变量。
  • 程序
def fun(y):
    global x #x is a global variable
    print 'x is',x
    x=20
    print 'x is modified to',x
    print 'y is',y #y is a local variable
    y=111
    print 'y is modified to',y
x=5
y=10
fun(y)
print 'x is modified to',x
print 'y is still',y
  • 输出结果
x is 5
x is modified to 20
y is 10
y is modified to 111
x is modified to 20
y is still 10

默认参数值与关键参数

  • Python中函数的形参可以使用默认参数值也可以使用关键参数赋值,二者区别在于使用默认参数值,在赋值的时候必须按照顺序,并且只有后面的那些形参的赋值可以省去,而使用关键参数时不需要按照顺序。
  • 程序
def s(name='kerian',age=20,mark=100):
    print name,age,mark;
s('toy')  #use default param
s('tom',18) #use default param
s(mark=55) #use key param
s(mark=66,name='kindy')#use key param
  • 输出结果
toy 20 100
tom 18 100
kerian 20 55
kindy 20 66

五、模块

关于模块

  • 为了提高代码复用率,使用模块是一个很有效的方式。每个模块的后缀都是.py。当该模块被其他Python加载时,将会生成一个字节编译文件,即.pyc文件,这个.pyc文件比加载模块要快很多,这是Python解决加载模块速度慢的方法。

加载模块

  • 使用import加载模块,如 import xx,通过xx.func调用模块中函数
  • 使用from xx import func,这时调用函数func时不需要加xx.
  • 使用from xx import* 加载模块中所以函数,此时调用函数时也不需要加xx.

使用模块的__name__

  • 如果我们希望程序本身被运行时与改程序被调用时所运行的程序不一样。即本身被使用时使用主块,被其他程序加载使用时使用其他模块,此时就可以使用__name__来加以区分,即判断__name__是否等于__main__。

创建自己的模块

  • 创建自己的模块与编写Python程序的步骤相同。

  • 创建三个程序,并且model1.py和model2.py被model_demo,py调用

#model1.py
def m1func1():
    print 'This function belongs to  module1, it\'s function 1'
def m1func2():
    print 'This function belogs to module2, it\'s function 2'
m1version = '0.2'
if __name__=='__main__':
    print 'module1 is running it\'s main block code'
else:
    print 'module1 is called by other programs'

#model2.py
def m2func2():
    print 'This function belongs to module2'
m2version = '0.1'
if __name__=='__main__':
    print 'module2 is running it\'s main code block'
else:
    print 'module2 is called by other programs'

#model_demo.py
from model1 import * #import all function and variable from model1
import model2 
if __name__=='__main__':
    print 'module_demo is running it\'s main code block'
    m1func1()
    m1func2()
    print m1version
    model2.m2func2()
    print model2.m2version
else:
    print 'module_demo is called by other programs'
  • 输出结果
module1 is called by other programs
module2 is called by other programs
module_demo is running it's main code block
This function belongs to  module1, it's function 1
This function belogs to module2, it's function 2
0.2
This function belongs to module2
0.1

六、数据结构

  • Python有三种内建的数据结构,这三种数据结构能够帮助我们编写程序。

列表

  • 使用list = [x1,x2…]初始化列表。列表中元素既可以是数也可以是字符串,list.append(xx),将xx添加到list结尾,del list[index],删除第index+1项数据。
  • 程序
numlist=[5,2,'3',6,'7']
print 'numlist:',numlist
print 'numlist length:',len(numlist)
for item in numlist:
    print item,
else:
    print ''
numlist.append('1')
print 'add 1 in the end of list:',numlist
numlist.sort()
print 'sorted list:',numlist
del numlist[1]
print 'list number after deleted the second number',numlist
  • 运行结果
numlist: [5, 2, '3', 6, '7']
numlist length: 5
5 2 3 6 7 
add 1 in the end of list: [5, 2, '3', 6, '7', '1']
sorted list: [2, 5, 6, '1', '3', '7']
list number after deleted the second number [2, 6, '1', '3', '7']

元组

  • 元组与列表很相似,元组创建方法为tuple =(x1,x2,x3…)但是元组创建完成后不能再添加和删除
    程序。元组经常用来打印数据(此用法与C语言中printf函数有些相似)。
  • 程序
mtuple=('a','b','cd',123,456)
for item in mtuple:
    print item,
else:
    print ''
print mtuple
newtuple=('xy','z',mtuple)
print newtuple
print newtuple[2]
print newtuple[2][2]
name = 'kerain'
age=22
print 'name:%s age:%d' % (name,age)
                                       
  • 输出结果
a b cd 123 456 
('a', 'b', 'cd', 123, 456)
('xy', 'z', ('a', 'b', 'cd', 123, 456))
('a', 'b', 'cd', 123, 456)
cd
name:kerain age:22

字典

  • 字典类似于电话簿,电话簿中的名字容易记,而电话号码不容易记,所以这时候字典可以将名字和电话号码联系在一起,当进行检索的时候只需要根据名字(键)即可得到相应的电话号码(值)。字典创建的格式为d={name1:tel1,name2:tel2…}。
  • 程序
d={
    
    'kerian':'12345','toy':'123456','tom':'54321'}
print 'kerian\'s telephone is:%s '% d['kerian']
print d
d['jack']='9887123'
del d['tom']
print d
for name,tele in d.items():
    print 'name:%s tele:%s' % (name,tele),
  • 输出结果
kerian's telephone is:12345 
{
    
    'kerian': '12345', 'toy': '123456', 'tom': '54321'}
{
    
    'kerian': '12345', 'toy': '123456', 'jack': '9887123'}
name:kerian tele:12345 name:toy tele:123456 name:jack tele:9887123

序列

  • Python中列表、元组、字符串都是序列,可以利用索引操作抓取单个项目,也可以利用切片操作符获取部分序列。
  • 程序
numlist=['1','2','3','4']
print 'item 0:',numlist[0]
print 'item 2:',numlist[2]
print 'item -1:',numlist[-1]
print 'item -3:',numlist[-3]
print 'item 1 to 3:',numlist[1:3]
print 'item 1 to -1:',numlist[1:-1]
print 'item start to end:',numlist[:]
  • 输出结果
item 0: 1
item 2: 3
item -1: 4
item -3: 2
item 1 to 3: ['2', '3']
item 1 to -1: ['2', '3']
item start to end: ['1', '2', '3', '4']

对象与参考

  • 当创建一个对象是并给该对象赋值一个变量,那么该对象与变量将会共享同一段内存。只有将变量值赋值给对象,该对象才能拥有自己的内存空间。
  • 程序
numlist =['1','2','3','4']
mylist=numlist
del mylist[0]
print 'mylist:',mylist
print 'numlist:',numlist
mylist=numlist[:]
del mylist[0]
print 'mylist:',mylist
print 'numlist:',numlist                    
  • 输出结果
mylist: ['2', '3', '4']
numlist: ['2', '3', '4']
mylist: ['3', '4']
numlist: ['2', '3', '4']

猜你喜欢

转载自blog.csdn.net/dhejsb/article/details/123589131