前言

本教程综合Stanford CS231N和UC Berkerley CS188的Python教程。

教程非常短,但适合有一定编程基础。学过其它语言的童鞋。

Python

启动Python 解释器

Python能够有两种使用方式,一种就是使用解释器interpreter,相似Matlab。输入一行代码,执行一行;还有一种就是编写一个py后缀的文档。称为脚本,然后python xxx.py执行脚本script。这里我们使用解释器。

在已安装Python的情况下。在Terminal输入python,能够启动Python:

FloodSurges-MacBook-Pro:~ FloodSurge$ python
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

这里我是使用2.7.9版本号的Python

操作符

在Python解释器中,使用>>>来表示一行代码,相似Matlab(使用<<)

先是最主要的操作符+。-。*,/:

>>> 1 + 1
2
>>> 2 * 3
6
>>> 2 / 3
0
>>> 2 / 3.1
0.6451612903225806

接下来还有经常使用的次方运算,採用**

>>> 2 ** 2
4
>>> 2 ** 3
8

数据类型

Python和其它语言非常大的不同就是Python不须要定义数据类型,数据类型是依据数据的情况自行确定的。

比方上面的运算。输入3就是整型,输入3.1就是浮点数

数字

x=3

print type(x) # Prints "<type 'int'>"
print x # Prints "3"
print x + 1 # Addition; prints "4"
print x - 1 # Subtraction; prints "2"
print x * 2 # Multiplication; prints "6"
print x ** 2 # Exponentiation; prints "9"
x += 1
print x # Prints "4"

注意Python不支持x++或者x–的操作

布尔量Boolean

用True和False表示

f = False
print type(t) # Prints "<type 'bool'>"
print t and f # Logical AND; prints "False"
print t or f # Logical OR; prints "True"
print not t # Logical NOT; prints "False"

这里要注意Python中不使用&&, ||,。来表示与。或,非

而是直接使用英语and,or,not

>>> 1==0
False
>>> not (1==0)
True
>>> (2==2) and (2==3)
False
>>> (2==2) or (2==3)
True

字符串

hello = 'hello' # String literals can use single quotes
world = "world" # or double quotes; it does not matter.
print hello # Prints "hello"
print len(hello) # String length; prints "5"
hw = hello + ' ' + world # String concatenation
print hw # prints "hello world"
hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string format
in
print hw12 # prints "hello world 12

有非常多现成的方法对字符串进行操作:


print s.capitalize() # Capitalize a string; prints "Hello"
print s.upper() # Convert a string to uppercase; prints "HELLO"
print s.rjust(7) # Right-justify a string, padding with spaces;
print s.center(7) # Center a string, padding with spaces; prints
print s.replace('l', '(ell)') # Replace all instances of one substri
# prints "he(ell)(ell)o"
>>> 'artificial' + "intelligence"
'artificialintelligence'

其实,无论是用单引號还是双引號都是一样的。

>>> a = 'hello'
>>> a
'hello'
>>> b = "hello"
>>> b
'hello'
>>> a == b
True

那么,我们能够通过dir和help来查看某个类型相应的methods.

>>> a = 'hello'
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> help(a.find)
Help on built-in function find: find(...)
S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure.

上面的help之后按Q退出查看。

数据结构

List列表

>>> fruits = ['apple','orange','pear','banana']
>>> fruits[0]
'apple'

能够通过 + 来连接列表

>>> otherFruits = ['kiwi','strawberry']
>>> fruits + otherFruits
>>> ['apple', 'orange', 'pear', 'banana', 'kiwi', 'strawberry']

Python支持负值索引,比方fruits[-1]就是列表的最后一个。

>>> fruits[-2]
'pear'
>>> fruits.pop()
'banana'
>>> fruits
['apple', 'orange', 'pear']
>>> fruits.append('grapefruit')
>>> fruits
['apple', 'orange', 'pear', 'grapefruit']
>>> fruits[-1] = 'pineapple'
>>> fruits
['apple', 'orange', 'pear', 'pineapple']

接下来能够用:来检索多个数据:

>>> fruits[0:2]
['apple', 'orange']
>>> fruits[:3]
['apple', 'orange', 'pear']
>>> fruits[2:]
['pear', 'pineapple']
>>> len(fruits)
4

