由彩云小译自动翻译自Project 0: Unix/Python/Autograder Tutorial,这是一个来自加州伯克利的教程,感觉质量颇为不错~

Python 基础

Required Files


You can download all of the files associated with the Python mini-tutorial as a zip archive: python_basics.zip. If you did the unix tutorial in the previous tab, you’ve already downloaded and unzipped this file.

您可以将与 Python 迷你教程相关的所有文件作为 zip 归档文件下载: python_basics.zip。如果您在上一个选项卡中学习了 unix 教程,那么您已经下载并解压缩了这个文件。

Table of Contents


The programming assignments in this course will be written in Python, an interpreted, object-oriented language that shares some features with both Java and Scheme. This tutorial will walk through the primary syntactic constructions in Python, using short examples.

本课程的编程作业将使用 Python 编写,Python 是一种解释型面向对象语言,与 Java 和 Scheme 共享一些特性。本教程将使用简短的例子介绍 Python 中的主要语法结构。

We encourage you to type all python shown in the tutorial onto your own machine. Make sure it responds the same way.

我们鼓励您在自己的机器上键入教程中所示的所有 python。确保它以同样的方式作出反应。

You may find the Troubleshooting section helpful if you run into problems. It contains a list of the frequent problems previous CS188 students have encountered when following this tutorial.

如果遇到问题,您可能会发现故障排除部分很有帮助。它包含了以前 CS188学生在学习本教程时经常遇到的问题列表。

Invoking the Interpreter 调用解释器

Python can be run in one of two modes. It can either be used interactively, via an interpeter, or it can be called from the command line to execute a script. We will first use the Python interpreter interactively.

Python 可以以两种模式之一运行。它既可以通过 interpeter 交互地使用,也可以通过命令行调用来执行脚本。我们将首先交互地使用 Python 解释器。

You invoke the interpreter by entering python at the Unix command prompt.
Note: you may have to type python2.4, python2.5, python2.6 or python2.7, rather than python, depending on your machine.

您可以在 Unix 命令提示符下输入 python 来调用解释器。注意: 您可能需要输入 python2.4、 python2.5、 python2.6或 python2.7,而不是 python,这取决于您的机器。

[cs188-ta@nova ~]$ python
Python 2.6.5 (r265:79063, Jan 14 2011, 14:20:15)
[GCC 4.4.1] on sunos5
Type "help", "copyright", "credits" or "license" for more information.

Operators 操作员

The Python interpreter can be used to evaluate expressions, for example simple arithmetic expressions. If you enter such expressions at the prompt (>>>) they will be evaluated and the result will be returned on the next line.

Python 解释器可用于计算表达式,例如简单的算术表达式。如果您在提示符(> > > >)中输入这样的表达式,它们将被计算,结果将在下一行中返回。

>>> 1 + 1
>>> 2 * 3

Boolean operators also exist in Python to manipulate the primitive True and False values.

Python 中还存在布尔运算符来操作原语 True 和 False 值。

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

Strings 弦乐

Like Java, Python has a built in string type. The + operator is overloaded to do string concatenation on string values.

和 Java 一样,Python 有一个内置的字符串类型。重载 + 运算符以对字符串值执行字符串连接。

>>> 'artificial' + "intelligence"

There are many built-in methods which allow you to manipulate strings.


>>> 'artificial'.upper()
>>> 'HELP'.lower()
>>> len('Help')

Notice that we can use either single quotes ' ' or double quotes " " to surround string. This allows for easy nesting of strings.


We can also store expressions into variables.


>>> s = 'hello world'
>>> print s
hello world
>>> s.upper()
>>> len(s.upper())
>>> num = 8.0
>>> num += 2.5
>>> print num

In Python, you do not have declare variables before you assign to them.

在 Python 中,在为变量赋值之前没有声明变量。

Exercise: Dir and Help 运动: 导师和帮助

Learn about the methods Python provides for strings. To see what methods Python provides for a datatype, use the dir and help commands:

了解 Python 为字符串提供的方法。要查看 Python 为数据类型提供了哪些方法,请使用 dir 和 help 命令:

>>> s = 'abc'

>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__','__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__','__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind','rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

