自己写的python学习例子

记录下自学python时写的小例子,这些例子基本上都是一本教程上面的,都是一些基本语法的例子



****************************************************************************************

var.py


#!/usr/bin/python

i=5

print i

i=i + 1

print i


s='''This is a multi-line string.

This is the second line.'''

print s


****************************************************************************************

expression.py


#!/usr/bin/python

length=5

breadth=3


area=length*breadth


print 'Area is',area

print 'Perimeter is',2*(length+breadth)


****************************************************************************************

if.py


#!/usr/bin/python


number = 23

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


if guess == number:

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

    print "(but you do not win any prizes!)" #New block

elif guess < number:

    print 'No, 123'

else:

    print 'none'

print 'Done'


****************************************************************************************

for.py


#!/usr/bin/python


for i in range(1,23):

    print i

else:

    print 'loop is over'


****************************************************************************************

while.py


#!/usr/bin/python


num=23

running=True


while running:

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

    if guess == num:

        print '='

        running=False

    elif guess < num:

        print "<"

    else:

        print ">"

else:

    print 'The loop is over'

print 'Done'


****************************************************************************************

break.py


#!/usr/bin/python


while True:

    s = raw_input('Enter something : ');

    if s == "quit":

        break

        print 'Length of the string is',len(s)

print "Done"


****************************************************************************************

continue.py


#!/usr/bin/python


while True:

    s=raw_input('Enter something:')

    if s=='quit':

break

    if len(s)<3:

continue

    print 'Input is of suffcient length'

#Do other kinds of processing here...


****************************************************************************************

function1.py


#!/usr/bin/python


def sayHello():

    print 'Hello World!'


sayHello()


****************************************************************************************

func_param.py


#!/usr/bin/python


def printMax(a,b):

    if a>b:

print a, 'is maximum'

    else:

print b, 'is maximum'


printMax(3,5)


x=5

y=8


printMax(x,y)


****************************************************************************************

func_local.py


#!/usr/bin/python


def func(x):

    print 'x is ',x

    x=2

    print 'Changed local x to ',x


x=50

func(x)

print 'x is still ',x


****************************************************************************************

func_default.py


#!/usr/bin/python


def func(x):

    print 'x is ',x

    x=2

    print 'Changed local x to ',x


x=50

func(x)

print 'x is still ',x


****************************************************************************************

func_doc.py


#!/usr/bin/python


def printMax(x,y):

    '''prints the maximum of two numbers.


    the two values must be intergers.'''

    x=int(x)

    y=int(y)

    if x>y:

print x,' is maximum'

    else:

print y,' is maximum'


printMax(3,5)

print printMax.__doc__


****************************************************************************************

func_global.py


#!/usr/bin/python


def func():

   global x


    print 'x is ',x

    x=2

    print 'Changed local x to ',x


x=50

func()

print 'Value of x is ',x


****************************************************************************************

func_key.py


#!/usr/bin/python


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

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


func(3,7)

func(24,c=32)

func(c=43,a=224)


****************************************************************************************

func_return.py


#!/usr/bin/python


def maximum(x,y):

    if x>y:

return x

    else:

return y


print maximum(3,5)


****************************************************************************************

using_name.py


#!/usr/bin/python


if __name__ == '__main__':

    print 'This program is being run by itself'

else:

    print 'I am being imported from another module'


****************************************************************************************

using_sys.py


#!/usr/bin/python


import sys


print 'The command line argements are: '

for i in sys.argv:

    print i

print '\n\nThe Python path is ',sys.path,'\n'


****************************************************************************************

using_list.py


#!/usr/bin/python


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


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

print 'These items are:'


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 is',shoplist

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


****************************************************************************************

mymodule.py

#!/usr/bin/python


def sayHi():

    print 'Hi, this is mymodule speaking.'


version='0.1'


mymodule_demo.py

#!/usr/bin/python


import mymodule


mymodule.sayHi()

print 'Version:',mymodule.version


mymodule_demo2.py

#!/usr/bin/python


from mymodule import sayHi,version


sayHi()

print 'Version',version


****************************************************************************************

using_tuple.py


#!/usr/bin/python


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

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


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

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

print 'All animals in new zoo here',new_zoo

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

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


****************************************************************************************

print_tulpe.py


#!/usr/bin/python


age=22

name='lucien'


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

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


****************************************************************************************

using_dict.py


#!/usr/bin/python


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']


#add

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

#delete

del ab['Spammer']


print '\nThere are %d contacts in the address-book\n'%len(ab)


for name,address in ab.items():

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


if 'Guido' in ab:

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

if ab.has_key('Guido'):

    print "\nGuido's address is %s 2"%ab['Guido']


****************************************************************************************

str_methods.py


#!/usr/bin/python


name='lucien'


if name.startswith('luc'):

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


if 'e' in name:

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


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

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


delimiter='_*_'

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

print delimiter.join(mylist)


****************************************************************************************

sed.py


#!/usr/bin/python


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


print 'Item 0 is',shoplist[0]

print 'Item 1 is',shoplist[1]

print 'Item 2 is',shoplist[2]

print 'Item 3 is',shoplist[3]

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

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



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[:]


name='swaroop'

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

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

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

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


****************************************************************************************

reference.py


#!/usr/bin/python


print 'Simple Assignment'

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

mylist=shoplist


del shoplist[0]


print 'shoplist is',shoplist

print 'mylist is',mylist


print 'Copy by making a full slice'

mylist=shoplist[:]

del mylist[0]


print 'shoplist is',shoplist

