本文实例讲述了Python简明入门教程。分享给大家供大家参考。具体如下:

一、基本概念

1、数

在Python中有4种类型的数――整数、长整数、浮点数和复数。

(1)2是一个整数的例子。

(2)长整数不过是大一些的整数。

(2)3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。

(4)(-5+4j)和(2.3-4.6j)是复数的例子。

2、字符串

(1)使用单引号(')

(2)使用双引号(")

(3)使用三引号('''或""")

利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号。例如:

'''This is a multi-line string. This is the first line.

This is the second line.

"What's your name?," I asked.

He said "Bond, James Bond."

'''

(4)转义符

(5)自然字符串

自然字符串通过给字符串加上前缀r或R来指定。例如r"Newlines are indicated by "。

3、逻辑行与物理行

一个物理行中使用多于一个逻辑行,需要使用分号(;)来特别地标明这种用法。一个物理行只有一个逻辑行可不用分号

二、控制流

1、if

块中不用大括号,条件后用分号,对应elif和else

if guess == number:

print 'Congratulations, you guessed it.' # New block starts here

elif guess < number:

print 'No, it is a little higher than that' # Another block

else:

print 'No, it is a little lower than that'

2、while

用分号,可搭配else

while running:

guess = int(raw_input('Enter an integer : '))

if guess == number:

print 'Congratulations, you guessed it.'

running = False # this causes the while loop to stop

elif guess < number:

print 'No, it is a little higher than that'

else:

print 'No, it is a little lower than that'

else:

print 'The while loop is over.'

# Do anything else you want to do here

3、for

用分号,搭配else

for i in range(1, 5):

print i

else:

print 'The for loop is over'

4、break和continue

同C语言

三、函数

1、定义与调用

def sayHello():

print 'Hello World!' # block belonging to the function

sayHello() # call the function

2、函数形参

类C语言

def printMax(a, b):

if a > b:

print a, 'is maximum'

else:

print b, 'is maximum'

3、局部变量

加global可申明为全局变量

4、默认参数值

def say(message, times = 1):

print message * times

5、关键参数

如果某个函数有许多参数,而只想指定其中的一部分,那么可以通过命名来为这些参数赋值――这被称作 关键参数 ――使用名字(关键字)而不是位置来给函数指定实参。这样做有两个 优势 ――一,由于不必担心参数的顺序,使用函数变得更加简单了。二、假设其他参数都有默认值,可以只给我们想要的那些参数赋值。

def func(a, b=5, c=10):

print 'a is', a, 'and b is', b, 'and c is', c

func(3, 7)

func(25, c=24)

func(c=50, a=100)

6、return

四、模块

1、使用模块

import sys

print 'The command line arguments are:'

for i in sys.argv:

print i

如果想要直接输入argv变量到程序中(避免在每次使用它时打sys.),可以使用from sys import argv语句

2、dir()函数

可以使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。

五、数据结构

1、列表

shoplist = ['apple', 'mango', 'carrot', 'banana']

print 'I have', len(shoplist),'items to purchase.'

print 'These items are:', # Notice the comma at end of the line

for item in shoplist:

print item,

print ' I also have to buy rice.'

shoplist.append('rice')

print 'My shopping list is now', shoplist

print 'I will sort my list now'

shoplist.sort()

print 'Sorted shopping list is', shoplist

print 'The first item I will buy is', shoplist[0]

olditem = shoplist[0]

del shoplist[0]

print 'I bought the', olditem

print 'My shopping list is now', shoplist

2、元组

元组和列表十分类似,只不过元组和字符串一样是不可变的即你不能修改元组。

zoo = ('wolf', 'elephant', 'penguin')

print 'Number of animals in the zoo is', len(zoo)

new_zoo = ('monkey', 'dolphin', zoo)

print 'Number of animals in the new zoo is', len(new_zoo)

print 'All animals in new zoo are', new_zoo

print 'Animals brought from old zoo are', new_zoo[2]

print 'Last animal brought from old zoo is', new_zoo[2][2]

像一棵树

元组与打印

age = 22

name = 'Swaroop'

print '%s is %d years old' % (name, age)

print 'Why is %s playing with that python?' % name

3、字典

类似哈希

ab = { 'Swaroop' : 'swaroopch@byteofpython.info',

'Larry' : 'larry@wall.org',

'Matsumoto' : 'matz@ruby-lang.org',

'Spammer' : 'spammer@hotmail.com'

}

print "Swaroop's address is %s" % ab['Swaroop']

# Adding a key/value pair

ab['Guido'] = 'guido@python.org'

# Deleting a key/value pair

del ab['Spammer']

print ' There are %d contacts in the address-book ' % len(ab)

for name, address in ab.items():

print 'Contact %s at %s' % (name, address)

if 'Guido' in ab: # OR ab.has_key('Guido')

print " Guido's address is %s" % ab['Guido']

4、序列

列表、元组和字符串都是序列。序列的两个主要特点是索引操作符和切片操作符。

shoplist = ['apple', 'mango', 'carrot', 'banana']

# Indexing or 'Subscription' operation

print 'Item 0 is', shoplist[0]

print 'Item 1 is', shoplist[1]

print 'Item -1 is', shoplist[-1]

print 'Item -2 is', shoplist[-2]

# Slicing on a list

print 'Item 1 to 3 is', shoplist[1:3]

print 'Item 2 to end is', shoplist[2:]

print 'Item 1 to -1 is', shoplist[1:-1]

print 'Item start to end is', shoplist[:]

# Slicing on a string

name = 'swaroop'

print 'characters 1 to 3 is', name[1:3]

print 'characters 2 to end is', name[2:]

print 'characters 1 to -1 is', name[1:-1]

print 'characters start to end is', name[:]

5、参考

当你创建一个对象并给它赋一个变量的时候,这个变量仅仅参考那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。

print 'Simple Assignment'

shoplist = ['apple', 'mango', 'carrot', 'banana']

mylist = shoplist # mylist is just another name pointing to the same object!

del shoplist[0]

print 'shoplist is', shoplist

print 'mylist is', mylist

# notice that both shoplist and mylist both print the same list without

# the 'apple' confirming that they point to the same object

print 'Copy by making a full slice'

mylist = shoplist[:] # make a copy by doing a full slice

del mylist[0] # remove first item

print 'shoplist is', shoplist

print 'mylist is', mylist

# notice that now the two lists are different

6、字符串

name = 'Swaroop' # This is a string object

if name.startswith('Swa'):

print 'Yes, the string starts with "Swa"'

if 'a' in name:

print 'Yes, it contains the string "a"'

if name.find('war') != -1:

print 'Yes, it contains the string "war"'

delimiter = '_*_'

mylist = ['Brazil', 'Russia', 'India', 'China']

print delimiter.join(mylist) //用delimiter来连接mylist的字符

六、面向对象的编程

1、self

Python中的self等价于C++中的self指针和Java、C#中的this参考

2、创建类

class Person:

pass # An empty block

p = Person()

print p

3、对象的方法

class Person:

def sayHi(self):

print 'Hello, how are you?'

p = Person()

p.sayHi()

4、初始化

class Person:

def __init__(self, name):

self.name = name

def sayHi(self):

print 'Hello, my name is', self.name

p = Person('Swaroop')

p.sayHi()

5、类与对象的方法

类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。

对象的变量 由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。

class Person:

'''Represents a person.'''

population = 0

def __init__(self, name):

'''Initializes the person's data.'''

self.name = name

print '(Initializing %s)' % self.name

# When this person is created, he/she

# adds to the population

Person.population += 1

population属于Person类,因此是一个类的变量。name变量属于对象(它使用self赋值)因此是对象的变量。

6、继承

class SchoolMember:

'''Represents any school member.'''

def __init__(self, name, age):

self.name = name

class Teacher(SchoolMember):

'''Represents a teacher.'''

def __init__(self, name, age, salary):

SchoolMember.__init__(self, name, age)

self.salary = salary

七、输入输出

1、文件

f = file('poem.txt', 'w') # open for 'w'riting

f.write(poem) # write text to file

f.close() # close the file

f = file('poem.txt')

# if no mode is specified, 'r'ead mode is assumed by default

while True:

line = f.readline()

if len(line) == 0: # Zero length indicates EOF

break

print line,

# Notice comma to avoid automatic newline added by Python

f.close() # close the file

2、存储器

持久性

import cPickle as p

#import pickle as p

shoplistfile = 'shoplist.data'

# the name of the file where we will store the object

shoplist = ['apple', 'mango', 'carrot']

# Write to the file

f = file(shoplistfile, 'w')

p.dump(shoplist, f) # dump the object to a file

f.close()

del shoplist # remove the shoplist

# Read back from the storage

f = file(shoplistfile)

storedlist = p.load(f)

print storedlist

3、控制台输入

输入字符串 nID = raw_input("Input your id plz")

输入整数 nAge = int(raw_input("input your age plz: "))

输入浮点型 fWeight = float(raw_input("input your weight "))

输入16进制数据 nHex = int(raw_input('input hex value(like 0x20): '),16)

输入8进制数据 nOct = int(raw_input('input oct value(like 020): '),8)

八、异常

1、try..except

import sys

try:

s = raw_input('Enter something --> ')

except EOFError:

print ' Why did you do an EOF on me?'

sys.exit() # exit the program

except:

print ' Some error/exception occurred.'

# here, we are not exiting the program

print 'Done'

2、引发异常

使用raise语句引发异常。你还得指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类。

class ShortInputException(Exception):

'''A user-defined exception class.'''

def __init__(self, length, atleast):

Exception.__init__(self)

self.length = length

self.atleast = atleast

raise ShortInputException(len(s), 3)

3、try..finnally

import time

try:

f = file('poem.txt')

while True: # our usual file-reading idiom

line = f.readline()

if len(line) == 0:

break

time.sleep(2)

print line,

finally:

f.close()

print 'Cleaning up...closed the file'

九、Python标准库

1、sys库

sys模块包含系统对应的功能。sys.argv列表,它包含命令行参数。

2、os库

os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。

os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。

os.getenv()和os.putenv()函数分别用来读取和设置环境变量。

os.listdir()返回指定目录下的所有文件和目录名。

os.remove()函数用来删除一个文件。

os.system()函数用来运行shell命令。

os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用' ',Linux使用' '而Mac使用' '。

os.path.split()函数返回一个路径的目录名和文件名。

>>> os.path.split('/home/swaroop/byte/code/poem.txt')

('/home/swaroop/byte/code', 'poem.txt')

os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe()函数用来检验给出的路径是否真地存在。

希望本文所述对大家的Python程序设计有所帮助。

python新手入门教程-Python简明入门教程相关推荐

  1. python运行怎么下一步_简明Python3教程 18.下一步是什么

    如果你有认真通读本书之前的内容并且实践其中包含的大量例程,那么你现在一定可以熟练使用python了. 同时你可能也编写了一些程序用于验证python特性并提高你的python技能.如果还没有这样做的话 ...

  2. 简明python教程购买-简明Python3教程 6.基础

    你肯定不满足于只打印"Hello World"吧? 你想要的更多 - 你希望得到一些输入,操纵它后再从中得到某些东西. 我们可以使用python中的常量和变量实现这些功能. 字面常 ...

  3. matlab项目实例教程,matlab简明实例教程.doc

    matlab简明实例教程.doc 南京航空航天大学王正盛1MATLAB数学工具软件实例简明教程王正盛编写南京航空航天大学南京航空航天大学王正盛2第一章MATLAB简介MALAB译于矩阵实验室MATri ...

  4. python新手输出错误,Python 新手常犯错误(第一部分)

    用一个可变的值作为默认值 这是一个绝对值得放在第一个来说的问题.不仅仅是因为产生这种BUG的原因很微妙,而且这种问题也很难检查出来.思考一下下面的代码片段: def foo(numbers=[]): ...

  5. python pip-什么是pip?Python新手入门指南

    什么是 pip ?pip 是 Python 中的标准库管理器.它允许你安装和管理不属于 Python标准库 的其它软件包.本教程就是为 Python 新手介绍 pip. 通过本教程,你将学到: 1. ...

  6. bat批处理教程_超级详细教程

    bat批处理教程(1) 这是一篇技术教程,我会用很简单的文字表达清楚自己的意思,你要你识字就能看懂,就能学到知识.写这篇教程的目的,是让每一个看过这些文字的朋友记住一句话:如果爱可以让事情变的更简单, ...

  7. python简单入门_Python简明入门教程

    本文实例讲述了Python简明入门教程.分享给大家供大家参考.具体如下: 一.基本概念 1.数 在Python中有4种类型的数--整数.长整数.浮点数和复数. (1)2是一个整数的例子. (2)长整数 ...

  8. 编程入门python语言是多大孩子学的-不学点编程,将来怎么给孩子辅导作业―Python新手入门教程...

    为了填满AI时代的人才缺口,编程语言教育都从娃娃抓起了!如果你还不懂Python是什么将来怎么给孩子辅导作业呢? Python新手入门教程 近期,浙江省信息技术课程改革方案出台,Python言语现已断 ...

  9. python新手教程 从零开始-Python零基础从零开始学习Python十分钟快速入门

    原标题:Python零基础从零开始学习Python十分钟快速入门 学习Python的,都知道Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言.Python是一种动态解释型的 ...

最新文章

  1. Spring MVC前后端的数据传输
  2. 001-Spring Cloud Edgware.SR3 升级最新 Finchley.SR1,spring boot 1.5.9.RELEASE 升级2.0.4.RELEASE注意问题点...
  3. ustc小道消息20220102
  4. python 作用域嵌套_python嵌套作用域问题
  5. boost::allocator_void_pointer
  6. 面对面快传文件服务器恢复,QQ 面对面快传的传应用功能,如何找到已安装应用的安装包?...
  7. Python画图实战之画K线图【附带自动下载股票数据】
  8. Spring Security中关于认证授权的配置
  9. Jmeter工具使用-分布式架构和服务器性能监控解决方案
  10. 阶段3 3.SpringMVC·_07.SSM整合案例_04.ssm整合之编写SpringMVC框架
  11. 质量管理 六西格玛-黑带大师
  12. 官网下载InstallShield Limited Edition for Visual Studio
  13. erp系统实施方案会遇到哪些问题?
  14. 史上最全法则、效应大全,看一遍受用终身!
  15. der解码规则_[转] DER编码和ASN.1
  16. 帝国cms发布文章对哪些数据表做了操作
  17. SpringCloud五大神兽03-Hystrix断路器(豪猪)
  18. Dancing Line、网易蜗牛读书——创新性分析
  19. (数据库系统概论|王珊)第七章数据库设计-第三节:概念结构设计
  20. 涤纶电容的作用原理及优点缺点

热门文章

  1. 性能:15个JavaScript本地存储技术的函数库和工具
  2. 在两个页面间翻转设置Animation动作的一些总结
  3. 2010年3月4日参加由张应杭老师主讲的关于传统文化的培训-一个有益的PPT分享给大家...
  4. 自我学习SSM框架集成(二)
  5. 【bzoj3601】一个人的数论 莫比乌斯反演+莫比乌斯函数性质+高斯消元
  6. 第四篇[机器学习] 机器学习,线性回归的优化
  7. iOS 生日计算星座
  8. HashMap数据类型使用注意-不能使用基本数据类型
  9. Push Notification (1)Google C2DM 服务
  10. 面向对象编程的乐趣(TextBox.Text=)