然后lists也能够嵌套:

>>> lstOfLsts = [['a','b','c'],[1,2,3],['one','two','three']]
>>> lstOfLsts[1][2]
3
>>> lstOfLsts[0].pop()
'c'
>>> lstOfLsts
[['a', 'b'],[1, 2, 3],['one', 'two', 'three']]

循环Loops:

animals = ['cat', 'dog', 'monkey']
for animal in animals:
 print animal
# Prints "cat", "dog", "monkey", each on its own line.

假设要获取每一个元素的索引值,使用枚举Enumerate:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
 print '#%d: %s' % (idx + 1, animal)
# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line

List Comprehension 从一个数据转换到还有一个数据:

>>> nums = [0,1,2,3,4]
>>> squares = []
>>> for x in nums:
... squares.append(x ** 2)
...
>>> print squares
[0, 1, 4, 9, 16]

也能够这么写:

>>> nums = [0,1,2,3,4]
>>> squares = [x**2 for x in nums]
>>> print squares
[0, 1, 4, 9, 16]

还能够包括条件:

nums = [0, 1, 2, 3, 4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print even_squares # Prints "[0, 4, 16]"

Tuple

相似List,但初始化之后就不可更改

>>> pair = (3,5)
>>> pair[0]
3
>>> x,y = pair
>>> x
3
>>> y
5
>>> pair[1] = 6
TypeError: object does not support item assignment

Set集合

Set集合没有顺序

>>> shapes = ['circle','square','triangle','circle']
>>> setOfShapes = set(shapes)
>>> setOfShapes
set(['circle','square','triangle'])
>>> setOfShapes.add('polygon')
>>> setOfShapes
set(['circle','square','triangle','polygon'])
>>> 'circle' in setOfShapes
True
>>> 'rhombus' in setOfShapes
False
>>> favoriteShapes = ['circle','triangle','hexagon']
>>> setOfFavoriteShapes = set(favoriteShapes)
>>> setOfShapes - setOfFavoriteShapes
set(['square','polyon'])
>>> setOfShapes & setOfFavoriteShapes
set(['circle','triangle'])
>>> setOfShapes | setOfFavoriteShapes
set(['circle','square','triangle','polygon','hexagon'])

Dictionary字典

相似java的Map。一个Key相应一个Value。

>>> studentIds = {'knuth': 42.0, 'turing': 56.0, 'nash': 92.0 }
>>> studentIds['turing']
56.0
>>> studentIds['nash'] = 'ninety-two'
>>> studentIds
{'knuth': 42.0, 'turing': 56.0, 'nash': 'ninety-two'}
>>> del studentIds['knuth']
>>> studentIds
{'turing': 56.0, 'nash': 'ninety-two'}
>>> studentIds['knuth'] = [42.0,'forty-two']
>>> studentIds
{'knuth': [42.0, 'forty-two'], 'turing': 56.0, 'nash': 'ninety-two'}
>>> studentIds.keys()
['knuth', 'turing', 'nash']
>>> studentIds.values()
[[42.0, 'forty-two'], 56.0, 'ninety-two']
>>> studentIds.items()
[('knuth',[42.0, 'forty-two']), ('turing',56.0), ('nash','ninety-two')]
>>> len(studentIds)
3

写脚本Script

就是新建一个文件,然后把后缀改成py。

然后在里面输入代码。比方foreach.py:

# This is what a comment looks like
fruits = ['apples','oranges','pears','bananas']
for fruit in fruits:
print fruit + ' for sale'
fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75}
for fruit, price in fruitPrices.items():
if price < 2.00:
print '%s cost %f a pound' % (fruit, price)
else:
print fruit + ' are too expensive!'

然后在terminal在相应路径下(记住不是在Python 解释器下执行)

python foreach.py
apples for sale
oranges for sale
pears for sale
bananas for sale
oranges cost 1.500000 a pound
pears cost 1.750000 a pound
apples are too expensive!

这里还有两个非常实用的map和filter方法:

>>> map(lambda x: x * x, [1,2,3])
[1, 4, 9]
>>> filter(lambda x: x > 3, [1,2,3,4,5,4,3,2,1])
[4, 5, 4]