print 'mylist is',mylist


****************************************************************************************

simplest_class.py


#!/usr/bin/python


class Person:

    pass


p = Person()

print p


****************************************************************************************

method.py


#!/usr/bin/python


class Person:

    def sayHi(self):

        print 'Hello, how are you?'


p = Person()

p.sayHi()


****************************************************************************************

class_init.py


#!/usr/bin/python


class Person():

    def __init__(self,name):

        self.name = name

    def sayHi(self):

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


p = Person('lucien')

p.sayHi()


****************************************************************************************

objvar.py


#!/usr/bin/python


class Person():

    '''Represents a person.'''

    population = 0

    def __init__(self, name):

        '''Initializes the person' data'''

        self.name = name

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


        Person.population += 1


    def __del__(self):

        '''I am dying.'''

        print '%s says bye.' % self.name

        Person.population -= 1


        if Person.population == 0:

            print 'I am the last one'

        else:

            print 'There are still %d people left.' % Person.population


    def sayHi(self):

        '''Greeting by the person.


        Really,that's all it does'''

        print 'Hi,my name is %s.' % self.name


    def howMany(self):

        '''Prints the current population'''

        if Person.population == 1:

            print 'I am the only person here.'

        else:

            print 'We have %d persons here.' % Person.population

        print ''


lucien = Person('lucien')

lucien.sayHi()

lucien.howMany()


kitty = Person('Bell Kitty')

kitty.sayHi()

kitty.howMany()


lucien.sayHi()

lucien.howMany()


print Person.__doc__

print Person.sayHi.__doc__


****************************************************************************************

inherit.py


#!/usr/bin/python


class SchoolMember:

    '''Represents any school member'''

    def __init__(self, name, age):

        self.name = name

        self.age = age

        print '(init schoolMember:%s)'%self.name

    

    def tell(self):

        '''Tell my details'''

        print 'Name:"%s" Age:"%s"'%(self.name,self.age)


class Teacher(SchoolMember):

    '''Represents a teacher.'''

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

        SchoolMember.__init__(self,name,age)

        self.salary = salary

        print '(init Teacher:%s)'%self.name

    

    def tell(self):

        SchoolMember.tell(self)

        print 'Salary:"%d"'%self.salary


class Student(SchoolMember):

    '''Represents a student.'''

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

        SchoolMember.__init__(self, name, age)

        self.marks = marks

        print '(init student:%s)'%self.name


    def tell(self):

        SchoolMember.tell(self)

        print 'Marks: "%d"'%self.marks


t = Teacher('zds',40,3000)

s = Student('lx', 23, 90)


print


members = [t,s]

for member in members:

    member.tell()


****************************************************************************************

picking.py


#!/usr/bin/python


#import cPickle as p

import pickle as p


shopListFile = 'shoplist.data'

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


f = file(shopListFile,'w')

p.dump(shoplist,f)

f.close()


f = file(shopListFile, 'w')


p.dump(shoplist, f)

f.close()


del shoplist


f = file(shopListFile)

storedlist = p.load(f)

print storedlist


****************************************************************************************

using_file.py


#!/usr/bin/python


poem = '''\

Programming is fun

When the work is done

if you wanna make your work also fun:

    use Python!

'''

f = file('poem.txt','w')

f.write(poem)

f.close()


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:

        break

    print line,

    # Notice comma to avoid automatic newline added by Python

f.close()


****************************************************************************************

try_except.py


#!/usr/bin/python


import sys


try:

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

except EOFError:

    print '\nWhy did you do an EOF on me?'

    sys.exit()

except:

    print '\nSome error/exception occurred.'

print 'Done'


****************************************************************************************

raising.py


#!/usr/bin/python


class ShortInputException(Exception):

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

    def __init__(self, length, atleast):

        Exception.__init__(self)

        self.length = length

        self.atleast = atleast


try:

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

    if len(s) < 3:

        raise ShortInputException(len(s),3)

except EOFError:

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

except ShortInputException,x:

    print 'ShortInputException: The input was of length %d, I was expecting at least %d' % (x.length,x.atleast)


else:

    print 'No exception was raised'


****************************************************************************************

finally.py


#!/usr/bin/python


import time


try:

    f = file('poem.txt')

    while True:

        line = f.readline()

        if len(line) == 0:

            break

        time.sleep(2)

        print line,

finally:

    f.close()

    print 'clean up...'


****************************************************************************************

cat.py


#!/usr/bin/python


import sys

import os


def readfile(filename):

    '''Print a file to the standard output.'''

    f = file(filename)

    while True:

        line = f.readline()

        if len(line) == 0:

            break

        print line,

    f.close()


# Script starts from here

print os.getcwd()

print os.name

print os.path.split('/home/lucien/test/py_test/poem.txt')

if sys.argv[1].startswith('--'):

    option = sys.argv[1][2:]

    if option == 'version':

        print 'Version 1.2'

    elif option == 'help':

        print '''\

This program prints files to the standard output.

Any number of files can be specified.

Options include:

    --version : Prints the versioin number

    --help : Display this help'''

    else:

        print 'Unknown option.'

    sys.exit()

else:

    for filename in sys.argv[1:]:

        readfile(filename)


****************************************************************************************

list_comprehension.py


#!/usr/bin/python


listone=[2,3,4]

listtwo=[2*i for i in listone if i > 2]


print listtwo


****************************************************************************************

lambda.py


#!/usr/bin/python


def make_repeater(n):

    return lambda s:s*n


twice=make_repeater(2)


print twice('word')

print twice(5)




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值