>>> help(s.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.

>> s.find('b')

Try out some of the string functions listed in dir (ignore those with underscores ‘_’ around the method name).

尝试使用 dir 中列出的一些字符串函数(忽略方法名周围带有下划线“ _”的函数)。

Built-in Data Structures 内置数据结构

Python comes equipped with some useful built-in data structures, broadly similar to Java’s collections package.

Python 配备了一些有用的内置数据结构,与 Java 的集合包大致相似。

Lists 名单

Lists store a sequence of mutable items:


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

水果[‘苹果’、‘桔子’、‘梨’、‘香蕉’] > 水果[0]‘苹果’

We can use the + operator to do list concatenation:

我们可以使用 + 运算符来串联待办事项列表:

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

其他水果[‘猕猴桃’ ,‘草莓’] > > 水果 + 其他水果 > [‘苹果’ ,‘橘子’ ,‘梨’ ,‘香蕉’ ,‘猕猴桃’ ,‘草莓’]

Python also allows negative-indexing from the back of the list. For instance, fruits[-1] will access the last element 'banana':

Python 还允许在列表后面进行负索引。例如,fruits [-1]将访问最后一个元素‘ banana’ :

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

水果[-2]‘梨’ > > 水果[-2]‘香蕉’ > > > 水果[苹果’、‘橘子’、‘梨’] > > 水果(‘柚子’) > 水果[苹果’、‘橘子’、‘梨’、‘柚子’] > 水果[-1] = ‘菠萝’ > > 水果[‘苹果’、‘橘子’、‘梨’、‘梨’]

We can also index multiple adjacent elements using the slice operator. For instance, fruits[1:3], returns a list containing the elements at position 1 and 2. In general fruits[start:stop] will get the elements in start, start+1, ..., stop-1. We can also do fruits[start:] which returns all elements starting from the start index. Also fruits[:end] will return all elements before the element at position end:

我们也可以使用切片运算符来索引多个相邻的元素。例如,fruits [1:3]返回一个包含位于位置1和2的元素的列表。一般来说,水果[开始: 停止]会使元素开始,开始 + 1,… ,停止-1。我们还可以做 fruits [ start: ] ,它返回从 start 索引开始的所有元素。还有 fruits [ : end ]将返回位于位置末尾的元素之前的所有元素:

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

水果[0:2][苹果,橙子] > 水果[3][苹果,橙子,梨] > 水果[2: ][梨,菠萝] > > 水果(水果)

The items stored in lists can be any Python data type. So for instance we can have lists of lists:

存储在 list 中的条目可以是任何 Python 数据类型:

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

Exercise: Lists

练习: 列表

Play with some of the list functions. You can find the methods you can call on an object via the dir and get information about them via the help command:

使用一些列表函数。你可以通过 dir 找到你可以调用的方法,并通过 help 命令获得关于它们的信息:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
'__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__',
'__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__',
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',

>>> help(list.reverse)
Help on built-in function reverse:

    L.reverse() -- reverse *IN PLACE*

>>> lst = ['a','b','c']
>>> lst.reverse()
>>> ['c','b','a']

Note: Ignore functions with underscores “_” around the names; these are private helper methods. Press ‘q’ to back out of a help screen.

注意: 名称周围带下划线“ _”的忽略函数; 这些是私有的 helper 方法。按“ q”退出帮助屏幕。

Tuples 元组

A data structure similar to the list is the tuple, which is like a list except that it is immutable once it is created (i.e. you cannot change its content once created). Note that tuples are surrounded with parentheses while lists have square brackets.

与列表类似的数据结构是 tuple,它类似于一个列表,只是一旦创建了它,它就是不可变的(也就是说,一旦创建了它,就不能更改它的内容)。注意,元组被括号括起来,而列表有方括号。

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

The attempt to modify an immutable structure raised an exception. Exceptions indicate errors: index out of bounds errors, type errors, and so on will all report exceptions in this way.

修改不可变结构的尝试引发了异常。异常表示错误: 索引超出界限错误、类型错误等等都将以这种方式报告异常。

Sets 集合

A set is another data structure that serves as an unordered list with no duplicate items. Below, we show how to create a set, add things to the set, test if an item is in the set, and perform common set operations (difference, intersection, union):

集合是另一种数据结构,它作为无序列表,没有重复的项目。下面,我们将展示如何创建一个集合,如何向集合中添加内容,如何测试一个项是否在集合中,以及如何执行常见的集合操作(差异、交集、并集) :

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

Note that the objects in the set are unordered; you cannot assume that their traversal or print order will be the same across machines!

请注意,集合中的对象是无序的; 您不能假定它们的遍历或打印顺序在机器之间是相同的!

Dictionaries 字典

The last built-in data structure is the dictionary which stores a map from one type of object (the key) to another (the value). The key must be an immutable type (string, number, or tuple). The value can be any Python data type.

最后一个内置的数据结构是字典,它存储从一种类型的对象(键)到另一种类型(值)的映射。键必须是不可变类型(字符串、数字或元组)。该值可以是任何 Python 数据类型。

Note: In the example below, the printed order of the keys returned by Python could be different than shown below. The reason is that unlike lists which have a fixed ordering, a dictionary is simply a hash table for which there is no fixed ordering of the keys (like HashMaps in Java). The order of the keys depends on how exactly the hashing algorithm maps keys to buckets, and will usually seem arbitrary. Your code should not rely on key ordering, and you should not be surprised if even a small modification to how your code uses a dictionary results in a new key ordering. <!–(see the FAQ about dictionary key ordering). –>

注意: 在下面的示例中,Python 返回的键的打印顺序可能与下面所示的不同。原因在于,与具有固定顺序的列表不同,字典只是一个哈希表,其键的顺序不固定(如 Java 中的 HashMaps)。键的顺序取决于哈希算法如何准确地将键映射到存储桶,这通常看起来是任意的。您的代码不应该依赖于键顺序,而且即使对代码使用字典的方式进行一个小的修改,也会导致新的键顺序,您也不应该感到惊讶。

>>> studentIds = {'knuth': 42.0, 'turing': 56.0, 'nash': 92.0 }
>>> studentIds['turing']
>>> 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)

