Python简明入门教程
|
本文实例讲述了Python简明入门教程。分享给大家供大家参考。具体如下: 一、基本概念 1、数 在Python中有4种类型的数――整数、长整数、浮点数和复数。 2、字符串 (1)使用单引号(') '''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)转义符 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 for i in range(1,5): print i else: print 'The for loop is over' 4、break和continue 三、函数 1、定义与调用 def sayHello(): print 'Hello World!' # block belonging to the function sayHello() # call the function 2、函数形参
def printMax(a,b):
if a > b:
print a,'is maximum'
else:
print b,'is maximum'
3、局部变量 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()函数 五、数据结构 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 'nI 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 'nThere are %d contacts in the address-bookn' % 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 "nGuido's address is %s" % ab['Guido']
4、序列 列表、元组和字符串都是序列。序列的两个主要特点是索引操作符和切片操作符。 shoplist = ['apple','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','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',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赋值)因此是对象的变量。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
