Think Python

Chapter 1

The way of the program

1. The Python programming language

  • Python is an example of a high-level language .
  • There are also low-level language.
  • Computers can only run programs writter in low-level-language. So program written in a high-level language have to be processed before the can run .
  • Two kinds of programs preocess high-level language into low-level languages:interpreters and compilers.
  • Python is considered an interpreted language because Python programs are executed by an interpreter.

2. What is a program ?

  • A program is a sequence of instrucations that specifies how to preform a computation.

    base instrucations

    input 
    output
    math
    conditionan execution
    repetition
    

    algorithms.

3. What is debugging ?

Program errors are called bugs and the process of tracking the down is callede debugging.
Three kinds of errors can occur in a program:

  • Syntax errors.
  • Runtime errors.
  • Semantic errors.

4. Formal and natural languages

  • Natural languages are the language people speak.
  • Formal languages are language the are designed by people for specific applications.
    Programming languages are formal languages that have been designed to express computations.

5. The first program

In Python 3 , display the words “Hello World !”

 >>> print('Hello World!')
Hello world
>>> 

Chapter 2

Variables, expressions and statements

1. Valuse and types

if you are not sure what type a values has, the interpreter can tell you.

>>> type('Hello Hoo')
<type 'str'>
>>> type('2')
<type 'str'>
>>> type(2)
<type 'int'>
>>> type(2.222)
<type 'float'>
>>> mile = 30     
>>> type(mile)
<type 'int'>
>>> 
types: int, str, float .

2. Variables

An assignment statement creates new variables and gives the values:

>>> name = "hoo"
>>> name = 'hoo'
>>> i = 15
>>> j = 13.11
>>> 

3. Variable names and keywords

  • Variable names can be arbitrarily long.
  • They can contain both letters and numbers,but they have to begin with a letter.
  • It is a good idea to begin variable names with a lowercse letter than uppercase letter.
  • The underscore character,_,can appear in a name often used in namse with multiple words, such as my_name or type_of_value.
  • Keywords cannot be used variable names.

if you giva a variable an illegal name, you get a sytax error.

Python 2 has 31 keywords:

and del from not while
as elif global or with
assert esle if pass yield
break except import print class
exec in raise continue finally
is return def for lambda
try

In Python 3, exec is no longer a keyword, but nonlocal is.

4. Operators and operands

The operators +, _, , /, and * peform addition, subtraction, multiplication, division and exponentiation .

eg: 20+31, 4-1, 52, 6/2, 5*2

>>> 5*2
10
>>> 5**2
25

In Python 2

>>> 59/60
0
>>> 
The reason for the discrepancy is that Python is performing floor division.

In Pytion 3

>>> 59/60
0.98333333333333328
>>> 
and the new operator // performs floor division.

If either of the operands is a floating-point number, Python preforms floating-point divition, and the result is a float :

>>> 59/60
0.98333333333333328
>>> 

5. Expressions and statements

  • An expression is a combination of values, variables, and operators. eg: x + 17
  • A statement is a unit of code that the Python interpreter can execute.

6. Interactive mode and script mode

  • the scripte mode should use ‘print’ to display the value.

7. String operations

The + operator wokrs wiht strings, it performs concatenation, which means joining the strings by linking the end-to-end.

>>> first = 'bed'
>>> second ='room'
>>> first + second
'bedroom'
>>> 

The * operator also wokrs on stirngs; it performs repetition .

>>> sound = 'da'
>>> sound * 4
'dadadada'
>>> 

8.Comments

The notes added to your programs called comments, and they start with hte # symobol. These to explain in natural language what the program is doing.

Chapter 3

Functions

1. Function calls

When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name.

>>> type(32)
<type 'int'>
>>> 

2. Type conversion functions

Python provides built-in fuctions that convert values from one type to another.