图灵: 56.0,‘ nash’ : 92.0 > > > 学习资料[‘ turing’]56.0 > > > 学习资料[‘ nash’] = ‘92’ > > > > 学习资料{‘ knuth’ : 42.0,‘ turing’ : 56.0,‘92’} > > 德尔学习资料[‘ knuth’]56.0,‘ nash’ : ‘92’} > > studentIds [‘ knuth’] = [42.0,‘ forty-two’] > studentIds {‘ knuth’ : [42.0,‘ forty-two’] ,‘ turing’ : 56.0,‘ nash’ : ‘92’} > > > 学习资料。Keys ()[‘ knuth’ ,‘ turing’ ,‘ nash’] > > studentIds。价值观[42.0,‘ forty-two’] ,56.0,‘92’] > > 学生。(‘ knuth’ ,[42.0,‘ forty-two’](‘ knuth’ ,[42.0,‘ forty-two’]) ,(‘ turing’ ,56.0) ,(‘ nash’ ,‘92’)] > len (studenids)3

As with nested lists, you can also create dictionaries of dictionaries.


Exercise: Dictionaries

练习: 字典

Use dir and help to learn about the functions you can call on dictionaries.

使用 dir 并帮助了解可以调用字典的函数。

Writing Scripts 写脚本

Now that you’ve got a handle on using Python interactively, let’s write a simple Python script that demonstrates Python’s for loop. Open the file called foreach.py and update it with the following code:

现在您已经掌握了交互式使用 Python 的处理方法,接下来让我们编写一个简单的 Python 脚本来演示 Python 的 for 循环。打开名为 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)
        print fruit + ' are too expensive!'

At the command line, use the following command in the directory containing foreach.py:

在命令行中,在包含 foreach.py 的目录中使用以下命令:

[cs188-ta@nova ~/tutorial]$ 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!

Remember that the print statements listing the costs may be in a different order on your screen than in this tutorial; that’s due to the fact that we’re looping over dictionary keys, which are unordered. To learn more about control structures (e.g., if and else) in Python, check out the official Python tutorial section on this topic.

请记住,列出成本的 print 语句在屏幕上的顺序可能与本教程中的顺序不同; 这是因为我们在字典键上循环,而这些键是无序的。要了解 Python 中控制结构(例如 if 和 else)的更多信息,请查看关于这个主题的 Python 官方教程部分。

If you like functional programming you might also like map and filter:

如果你喜欢函数式编程,你可能也喜欢 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]

You can learn more about lambda if you’re interested.

如果你感兴趣,你可以学习更多关于 lambda 的知识。

The next snippet of code demonstrates Python’s list comprehension construction:

下一个代码片段演示了 Python 的列表内涵结构:

nums = [1,2,3,4,5,6]
plusOneNums = [x+1 for x in nums]
oddNums = [x for x in nums if x % 2 == 1]
print oddNums
oddNumsPlusOne = [x+1 for x in nums if x % 2 ==1]
print oddNumsPlusOne

This code is in a file called listcomp.py, which you can run:

这段代码位于一个名为 listcomp.py 的文件中,你可以运行它:

[cs188-ta@nova ~]$ python listcomp.py

Exercise: List Comprehensions

练习: 列表理解

Write a list comprehension which, from a list, generates a lowercased version of each string that has length greater than five. You can find the solution in listcomp2.py.

写一个列表内涵,从列表中生成每个长度大于5的字符串的小写版本。您可以在 listcomp2.py 中找到解决方案。

Beware of Indendation! 小心契约

Unlike many other languages, Python uses the indentation in the source code for interpretation. So for instance, for the following script:

与许多其他语言不同,Python 使用源代码中的缩进进行解释。例如,下面的脚本:

if 0 == 1: 
    print 'We are in a world of arithmetic pain' 
print 'Thank you for playing' 

will output


Thank you for playing

But if we had written the script as


if 0 == 1: 
    print 'We are in a world of arithmetic pain'
    print 'Thank you for playing'

there would be no output. The moral of the story: be careful how you indent! It’s best to use four spaces for indentation — that’s what the course code uses.

不会有输出。这个故事的寓意是: 注意缩进的方式!最好使用四个空格进行缩进——这就是课程代码使用的空格。

Tabs vs Spaces 制表符 vs 空间

Because Python uses indentation for code evaluation, it needs to keep track of the level of indentation across code blocks. This means that if your Python file switches from using tabs as indentation to spaces as indentation, the Python interpreter will not be able to resolve the ambiguity of the indentation level and throw an exception. Even though the code can be lined up visually in your text editor, Python “sees” a change in indentation and most likely will throw an exception (or rarely, produce unexpected behavior).

因为 Python 使用缩进进行代码评估,所以它需要跟踪代码块之间的缩进级别。这意味着,如果 Python 文件从使用制表符缩进切换到使用空格缩进,Python 解释器将无法解决缩进级别的不确定性并抛出异常。即使代码可以在文本编辑器中直观地排列,Python 仍然可以“看到”缩进中的变化,并且很可能会引发异常(或者很少会产生意外的行为)。

This most commonly happens when opening up a Python file that uses an indentation scheme that is opposite from what your text editor uses (aka, your text editor uses spaces and the file uses tabs). When you write new lines in a code block, there will be a mix of tabs and spaces, even though the whitespace is aligned. For a longer discussion on tabs vs spaces, see this discussion on StackOverflow.

这种情况通常发生在打开使用缩进方案的 Python 文件时,该方案与文本编辑器使用的方案相反(也就是说,文本编辑器使用空格,文件使用制表符)。当您在代码块中编写新行时,将会出现制表符和空格的混合,即使空格是对齐的。有关制表符 vs 空格的更长的讨论,请参阅 StackOverflow 上的讨论。

Writing Functions 写作功能

As in Java, in Python you can define your own functions:

和 Java 一样,在 Python 中你可以定义你自己的函数:

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)
        cost = fruitPrices[fruit] * numPounds
        print "That'll be %f please" % (cost)

# Main Function
if __name__ == '__main__':        

Rather than having a main function as in Java, the __name__ == '__main__' check is used to delimit expressions which are executed when the file is called as a script from the command line. The code after the main check is thus the same sort of code you would put in a main function in Java.

与 Java 中的 main 函数不同,当从命令行以脚本形式调用文件时,使用 _ name _ = = ‘ _ main _’检查来分隔执行的表达式。因此,主检查之后的代码与您在 Java 中放入 main 函数的代码类型相同。

Save this script as fruit.py and run it:

将此脚本保存为 fruit.py 并运行它:

[cs188-ta@nova ~]$ python fruit.py
That'll be 4.800000 please
Sorry we don't have coconuts

Advanced Exercise


Write a quickSort function in Python using list comprehensions. Use the first element as the pivot. You can find the solution in quickSort.py.

使用列表理解在 Python 中编写一个快速排序函数。使用第一个元素作为枢轴。您可以在 quickSort.py 中找到解决方案。