注意空格

Python对语法要求非常高,比方for语句下一个语句要空格否则可能报错

>>> for x in nums:
... squares.append(x ** 2)
File "<stdin>", line 2
squares.append(x ** 2)
^
IndentationError: expected an indented block
>>> for x in nums:
... squares.append(x ** 2)

Function函数

fruitPrices = {'apples':2.00, 'oranges': 1.50, 'pears': 1.75}
def buyFruit(fruit, numPounds):
if fruit not in fruitPrices:
print "Sorry we don't have %s" % (fruit)
else:
cost = fruitPrices[fruit] * numPounds
print "That'll be %f please" % (cost)
# Main Function
if __name__ == '__main__':
buyFruit('apples',2.4)
buyFruit('coconuts',2)

Class 类

class FruitShop:
def __init__(self, name, fruitPrices):
"""
name: Name of the fruit shop
fruitPrices: Dictionary with keys as fruit
strings and prices for values e.g.
{'apples':2.00, 'oranges': 1.50, 'pears': 1.75}
"""
self.fruitPrices = fruitPrices
self.name = name
print 'Welcome to the %s fruit shop' % (name)
def getCostPerPound(self, fruit):
"""
fruit: Fruit string
Returns cost of 'fruit', assuming 'fruit'
is in our inventory or None otherwise
"""
if fruit not in self.fruitPrices:
print "Sorry we don't have %s" % (fruit)
return None
return self.fruitPrices[fruit]
def getPriceOfOrder(self, orderList):
"""
orderList: List of (fruit, numPounds) tuples
Returns cost of orderList. If any of the fruit are
"""
totalCost = 0.0
for fruit, numPounds in orderList:
costPerPound = self.getCostPerPound(fruit)
if costPerPound != None:
totalCost += numPounds * costPerPound
return totalCost
def getName(self):
return self.name

使用对象Object

在前面在shop.py定义了FruitShop类,接下来我们能够在另外的脚本中使用这个类:

採用import

mport shop
shopName = 'the Berkeley Bowl'
fruitPrices = {'apples': 1.00, 'oranges': 1.50, 'pears': 1.75}
berkeleyShop = shop.FruitShop(shopName, fruitPrices)
applePrice = berkeleyShop.getCostPerPound('apples')
print applePrice
print('Apples cost $%.2f at %s.' % (applePrice, shopName))
otherName = 'the Stanford Mall'
otherFruitPrices = {'kiwis':6.00, 'apples': 4.50, 'peaches': 8.75}
otherFruitShop = shop.FruitShop(otherName, otherFruitPrices)
otherPrice = otherFruitShop.getCostPerPound('apples')
print otherPrice
print('Apples cost $%.2f at %s.' % (otherPrice, otherName))
print("My, that's expensive!")

静态和实例变量

在person_class.py中输入:

class Person:
population = 0
def __init__(self, myAge):
self.age = myAge
Person.population += 1
def get_population(self):
return Person.population
def get_age(self):
return self.age

这里的population是一个静态变量,或者说是全局变量

执行例如以下:

>>> import person_class
>>> p1 = person_class.Person(12)
>>> p1.get_population()
1
>>> p2 = person_class.Person(63)
>>> p1.get_population()
2
>>> p2.get_population()
2
>>> p1.get_age()
12
>>> p2.get_age()
63

其它

使用range来循环:

  for index in range(3):

        print lst[index]

