文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Notes for python (2)

2023-01-31 01:58

关注

使用列表

例9.1 使用列表
#!/usr/bin/python
# Filename: using_list.py

# This is my shopping list

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
(源文件:code/using_list.py)

输出

$ python using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']


使用元组

例9.2 使用元组
#!/usr/bin/python
# Filename: using_tuple.py


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]
(源文件:code/using_tuple.py)

输出

$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin

使用字典

例9.4 使用字典
#!/usr/bin/python
# Filename: using_dict.py

# 'ab' is short for 'a'ddress'b'ook


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-book\n' % 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']
(源文件:code/using_dict.py)

输出

$ python using_dict.py
Swaroop's address is swaroopch@byteofpython.info

There are 4 contacts in the address-book

Contact Swaroop at swaroopch@byteofpython.info
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Contact Guido at guido@python.org

Guido's address is guido@python.org



使用序列

例9.5 使用序列
#!/usr/bin/python
# Filename: seq.py


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

# Indexing or 'Subscription' operation
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]

# 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[:]
(源文件:code/seq.py)

输出

$ python seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop



Create a python script----backup files into archives

#!/usr/bin/python
#Filename : backup.py
import os
import time

#source list
source = ['/Users/chengflandy/src/python','/Users/chengflandy/src/lsw/frontend/html']

#target directory
target_dir = "/Users/chengflandy/src/backup/"

#today is the name of the sub backup directory
today = target_dir + time.strftime("%Y%m%d")

#current time is the name of the zip archive
now = time.strftime("%H%M%S")

#take a comment fron the user to create the zp
comment = raw_input("Enter a comment for the archive->")

#create the subdirectory if not exists
if not os.path.exists(today):
  os.mkdir(today)
  print "Successfully created directory:",today
  
#the name of the zip file
if len(comment) == 0:
  target = today+os.sep+now+".zip"
else:
  target = today+os.sep+now+"_"+comment.replace(' ','_')+".zip"

#use the zip command to zip
zip_command = "zip -qr %s %s" % (target,' '.join(source))

#run the command
if os.system(zip_command) == 0:
  print "Successful backup to ",target
else:
  print "Back failed"

使用类与对象的变量

#!/usr/bin/python
# Filename: objvar.py

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

        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

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany()

使用继承

#!/usr/bin/python
# Filename: inherit.py

class SchoolMember:
        '''Represents any school member.'''
        def __init__(self, name, age):
                self.name = name
                self.age = age
                print '(Initialized 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 '(Initialized 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 '(Initialized Student: %s)' % self.name

        def tell(self):
                SchoolMember.tell(self)
                print 'Marks: "%d"' % self.marks

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)

print # prints a blank line

members = [t, s]
for member in members:
        member.tell() # works for both Teachers and Students

prepare to learm input/output stream next time
http://linux.chinaitlab.com/manual/Python_chinese/ch12.html

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