Object Basics 对象基础

Although this isn’t a class in object-oriented programming, you’ll have to use some objects in the programming projects, and so it’s worth covering the basics of objects in Python. An object encapsulates data and provides functions for interacting with that data.

尽管这不是一个面向对象程序设计的类,但是你必须在编程项目中使用一些对象,所以这值得学习 Python 中对象的基础知识。对象封装数据并提供与该数据交互的函数。

Defining Classes 定义类

Here’s an example of defining a class named FruitShop:

下面是定义一个名为 FruitShop 的类的例子:

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

The FruitShop class has some data, the name of the shop and the prices per pound of some fruit, and it provides functions, or methods, on this data. What advantage is there to wrapping this data in a class?

FruitShop 类有一些数据,商店的名称和一些水果的每磅价格,并且它在这些数据上提供函数或方法。在类中包装这些数据有什么好处?

  1. Encapsulating the data prevents it from being altered or used inappropriately, 封装数据可以防止数据被修改或不恰当地使用,
  2. The abstraction that objects provide make it easier to write general-purpose code. 对象提供的抽象使得编写通用代码更加容易

Using Objects 使用对象

So how do we make an object and use it? Make sure you have the FruitShop implementation in shop.py. We then import the code from this file (making it accessible to other scripts) using import shop, since shop.py is the name of the file. Then, we can create FruitShop objects as follows:

那么,我们如何制作一个物体并使用它呢?确保在 shop.py 中有 FruitShop 实现。然后,我们使用 import shop 从该文件导入代码(使其他脚本可以访问该文件) ,因为 shop.py 是该文件的名称。然后,我们可以像下面这样创建 FruitShop 对象:

import 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!")

This code is in shopTest.py; you can run it like this:

这段代码在 shopTest.py 中,你可以这样运行:

[cs188-ta@nova ~]$ python shopTest.py
Welcome to the Berkeley Bowl fruit shop
Apples cost $1.00 at the Berkeley Bowl.
Welcome to the Stanford Mall fruit shop
Apples cost $4.50 at the Stanford Mall.
My, that's expensive!

So what just happended? The import shop statement told Python to load all of the functions and classes in shop.py. The line berkeleyShop = shop.FruitShop(shopName, fruitPrices) constructs an instance of the FruitShop class defined in shop.py, by calling the __init__ function in that class. Note that we only passed two arguments in, while __init__ seems to take three arguments: (self, name, fruitPrices). The reason for this is that all methods in a class have self as the first argument. The self variable’s value is automatically set to the object itself; when calling a method, you only supply the remaining arguments. The self variable contains all the data (name and fruitPrices) for the current specific instance (similar to this in Java). The print statements use the substitution operator (described in the Python docs if you’re curious).

刚才发生了什么?Import shop 语句告诉 Python 加载 shop.py 中的所有函数和类。商店等于商店。FruitShop (shopName,fruitPrices)通过调用 shop.py 中的 _ init _ function,构造了 FruitShop 类的实例。注意,我们只传递了两个参数,而 _ init _ 似乎有三个参数: (self,name,fruitPrices)。这是因为类中的所有方法都以 self 作为第一个参数。Self 变量的值自动设置为对象本身; 在调用方法时,只提供其余的参数。Self 变量包含当前特定实例的所有数据(name 和 fruitPrices)(与 Java 中的类似)。Print 语句使用替换操作符(如果您感兴趣,可以在 Python 文档中进行描述)。

Static vs Instance Variables 静态变量 vs 实例变量

The following example illustrates how to use static and instance variables in Python.

下面的示例说明如何在 Python 中使用静态和实例变量。

Create the person_class.py containing the following code:

创建包含以下代码的 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

We first compile the script:


[cs188-ta@nova ~]$ python person_class.py

Now use the class as follows:


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

In the code above, age is an instance variable and population is a static variable. population is shared by all instances of the Person class whereas each instance has its own age variable.

在上面的代码中,年龄是一个实例变量,人口是一个静态变量。由 Person 类的所有实例共享,而每个实例都有自己的 age 变量。

More Python Tips and Tricks 更多 Python 技巧和窍门

This tutorial has briefly touched on some major aspects of Python that will be relevant to the course. Here are some more useful tidbits:

本教程简要介绍了与本课程相关的 Python 的一些主要方面。下面是一些更有用的花絮:

  • Use 使用range to generate a sequence of integers, useful for generating traditional indexed 生成一个整数序列,用于生成传统的索引for loops: 循环:
    for index in range(3):
        print lst[index]
  • After importing a file, if you edit a source file, the changes will not be immediately propagated in the interpreter. For this, use the 导入文件后,如果编辑源文件,则不会立即在解释器中传播更改。为此,请使用reload command: 命令:

    >>> reload(shop)

Troubleshooting 故障排除

These are some problems (and their solutions) that new Python learners commonly encounter.

这些是新的 Python 学习者经常遇到的一些问题(及其解决方案)。

  • Problem:
    ImportError: No module named py

    问题: ImportError: 没有名为 py 的模块

    When using import, do not include the “.py” from the filename.
    For example, you should say: import shop
    NOT: import shop.py

    解决方案: 当使用 import 时,不要在文件名中包含“ . py”

  • Problem:
    NameError: name ‘MY VARIABLE’ is not defined
    Even after importing you may see this.

    问题: 名称错误: 名称’我的变量’没有定义即使导入后,你可能会看到这一点。

    To access a member of a module, you have to type MODULE NAME.MEMBER NAME, where MODULE NAME is the name of the .py file, and MEMBER NAME is the name of the variable (or function) you are trying to access.

    解决方案: 要访问模块的成员,必须键入 modulename.member NAME,其中 modulename 是。Py 文件,而 MEMBER NAME 是您试图访问的变量(或函数)的名称。

  • Problem:
    TypeError: ‘dict’ object is not callable

    问题: TypeError: ‘ dict’对象不可调用

    Dictionary looks up are done using square brackets: [ and ]. NOT parenthesis: ( and ).

    解决方案: 字典查找使用方括号: [和]。非括号: (和)。

  • Problem:
    ValueError: too many values to unpack

    问题: ValueError: 太多的值需要解压缩

    Make sure the number of variables you are assigning in a for loop matches the number of elements in each item of the list. Similarly for working with tuples.

    解决方案: 确保在 for 循环中分配的变量数量与列表中每个项的元素数量相匹配。与处理元组类似。

    For example, if pair is a tuple of two elements (e.g. pair =('apple', 2.0)) then the following code would cause the “too many values to unpack error”:

    例如,如果 pair 是一个由两个元素组成的元组(例如 pair = (‘ apple’ ,2.0)) ,那么下面的代码将导致“太多的值解压缩错误” :

    (a,b,c) = pair

    Here is a problematic scenario involving a for loop:

    下面是一个涉及 for 循环的有问题的场景:

    pairList = [('apples', 2.00), ('oranges', 1.50), ('pears', 1.75)]
    for fruit, price, color in pairList:
        print '%s fruit costs %f and is the color %s' % (fruit, price, color)
  • Problem:
    AttributeError: ‘list’ object has no attribute ‘length’ (or something similar)

    问题: AttributeError: ‘ list’对象没有属性‘ length’(或类似的属性)

    Finding length of lists is done using len(NAME OF LIST).

    解决方案: 使用 len (nameoflist)查找列表的长度。

  • Problem:
    Changes to a file are not taking effect.

    问题: 对文件的更改无效。



    1. Make sure you are saving all your files after any changes. 确保在更改后保存了所有文件
    2. If you are editing a file in a window different from the one you are using to execute python, make sure you 如果您正在编辑一个窗口中的文件,该窗口与您用于执行 python 的窗口不同,请确保reload(YOUR_MODULE) to guarantee your changes are being reflected. 来保证你的改变会被反映出来reload works similarly to 类似于import.

More References 更多参考资料

  • The place to go for more Python information: 获取更多 Python 信息的地方:www.python.org
  • A good reference book: 一本好的参考书:Learning Python 学习 Python (From the UCB campus, you can read the whole book online) (在加州大学伯克利分校,你可以在线阅读整本书)

Autograding 自动分级


All projects in this course will be autograded after you submit your code through the edX website. For all projects you can submit as many times as you like until the deadline. Every project’s release includes its autograder for you to run yourself. This is the recommended, and fastest, way to test your code, but keep in mind you need to submit into the edX system to get your grade registered.


To get you familiarized with the autograder, we will ask you to code, test, and submit solutions for three questions.