Python 学习之二:Python超短教程的更多相关文章

  1. Python学习之二:Python 与 C 区别

    引自http://www.lxway.com/181844.htm 从开始看Python到现在也有半个多月了,前后看了Python核心编程和Dive into Python两本书.话说半个月看两本,是 ...

  2. python学习笔记(二):python数据类型

    上一篇博客写了python的入门和简单流程控制,这次写python的数据类型和各种数据类型的内置方法.一.数据类型是什么鬼?计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各 ...

  3. python入门灵魂5问--python学习路线,python教程,python学哪些,python怎么学,python学到什么程度

    一.python入门简介 对于刚接触python编程或者想学习python自动化的人来说,基本都会有以下python入门灵魂5问--python学习路线,python教程,python学哪些,pyth ...

  4. python学习第九讲,python中的数据类型,字符串的使用与介绍

    目录 python学习第九讲,python中的数据类型,字符串的使用与介绍 一丶字符串 1.字符串的定义 2.字符串的常见操作 3.字符串操作 len count index操作 4.判断空白字符,判 ...

  5. python学习第五讲,python基础语法之函数语法,与Import导入模块.

    目录 python学习第五讲,python基础语法之函数语法,与Import导入模块. 一丶函数简介 1.函数语法定义 2.函数的调用 3.函数的文档注释 4.函数的参数 5.函数的形参跟实参 6.函 ...

  6. python学习第一讲,python简介

    目录 python学习第一讲,python简介 一丶python简介 1.解释型语言与编译型语言 2.python的特点 3.python的优缺点 二丶第一个python程序 1.python源程序概 ...

  7. python学习第三讲,python基础语法之注释,算数运算符,变量.

    目录 python学习第三讲,python基础语法之注释,算数运算符,变量. 一丶python中的基础语法,注释,算数运算符,变量 1.python中的注释 2.python中的运算符. 3.pyth ...

  8. python学习笔记(二)、字符串操作

    该一系列python学习笔记都是根据<Python基础教程(第3版)>内容所记录整理的 1.字符串基本操作 所有标准序列操作(索引.切片.乘法.成员资格检查.长度.最小值和最大值)都适用于 ...

  9. Python学习(二)Python 简介

    Python 简介 官方指南及文档 Python2.7官方指南(中文版):http://pan.baidu.com/s/1dDm18xr Python3.4官方指南(中文版):http://pan.b ...

随机推荐

  1. Android入门:用HttpClient模拟HTTP的GET和POST请求

    一.HttpClient介绍   HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器:   Android已经集成了HttpClient,因此可以直接使用: ...

  2. Android功能模块化之生成验证码Bitmap

    Android生成验证码Bitmap,主要使用Canvas绘制,实现的步骤如下: 1.生成验证码.主要采用java的随机函数生成序号,然后对应获取预设的Char数组的值,生成长度固定的验证码: 2.C ...

  3. Windows7 64位系统下无法安装网络打印机的解决方法

    背景: 公司一台HP LaserJet 1010 打印机连在一台Windows XP的电脑上,而我的是windows7 64位系统,无法安装驱动解决办法:1:去惠普官网上下载对应的64位驱动(什么Vi ...

  4. 基本输入输出系统BIOS---键盘输入

    基本输入输出系统BIOS概述 硬盘操作系统DOS建立在BIOS的基础上,通过BIOS操纵硬件,例如DOS调用BIOS显示I/O程序完成输入显示,调用打印I/O完成打印输出 通常应用程序应该调用DOS提 ...

  5. BSON与JSON的区别

    BSON是由10gen开发的一个数据格式,目前主要用于MongoDB中,是MongoDB的数据存储格式.BSON基于JSON格式,选择JSON进行改造的原因主要是JSON的通用性及JSON的schem ...

  6. PHP图像操作:3D图、缩放、旋转、裁剪、添加水印(三)

    来源:http://www.ido321.com/887.html 5.PHP对图像的旋转 1: <div> 2: <h4>旋转之前</h4> 3: <img ...

  7. IO-同步,异步,阻塞,非阻塞,阅读摘要

    http://www.cnblogs.com/Fly-Wind/p/io.html http://blog.csdn.net/historyasamirror/article/details/5778 ...

  8. ES6学习(1)——如何通过babel将ES6转化成ES5

    使用babel编译ES6 babel是一个工具,可以通过多个平台,让js文件从ES6转化成ES5,从而支持一些浏览器并未支持的语法. Insall babel $ sudo npm install b ...

  9. Linux数据流重定向

    一.什么是数据流重导向: 数据流重导向 (redirect) 由字面上的意思来看,好像就是将『数据传导到其他地方去』,没错-数据流重导向就是将某个命令运行后应该要出现在屏幕上的数据, 给他传输到其他的 ...

  10. iOS 开发的9个超有用小技巧

    http://www.jianshu.com/p/221507eb8590 1.如何快速的查看一段代码的执行时间. 1 2 #define TICK   NSDate *startTime = [NS ...