>>> int('32')
32
>>> int('Hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'
>>> int('3.9999')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.9999'

>>> int(3.9999)
3
>>> int(2.3)
2

>>> float(32)
32.0
>>> float('3.999')
3.999

>>> str(32)
'32'
>>> str(3.999)
'3.999'
>>> 

3. Math functions

Python has a math module that provides most of the mathematical functions. A module is a file tha contains a collection of related functions.
Before we can use the module, we have to import it:

>>> import math

This statement creates a module boject named math. If you print the module object, you get some information about it :

>>> print math
<module 'math' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'>
>>> 

>>> radians = 0.7
>>> height = math.sin(radians)
>>> print height
0.644217687238
>>> 

4. Composition

So far, we have looke at the elements of a program—variables, expressions, and statements—in isolation, whitout talking about how tu combine them.
For example:

>>> degress = 120
>>> x = math.sin(degress / 360.0 * 2 * math.pi)
>>> print x
0.866025403784
>>> x = math.exp(math.log(x+1))
>>> print x
1.86602540378
>>> minutes = hours * 60


>>> hours = 11
>>> minutes = hours * 60
>>> hours * 60 = minutes
  File "<stdin>", line 1
SyntaxError: can't assign to operator
>>> 

5. Add new founctions

A fouction definiton specifies the name of a new function and the sequence of statements that execute when the function is called.
Here is example:

>>> def print_lyrice():
...     print "I'm a lumberjack, and I'm okay."
...     print "I sleep all night and I work all day."
... 

def is a keyword that indicates that this is a function definiton. The name of functions is print_lyrice.
The first line of the function is called the header. the rest is called the body. The header has to end with a colon and the body has to be indented.
To end the function, you have to enter an empty line(this is not necessary in a script).

>>> print print_lyrice
<function print_lyrice at 0x108f77cf8>
>>> type(print_lyrice)
<type 'function'>
>>> 

6. Definitions and uses

>>> print_lyrice()
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
>>> 

7. Flow of execution

Execution always begins at the first statement of the program. Statements are executed on at a time, in order from top to bottom.
Function definitions do not alter the flow of execution of the programe, but remember that statements inside the function are not executed until the function is called.

8. Parameters and arguments

Inside the function, the arguments are assigned to variables called parameters.

>>> def print_twice(bruce):
...     print bruce
...     print bruce
... 
>>> print_twice('Spam')
Spam
Spam
>>> 

This function assigns the argument to a parameter named bruce, When the function is called, if print the value of the parameter(whatever it is)twice.

9. Variables and parameters are local

When you create a variable inside a function, it is local, which means that it only exists inside the function.

10. Stack diagrams

To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram.

Each function is represented by a frame. A frame is a box whit the name of function bedide it and the parameters and variable of the fanction inside it.

The frames are arranged in a stack that indicates which function called whicn, and so on.

11. Fruitful functions and void functions

Some of the functions we are using, such as the math functions, yield resulets; for lack of a batter name, I call the fruitful functions. Other functions, like print_twice, preform an actions but don’t return a value. They are called void functions.

If you try to assign the result to variable, you get a special value called None.

>>> result = print_twice('Bing')
Bing
Bing
>>> print result
None

The value None is not the same as the string ‘None’. It is a special value that has its own type.

>>> print type(None)
<type 'NoneType'>

12. Why functions ?

It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:/Users/povol

  • Creating a new function gives you an opporunity to name a group of statements, which make your program easier to read and debug.

  • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you have to make it in one place.

  • Dividing a long program into functions allows you to debug the parts one at a time ande then assemble them into a working whole.
  • Well-designed functions are often useful for mamy programs. Once you write and debug one, you can reuse it.

13. Importing with form

Python provider two ways to import modules; we have already seen one:

>>> import math
>>> print math
<module 'math' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'>
>>> print math.pi
3.14159265359
>>> 

If you import math, you get a module object name math. The module object contains constants like pi and functions like sin and exp.

But if you try access pi directly, you get an error.

>>> print pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined
>>> 

As an alternative, you can import an object from a module like this:

>>> from math import pi

Now you can access pi directly, whitout dot notaion.

>>> print pi
3.14159265359    
>>> 

Or you can use the star operator to import everything from the module:

>>> from math import *
>>> cos(pi)
-1.0
>>>     

Chapter 4

Case study: interface design

1.

梦想还是要有的,万一实现了呢?