You can download all of the files associated the autograder tutorial as a zip archive: tutorial.zip (note this is different from the zip file used in the UNIX and Python mini-tutorials, python_basics.zip). Unzip this file and examine its contents:

您可以下载与 autograder 教程相关的所有文件,它们是 zip 归档文件: tutorial.zip (注意,这与 UNIX 和 Python 迷你教程 python_basics.zip 中使用的 zip 文件不同)。解压此文件并检查其内容:

[cs188-ta@nova ~]$ unzip tutorial.zip
[cs188-ta@nova ~]$ cd tutorial
[cs188-ta@nova ~/tutorial]$ ls

This contains a number of files you’ll edit or run:


  • addition.py: source file for question 1 : 问题1的源文件
  • buyLotsOfFruit.py: source file for question 2 : 问题2的源文件
  • shop.py: source file for question 3 : 问题3的源文件
  • shopSmart.py: source file for question 3 : 问题3的源文件
  • autograder.py: autograding script (see below) : 自动评分脚本(见下文)

and others you can ignore:


  • test_cases: directory contains the test cases for each question : 目录包含每个问题的测试用例
  • grading.py: autograder code 自动分级机代码
  • testClasses.py: autograder code 自动分级机代码
  • tutorialTestClasses.py: test classes for this particular project : 这个特定项目的测试类
  • projectParams.py: project parameters : 项目参数

The command python autograder.py grades your solution to all three problems. If we run it before editing any files we get a page or two of output:

命令 python autograder.py 为所有三个问题的解决方案打分。如果我们在编辑任何文件之前运行它,我们会得到一两页的输出:

[cs188-ta@nova ~/tutorial]$ python autograder.py 
Starting on 1-21 at 23:39:51

Question q1
*** FAIL: test_cases/q1/addition1.test
*** 	add(a,b) must return the sum of a and b
*** 	student result: "0"
*** 	correct result: "2"
*** FAIL: test_cases/q1/addition2.test
*** 	add(a,b) must return the sum of a and b
*** 	student result: "0"
*** 	correct result: "5"
*** FAIL: test_cases/q1/addition3.test
*** 	add(a,b) must return the sum of a and b
*** 	student result: "0"
*** 	correct result: "7.9"
*** Tests failed.

### Question q1: 0/1 ###

Question q2
*** FAIL: test_cases/q2/food_price1.test
*** 	buyLotsOfFruit must compute the correct cost of the order
*** 	student result: "0.0"
*** 	correct result: "12.25"
*** FAIL: test_cases/q2/food_price2.test
*** 	buyLotsOfFruit must compute the correct cost of the order
*** 	student result: "0.0"
*** 	correct result: "14.75"
*** FAIL: test_cases/q2/food_price3.test
*** 	buyLotsOfFruit must compute the correct cost of the order
*** 	student result: "0.0"
*** 	correct result: "6.4375"
*** Tests failed.

### Question q2: 0/1 ###

Question q3
Welcome to shop1 fruit shop
Welcome to shop2 fruit shop
*** FAIL: test_cases/q3/select_shop1.test
*** 	shopSmart(order, shops) must select the cheapest shop
*** 	student result: "None"
*** 	correct result: "<FruitShop: shop1>"
Welcome to shop1 fruit shop
Welcome to shop2 fruit shop
*** FAIL: test_cases/q3/select_shop2.test
*** 	shopSmart(order, shops) must select the cheapest shop
*** 	student result: "None"
*** 	correct result: "<FruitShop: shop2>"
Welcome to shop1 fruit shop
Welcome to shop2 fruit shop
Welcome to shop3 fruit shop
*** FAIL: test_cases/q3/select_shop3.test
*** 	shopSmart(order, shops) must select the cheapest shop
*** 	student result: "None"
*** 	correct result: "<FruitShop: shop3>"
*** Tests failed.

### Question q3: 0/1 ###

Finished at 23:39:51

Provisional grades
Question q1: 0/1
Question q2: 0/1
Question q3: 0/1
Total: 0/3

Your grades are NOT yet registered.  To register your grades, make sure
to follow your instructor's guidelines to receive credit on your project.

For each of the three questions, this shows the results of that question’s tests, the questions grade, and a final summary at the end. Because you haven’t yet solved the questions, all the tests fail. As you solve each question you may find some tests pass while other fail. When all tests pass for a question, you get full marks.


