广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Notes for python (2)
  • 527
分享到

Notes for python (2)

Notespython 2023-01-31 01:01:40 527人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

使用列表 例9.1 使用列表 #!/usr/bin/python # Filename: using_list.py # This is my shopping list shoplist = ['apple', '


使用列表

例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

--结束END--

本文标题: Notes for python (2)

本文链接: https://www.lsjlt.com/news/185143.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Notes for python (2)
    使用列表 例9.1 使用列表 #!/usr/bin/python # Filename: using_list.py # This is my shopping list shoplist = ['apple', '...
    99+
    2023-01-31
    Notes python
  • Notes for python (1)
      It's a great pleasure that recently I start to lean Python, hohohohooooooo^_^使用sys模块 #!/usr/bin/python # Filename...
    99+
    2023-01-31
    Notes python
  • C++程序员Python notes
    参考http://blog.chinaunix.net/uid/20039893/frmd/49956.html及其他一些网上资料,C++程序员的Python入门。 1. important getchas:     judge whe...
    99+
    2023-01-31
    程序员 Python notes
  • Skype For Business 2
    Skype For Business 2015实战系列3:安装并配置CA不管是Skype for business server 2015,还是以前的Lync,在部署的过程中一个绕不开的东西就是证书,不要说Skype for busines...
    99+
    2023-01-31
    Skype Business
  • Python(2)
    一、python是强类型语言:1、两个对象比较:(1)、身份(内存地址):两个对象的引用是否相同。 id(a)==id(b)或者a is b (2)、值:两个对象的数据是否相等。 a==b(3)、类型:两个对象的类型是否相同。 type(a...
    99+
    2023-01-31
    Python
  • BeatMark 2 for Mac工具有什么用
    这篇文章主要介绍BeatMark 2 for Mac工具有什么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!BeatMark 2 激活版可以将音频处理成带有节奏标记的.fcpxml文件,然后在FCPX软件里直接导入...
    99+
    2023-06-02
  • zero python.2
    1.使用函数 2.装饰器 3.异常处理 4.socket 1.使用函数  给函数传递参数时,可以灵活传递实参数量。形参在定义时,使用到列表、字典。# 定义函数 def f (hostip, port='52161'):     print(...
    99+
    2023-01-31
    python
  • 2 . python Collectio
    nametuple() 是具有命名字段的元组的工厂函数命名元组为元组中每个位置赋予含义,并允许更具可读性的自编写代码 它们可以在任何使用常规元组的地方使用,并且他们添加了按名称而不是位置索引访问字段的功能。用法:collections.na...
    99+
    2023-01-31
    python Collectio
  • selenium 2 + python
    在使用selenium 2的时候,经常会碰到打开一个页面后新页面以新窗口打开,因为脱离当前窗口需要重新定位窗口,可以用以下方法定位到需要的窗口。#父窗口是0 browser.switch_to_window(browser.window_h...
    99+
    2023-01-31
    selenium python
  • Django1.7+python 2.
    配置好virtualenv 和virtualenvwrapper后,使用pycharm创建新项目。之后要面临的问题就来了,之前一直使用的是sqlite作为开发数据库进行学习,按照之前看教程的原则,好像就是说开发环境要和生产环境尽量的一致,...
    99+
    2023-01-31
    python
  • Python 2 和 Python 3
      Guido(Python之父,仁慈的独裁者)在设计 Python3 的过程中,受一篇文章 “Python warts” 的影响,决定不向后兼容,否则无法修复大多数缺陷。---摘录自《流畅的Python》   你可能从来没有听说过学 J...
    99+
    2023-01-31
    Python
  • Patternodes 2 for Mac是一款什么工具
    这篇文章主要为大家展示了“Patternodes 2 for Mac是一款什么工具”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Patternodes 2 for Mac是一款什么工具”这篇文章...
    99+
    2023-06-05
  • #2 安装Python
    上一篇文章主要记录 了Python简介,相信你已经爱上了小P,俗话说的好:公欲善其事,必先利其器,所以本文将带领你安装Python3! Windows平台 1.确认Windows位数: 鼠标右击此电脑-->打开属性,如下图所示: ...
    99+
    2023-01-30
    Python
  • python 函数(2)
    一、内容回顾 1.面试题相关: 1.py2和py3的区别 2.运算符的计算 :3 or 9 and 8 3.字符串的反转 4.is和==的区别 5.v1 = (1) v2 = 1 v3 = (1,)有什么区别 v1 、v2都是数...
    99+
    2023-01-31
    函数 python
  • Python练习【2】
    题目1: 用Python实现队列(先入先出) 入队 出队 队头 队尾 队列是否为空 显示队列元素 代码: list=[] ##定义空列表用于存储数据 tip = """ ******队...
    99+
    2023-01-31
    Python
  • python 第2天
    import easygui,randomsecret = random.randint(1,99)easygui.msgbox("""I have a secret ,It is a number from 1-99 ,you have ...
    99+
    2023-01-31
    python
  • python练习2
    # 理论性1. 写出python中的几种分支结构,并解释其执行过程;2. 写出python中的几种循环结构,并解释其执行过程;3. python中是否支持switch语句   如果支持,写出该语句格式;   如果不支持,说说python中怎...
    99+
    2023-01-31
    python
  • 2.Python基础
    一.语句和语法 一.继续 (\) Python语句,一般使用换行分隔,也就是说一行一个语句, 一行过场的语句可以使用反斜杠"\" 分解成几行. 两种情况列外一个语句不使用反斜杠也可以跨行. 在使用闭合操作符时,单一语句可以哭啊多行....
    99+
    2023-01-31
    基础 Python
  • Python作业2
       1.分别取出0到10中的偶数和奇数。   2.判断一个数是否是质数 *程序*测试   3题目*程序*测试...
    99+
    2023-01-31
    作业 Python
  • ansible python api 2
     最近想利用python来调用anbile来实现一些功能,发现ansible的api已经升级到了2.0,使用上比以前复杂了许多。 这里我参考了官方文档的例子,做了一些整改,写了一个python调用ansible的函数,执行过程中输出执行结果...
    99+
    2023-01-31
    ansible python api
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作