Looking at the results for question 1, you can see that it has failed three tests with the error message “add(a,b) must return the sum of a and b”. The answer your code gives is always 0, but the correct answer is different. We’ll fix that in the next tab.

查看问题1的结果,您可以看到它已经失败了三次测试,错误消息是“ add (a,b) must return the sum of a and b”。你的代码给出的答案总是0,但是正确的答案是不同的。我们将在下一个标签中解决这个问题。

Question 1: Addition 问题1: 增加

Open addition.py and look at the definition of add:

打开 addition.py,查看 add 的定义:

    def add(a, b):
        "Return the sum of a and b"
        "*** YOUR CODE HERE ***"
        return 0

The tests called this with a and b set to different values, but the code always returned zero. Modify this definition to read:

测试将 a 和 b 设置为不同的值来调用这个函数,但代码总是返回零。修改这个定义为:

    def add(a, b):
        "Return the sum of a and b"
        print "Passed a=%s and b=%s, returning a+b=%s" % (a,b,a+b)
        return a+b

Now rerun the autograder (omitting the results for questions 2 and 3):

现在重新运行自动分级程序(省略问题2和3的结果) :

[cs188-ta@nova ~/tutorial]$ python autograder.py -q q1
Starting on 1-21 at 23:52:05

Question q1
Passed a=1 and b=1, returning a+b=2
*** PASS: test_cases/q1/addition1.test
*** 	add(a,b) returns the sum of a and b
Passed a=2 and b=3, returning a+b=5
*** PASS: test_cases/q1/addition2.test
*** 	add(a,b) returns the sum of a and b
Passed a=10 and b=-2.1, returning a+b=7.9
*** PASS: test_cases/q1/addition3.test
*** 	add(a,b) returns the sum of a and b

### Question q1: 1/1 ###

Finished at 23:41:01

Provisional grades
Question q1: 1/1
Question q2: 0/1
Question q3: 0/1
Total: 1/3

You now pass all tests, getting full marks for question 1. Notice the new lines “Passed a=…” which appear before “*** PASS: …”. These are produced by the print statement in add. You can use print statements like that to output information useful for debugging. You can also run the autograder with the option --mute to temporarily hide such lines, as follows:

现在你通过了所有的测试,问题1得到满分。注意新的行“ Passed a = … ”出现在“ * * * PASS: … ”之前。它们由 add 中的 print 语句生成。您可以使用这样的 print 语句输出对调试有用的信息。您还可以运行带有静音选项的自动分级程序来暂时隐藏这些行,如下所示:

[cs188-ta@nova ~/tutorial]$ python autograder.py -q q1 --mute	
Starting on 1-22 at 14:15:33

Question q1
*** PASS: test_cases/q1/addition1.test
*** 	add(a,b) returns the sum of a and b
*** PASS: test_cases/q1/addition2.test
*** 	add(a,b) returns the sum of a and b
*** PASS: test_cases/q1/addition3.test
*** 	add(a,b) returns the sum of a and b

### Question q1: 1/1 ###

Question 2: buyLotsOfFruit function 问题2: buyLotsOfFruit 函数

Add a buyLotsOfFruit(orderList) function to buyLotsOfFruit.py which takes a list of (fruit,pound) tuples and returns the cost of your list. If there is some fruit in the list which doesn’t appear in fruitPrices it should print an error message and return None. Please do not change the fruitPrices variable.

添加一个 buyLotsOfFruit (orderList)函数到 buyLotsOfFruit.py 列表中,该函数接受一个(fruit,pound)元组列表,并返回列表的成本。如果列表中有一些水果没有出现在 fruitPrices 中,它应该打印一个错误消息并返回 None。请不要更改 fruitPrices 变量。

Run python autograder.py until question 2 passes all tests and you get full marks. Each test will confirm that buyLotsOfFruit(orderList) returns the correct answer given various possible inputs. For example, test_cases/q2/food_price1.test tests whether:

运行 python autograder.py,直到问题2通过所有测试并得到满分。每个测试将确认给定各种可能的输入后,buyLotsOfFruit (orderList)返回正确的答案。例如,test _ cases/q2/food _ price1.test 测试是否:

Cost of [('apples', 2.0), ('pears', 3.0), ('limes', 4.0)] is 12.25



Fill in your details below or click an icon to log in:

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 登出 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 登出 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 登出 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 登出 /  更改 )

Connecting to %s

%d 博主赞过: