November 2015 Blog Posts

新手学python-codecademy-Class-Practice step-by-step

LC 2015-11-25 Python

Practice step by step:

Classes

Make your own Car and learn how to driveCar()!

 

 

Class basics

Classes can be very useful for storing complicated objects with their own methods and variables. Defining a class is much like defining a function, but we use the classkeyword instead. We also use the wordobject in parentheses because we want our classes to inherit the object class. This means that our class has all the properties of an object, which is the simplest, most basic class. Later we'll see that classes can inherit other, more complicated classes. An empty class would look like this:

class ClassName(object):

    # class statements go here

 

Instructions

Define a new class named "Car". For now, since we have to put something inside the class, use the pass keyword.

 

class Car(object):

    pass

 

 

Create an instance of a class

We can use classes to create new objects, which we say are instances of those classes.

Creating a new instance of a class is as easy as saying:

newObject = ClassName()

 

Instructions

Below your Car class, create a new object named my_car that is an instance of Car.

 

class Car(object):

    pass

 

my_car = Car()

 

 

 

 

Class member variables

Classes can have member variables that store information about each class object. We call them member variables since they are information that belongs to the class object.

Creating member variables and assigning them initial values is as easy as creating any other variable:

class ClassName(object):

    memberVariable = "initialValue"

 

 

Instructions

Inside your Car class, replace the passstatement with a new member variable named condition and give it an initial value of the string "new".

 

class Car(object):

    condition = "new"

 

my_car = Car()

 

 

Calling class member variables

Each class object we create has its own set of member variables. Since we've created an object my_car that is an instance of the Carclass, my_car should already have a member variable named condition. This attribute gets assigned a value as soon as my_car is created.

 

Instructions

At the end of your code, use a printstatement to display the condition ofmy_car.

 

 

class Car(object):

    condition = "new"

 

my_car = Car()

print my_car.condition

 

 

run this program:

 

new

 

 

Initializing a class

There is a special function named__init__() that gets called whenever we create a new instance of a class. It exists by default, even though we don't see it. However, we can define our own__init__() function inside the class, overwriting the default version. We might want to do this in order to provide more input variables, just like we would with any other function.

The first argument passed to __init__()must always be the keyword self - this is how the object keeps track of itself internally - but we can pass additional variables after that.

In order to assign a variable to the class (creating a member variable), we use dot notation. For instance, if we passednewVariable into our class, inside the__init__() function we would say:

self.new_variable = new_variable

 

 

Instructions

Define the __init__() function of the Carclass to take four inputs: self, model, color, and mpg. Assign the last three inputs to member variables of the same name by using the self keyword.

Then, modify the object my_car to provide the following inputs at initialization:

model = "DeLorean"

color = "silver"

mpg = 88

You don't need to include the self keyword when you create an instance of a class, because self gets added to the beginning of your list of inputs automatically by the class definition.

 

class Car(object):

    condition = "new"

    def __init__(self, model,color, mpg):

        self.model = model

        self.color = color

        self.mpg = mpg

 

my_car = Car("DeLorean", "silver", 88)

print my_car.condition

 

 

Referring to member variables

Calling class member variables works the same whether those values are created within the class (like our car's condition) or values are passed into the new object at initialization. We use dot notation to access the member variables of classes since those variables belong to the object.

For instance, if we had created a member variable named new_variable, a new instance of the class named new_objectcould access this variable by saying:

new_object.new_variable

 

 

Instructions

Now that you've created my_car print its member variables:

1.    First print the model of my_car. Click "Stuck? Get a hint!" for an example.

2.    Then print out the color of my_car.

3.    Then print out the mpg of my_car.

 

 

class Car(object):

    condition = "new"

    def __init__(self, model, color, mpg):

        self.model = model

        self.color = color

        self.mpg = mpg

 

my_car = Car("DeLorean", "silver", 88)

print my_car.condition

print my_car.model

print my_car.color

print my_car.mpg

 

 

 

run this program:

 

new
DeLorean
silver
88

 

 

 

Creating class methods

Besides member variables, classes can also have their own methods. For example:

class Square(object):

  def __init__(self, side):

    self.side = side

 

  def perimeter(self):

    return self.side * 4

The perimeter() class method is identical to defining any other function, except that it is written inside of the Square class definition.

Just like when we defined __init__(), you need to provide self as the first argument of any class method.

 

Instructions

1.    Inside the Car class, add a method named display_car() to Car that will reference the Car's member variables to return the string, "This is a [color][model] with [mpg] MPG." You can use thestr() function to turn your mpg into a string when creating the display string.

2.    Replace the individual print statements with a single print command that displays the result of calling my_car.display_car()

 

class Car(object):

    condition = "new"

    def __init__(self, model, color, mpg):

        self.model = model

        self.color = color

        self.mpg   = mpg

   

    def display_car(self):

        print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

 

my_car = Car("DeLorean", "silver", 88)

my_car.display_car()

 

 

run this program:

 

This is a silver DeLorean with 88 MPG.

 

 

 

Modifying member variables

We can modify variables that belong to a class the same way that we initialize those member variables. This can be useful when we want to change the value a variable takes on based on something that happens inside of a class method.

Instructions

1.    Inside the Car class, add a methoddrive_car() that sets self.condition to the string "used".

2.    Remove the call to my_car.display_car()and instead print only the condition of your car.

3.    Then drive your car by calling thedrive_car() method.

4.    Finally, print the condition of your car again to see how its value changes.

 

class Car(object):

    condition = "new"

    def __init__(self, model, color, mpg):

        self.model = model

        self.color = color

        self.mpg   = mpg

   

    def display_car(self):

        print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

    def drive_car(self):

        self.condition = "used"

 

my_car = Car("DeLorean", "silver", 88)

print my_car.condition

my_car.drive_car()

print my_car.condition

 

run this program:

 

new
used

 

 

Inheritance

One of the benefits of classes is that we can create more complicated classes that inherit variables or methods from their parent classes. This saves us time and helps us build more complicated objects, since thesechild classes can also include additional variables or methods.

We define a "child" class that inherits all of the variables and functions from its "parent" class like so:

class ChildClass(ParentClass):

    # new variables and functions go here

Normally we use object as the parent class because it is the most basic type of class, but by specifying a different class, we can inherit more complicated functionality.

 

Instructions

Create a class ElectricCar that inherits from Car. Give your new class an__init__() method of that includes a"battery_type" member variable in addition to the model, color and mpg.

Then, create an electric car named "my_car"with a "molten salt" battery_type. Supply values of your choice for the other three inputs (model, color and mpg).

 

class Car(object):

    condition = "new"

    def __init__(self, model, color, mpg):

        self.model = model

        self.color = color

        self.mpg   = mpg

   

    def display_car(self):

        print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

    def drive_car(self):

        self.condition = "used"

 

my_car = Car("DeLorean", "silver", 88)

print my_car.condition

my_car.drive_car()

print my_car.condition

 

class ElectricCar(Car):

    def __init__(self, model, color, mpg, battery_type):

        self.model = model

        self.color = color

        self.mpg = mpg

        self.battery_type = battery_type

my_car = ElectricCar("a", "b", 1, "molten salt")

 

 

Overriding methods

Since our ElectricCar is a more specialized type of Car, we can give the ElectricCar its own drive_car() method that has different functionality than the original Car class's.

 

Instructions

1.    Inside ElectricCar add a new methoddrive_car() that changes the car'scondition to the string "like new".

2.    Then, outside of ElectricCar, print thecondition of my_car

3.    Next, drive my_car by calling thedrive_car() function

4.    Finally, print the condition of my_caragain

 

 

class Car(object):

    condition = "new"

    def __init__(self, model, color, mpg):

        self.model = model

        self.color = color

        self.mpg   = mpg

   

    def display_car(self):

        print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

    def drive_car(self):

        self.condition = "used"

 

my_car = Car("DeLorean", "silver", 88)

print my_car.condition

my_car.drive_car()

print my_car.condition

 

class ElectricCar(Car):

    def __init__(self, model, color, mpg, battery_type):

        self.model = model

        self.color = color

        self.mpg = mpg

        self.battery_type = battery_type

    def drive_car(self):

        condition = "like new"

my_car = ElectricCar("a", "b", 1, "molten salt")

print my_car.condition

my_car.drive_car()

print my_car.condition

 

 

run this program:

new
used
new
new

 

and return:

Oops, try again. It looks like you didn't update the condition of my_car to 'like new'.

 

 

Modify as following:

 

class Car(object):

    condition = "new"

    def __init__(self, model, color, mpg):

        self.model = model

        self.color = color

        self.mpg   = mpg

   

    def display_car(self):

        print "This is a %s %s with %s MPG." % (self.color, self.model, str(self.mpg))

    def drive_car(self):

        self.condition = "used"

 

my_car = Car("DeLorean", "silver", 88)

print my_car.condition

my_car.drive_car()

print my_car.condition

 

class ElectricCar(Car):

    def __init__(self, model, color, mpg, battery_type):

        self.model = model

        self.color = color

        self.mpg = mpg

        self.battery_type = battery_type

    def drive_car(self):

        self.condition = "like new"

my_car = ElectricCar("a", "b", 1, "molten salt")

print my_car.condition

my_car.drive_car()

print my_car.condition

 

 

And run again:

 

new
used
new
like new

 

 

Building useful classes

Chances are, you won't be designing Car classes in the real world anytime soon. Usually, classes are most useful for holding and accessing abstract collections of data.

One useful class method to override is the built-in __repr__() method, which is short for representation; by providing a return value in this method, we can tell Python how to represent an object of our class (for instance, when using a print statement).

 

1.    Define a Point3D class that inherits fromobject

2.    Inside the Point3D class, define an__init__() function that accepts self, x,y, and z, and assigns these numbers to the member variables self.x, self.y,self.z

3.    Define a __repr__() method that returns "(%d, %d, %d)" % (self.x, self.y, self.z). This tells Python to represent this object in the following format: (x, y, z).

4.    Outside the class definition, create a variable named my_point containing a new instance of Point3D with x=1, y=2, and z=3.

5.    Finally, print my_point.

 

class Point3D(object):

    def __init__(self, x, y, z):

        self.x = x

        self.y = y

        self.z = z

   

    def __repr__(self):

        return "(%d, %d, %d)" % (self.x, self.y, self.z)

 

my_point = Point3D(1, 2 ,3)

print my_point

 

 

run this program:

 

(1, 2, 3)

 

 

新手学python-codecademy-Class-Learn step-by-step

LC 2015-11-24 Python

Learn step-by-step:

Why Use Classes?

Python is an object-oriented programming language, which means it manipulates programming constructs called objects. You can think of an object as a single data structure that contains data as well as functions; functions of objects are calledmethods. For example, any time you call

len("Eric")

Python is checking to see whether the string object you passed it has a length, and if it does, it returns the value associated with that attribute. When you call

my_dict.items()

Python checks to see if my_dict has anitems() method (which all dictionaries have) and executes that method if it finds it.

But what makes "Eric" a string andmy_dict a dictionary? The fact that they're instances of the str and dict classes, respectively. A class is just a way of organizing and producing objects with similar attributes and methods.

 

Instructions

Check out the code in the editor to the right. We've defined our own class, Fruit, and created a lemon instance.

When you're ready, click Save & Submit Code to get started creating classes and objects of your own.

 

 

class Fruit(object):

    """A class that makes various tasty fruits."""

    def __init__(self, name, color, flavor, poisonous):

        self.name = name

        self.color = color

        self.flavor = flavor

        self.poisonous = poisonous

 

    def description(self):

        print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)

 

    def is_edible(self):

        if not self.poisonous:

            print "Yep! I'm edible."

        else:

            print "Don't eat me! I am super poisonous."

 

lemon = Fruit("lemon", "yellow", "sour", False)

 

lemon.description()

lemon.is_edible()

 

 

run this py program:

 

I'm a yellow lemon and I taste sour.
Yep! I'm edible.

 

 

 

Class Syntax

A basic class consists only of the classkeyword, the name of the class, and the class from which the new class inherits in parentheses. (We'll get to inheritance soon.) For now, our classes will inherit from theobject class, like so:

class NewClass(object):

    # Class magic here

This gives them the powers and abilities of a Python object. By convention, user-defined Python class names start with a capital letter.

 

Instructions

Create a class called Animal in the editor. For now, in the body of your class, use thepass keyword. (pass doesn't do anything, but it's useful as a placeholder in areas of your code where Python expects an expression.)

 

class Animal(object):

    pass

 

 

 

Classier Classes

We'd like our classes to do more than... well, nothing, so we'll have to replace our pass with something else.

You may have noticed in our example back in the first exercise that we started our class definition off with an odd-looking function: __init__(). This function is required for classes, and it's used toinitialize the objects it creates.__init__() always takes at least one argument, self, that refers to the object being created. You can think of __init__() as the function that "boots up" each object the class creates.

Instructions

Remove the pass statement in your class definition, then go ahead and define an__init__() function for yourAnimal class. Pass it the argument self for now; we'll explain how this works in greater detail in the next section. Finally, put the pass into the body of the__init__() definition, since it will expect an indented block.

 

 

class Animal(object):

    def __init__(self):

        pass

 

 

 

 

Let's Not Get Too Selfish

Excellent! Let's make one more tweak to our class definition, then go ahead and instantiate(create) our first object.

So far, __init__() only takes one parameter: self. This is a Python convention; there's nothing magic about the wordself. However, it's overwhelmingly common to useself as the first parameter in__init__(), so you should do this so that other people will understand your code.

The part that is magic is the fact that self is the first parameter passed to __init__(). Python will use the first parameter that__init__() receives to refer to the object being created; this is why it's often called self, since this parameter gives the object being created its identity.

 

Instructions

Let's do two things in the editor:

1.    Pass __init__() a second parameter, name.

2.    In the body of __init__(), let the function know that namerefers to the created object's name by typing self.name =name. (This will become crystal clear in the next section.)

 

class Animal(object):

    def __init__(self, name):

        self.name = name

 

 

Instantiating Your First Object

Perfect! Now we're ready to start creating objects.

We can access attributes of our objects using dot notationHere's how it works:

class Square(object):

  def __init__(self):

    self.sides = 4

 

my_shape = Square()

print my_shape.sides

 

1.    First we create a class namedSquare with an attribute sides.

2.    Outside the class definition, we create a new instance ofSquare named my_shape and access that attribute usingmy_shape.sides.

 

Instructions

1.    Outside the Animal class definition, create a variable named zebra and set it equal toAnimal("Jeffrey").

2.    Then print out zebra's name.

Click "Stuck? Get a hint!" for an example.

 

class Animal(object):

    def __init__(self, name):

        self.name = name

 

zebra = Animal("Jeffrey")

print zebra.name

 

 

run this program:

 

Jeffrey

 

 

More on __init__() and self

Now that you're starting to understand how classes and objects work, it's worth delving a bit more into __init__() andself. They can be confusing!

As mentioned, you can think of__init__() as the method that "boots up" a class' instance object: the init bit is short for "initialize."

The first argument __init__()gets is used to refer to the instance object, and by convention, that argument is called self. If you add additional arguments—for instance, a name and age for your animal—setting each of those equal to self.name andself.age in the body of__init__() will make it so that when you create an instance object of your Animal class, you need to give each instance a name and an age, and those will be associated with the particular instance you create.

 

Instructions

Check out the examples in the editor. See how __init__()"boots up" each object to expect a name and an age, then usesself.name and self.age to assign those names and ages to each object? Add a third attribute, is_hungry to__init__(), and click Save & Submit Code to see the results.

 

 

# Class definition

class Animal(object):

    """Makes cute animals."""

    # For initializing our instance objects

    def __init__(self, name, age): #

        self.name = name

        self.age = age

 

# Note that self is only used in the __init__()

# function definition; we don't need to pass it

# to our instance objects.

 

zebra = Animal("Jeffrey", 2, True)

giraffe = Animal("Bruce", 1, False)

panda = Animal("Chad", 7, True)

 

print zebra.name, zebra.age, zebra.is_hungry

print giraffe.name, giraffe.age, giraffe.is_hungry

print panda.name, panda.age, panda.is_hungry

 

 

run this program:

 

return error:

Traceback (most recent call last):
  File "python", line 13, in <module>
TypeError: __init__() takes exactly 3 arguments (4 given)

 

Add as following(the red):

 

# Class definition

class Animal(object):

    """Makes cute animals."""

    # For initializing our instance objects

    def __init__(self, name, age, is_hungry): # add is_hungry

        self.name = name

        self.age = age

        self.is_hungry = is_hungry # add is_hungry

 

# Note that self is only used in the __init__()

# function definition; we don't need to pass it

# to our instance objects.

 

zebra = Animal("Jeffrey", 2, True)

giraffe = Animal("Bruce", 1, False)

panda = Animal("Chad", 7, True)

 

print zebra.name, zebra.age, zebra.is_hungry

print giraffe.name, giraffe.age, giraffe.is_hungry

print panda.name, panda.age, panda.is_hungry

 

 

Run again:

Jeffrey 2 True
Bruce 1 False
Chad 7 True

 

 

Class Scope

Another important aspect of Python classes is scope. The scope of a variable is the context in which it's visible to the program.

It may surprise you to learn that not all variables are accessible to all parts of a Python program at all times. When dealing with classes, you can have variables that are available everywhere (global variables), variables that are only available to members of a certain class (member variables), and variables that are only available to particular instances of a class (instance variables).

The same goes for functions: some are available everywhere, some are only available to members of a certain class, and still others are only available to particular instance objects.

 

Instructions

Check out the code in the editor. Note that each individual animal gets its own name and age (since they're all initialized individually), but they all have access to the member variable is_alive, since they're all members of theAnimal class. Click Save & Submit Code to see the output!

 

 

class Animal(object):

    """Makes cute animals."""

    is_alive = True  # member variable

    def __init__(self, name, age):

        self.name = name

        self.age = age

 

zebra = Animal("Jeffrey", 2) #instance variable

giraffe = Animal("Bruce", 1) #instance variable

panda = Animal("Chad", 7)  #instance variable

 

print zebra.name, zebra.age, zebra.is_alive

print giraffe.name, giraffe.age, giraffe.is_alive

print panda.name, panda.age, panda.is_alive

 

 

run this program:

 

Jeffrey 2 True
Bruce 1 True
Chad 7 True

 

 

A Methodical Approach

When a class has its own functions, those functions are called methods. You've already seen one such method:__init__(). But you can also define your own methods!

 

Instructions

Add a method, description, to your Animal class. Using two separate print statements, it should print out the name andage of the animal it's called on. Then, create an instance ofAnimal, hippo (with whatever name and age you like), and call its description method.

 

 

class Animal(object):

    """Makes cute animals."""

    is_alive = True

    def __init__(self, name, age):

        self.name = name

        self.age = age

    # Add your method here!

    def description(self):

        print self.name

        print self.age

 

hippo = Animal("dog", 5)

hippo.description()

 

 

run this program:

 

dog
5

 

 

 

They're Multiplying!

A class can have any number ofmember variables. These are variables that are available to all members of a class.

hippo = Animal("Jake", 12)

cat = Animal("Boots", 3)

print hippo.is_alive

hippo.is_alive = False

print hippo.is_alive

print cat.is_alive

1.    In the example above, we create two instances of anAnimal.

2.    Then we print out True, the default value stored in hippo'sis_alive member variable.

3.    Next, we set that to False and print it out to make sure.

4.    Finally, we print out True, the value stored in cat'sis_alive member variable. We only changed the variable in hippo, not in cat.

Let's add another member variable to Animal.

 

Instructions

1.    After line 3, add a second member variable called healththat contains the string "good".

2.    Then, create two newAnimals: sloth and ocelot. (Give them whatever names and ages you like.)

3.    Finally, on three separate lines, print out the health of your hippo, sloth, and ocelot.

 

 

class Animal(object):

    """Makes cute animals."""

    is_alive = True

    health = "good"

    def __init__(self, name, age):

        self.name = name

        self.age = age

    # Add your method here!

    def description(self):

        print self.name

        print self.age

 

hippo = Animal("dog", 5)

hippo.description()

sloth = Animal("cat", 2)

ocelot = Animal("cow", 1)

print hippo.health

print sloth.health

print ocelot.health

 

 

run this program:

dog
5
good
good
good

 

 

 

 

It's Not All Animals and Fruits

Classes like Animal and Fruitmake it easy to understand the concepts of classes and instances, but you probably won't see many zebras or lemons in real-world programs.

However, classes and objects are often used to model real-world objects. The code in the editor is a more realistic demonstration of the kind of classes and objects you might find in commercial software. Here we have a basicShoppingCart class for creating shopping cart objects for website customers; though basic, it's similar to what you'd see in a real program.

 

Instructions

Create an instance ofShoppingCart called my_cart. Initialize it with any values you like, then use the add_itemmethod to add an item to your cart.

 

 

class ShoppingCart(object):

    """Creates shopping cart objects

    for users of our fine website."""

    items_in_cart = {}

    def __init__(self, customer_name):

        self.customer_name = customer_name

 

    def add_item(self, product, price):

        """Add product to the cart."""

        if not product in self.items_in_cart:

            self.items_in_cart[product] = price

            print product + " added."

        else:

            print product + " is already in the cart."

 

    def remove_item(self, product):

        """Remove product from the cart."""

        if product in self.items_in_cart:

            del self.items_in_cart[product]

            print product + " removed."

        else:

            print product + " is not in the cart."

my_cart = ShoppingCart("Apple")

my_cart.add_item("Fruit", 2)

 

 

 

run this program:

 

Fruit added.

 

 

Warning: Here Be Dragons

 

Inheritance is a tricky concept, so let's go through it step by step.

Inheritance is the process by which one class takes on the attributes and methods of another, and it's used to express an is-a relationship. For example, a Panda is a bear, so a Panda class could inherit from a Bear class. However, a Toyota is not a Tractor, so it shouldn't inherit from the Tractor class (even if they have a lot of attributes and methods in common). Instead, both Toyota and Tractor could ultimately inherit from the same Vehicle class.

Instructions

Check out the code in the editor. We've defined a class, Customer, as well as a ReturningCustomer class that inherits from Customer. Note that we don't define the display_cart method in the body of ReturningCustomer, but it will still have access to that method via inheritance. Click Save & Submit Code to see for yourself!

 

 

 

class Customer(object):

    """Produces objects that represent customers."""

    def __init__(self, customer_id):

        self.customer_id = customer_id

 

    def display_cart(self):

        print "I'm a string that stands in for the contents of your shopping cart!"

 

class ReturningCustomer(Customer):

    """For customers of the repeat variety."""

    def display_order_history(self):

        print "I'm a string that stands in for your order history!"

 

monty_python = ReturningCustomer("ID: 12345")

monty_python.display_cart()

monty_python.display_order_history()

 

 

run this program:

 

I'm a string that stands in for the contents of your shopping cart!
I'm a string that stands in for your order history!

 

 

 

Inheritance Syntax

In Python, inheritance works like this:

class DerivedClass(BaseClass):

    # code goes here

where DerivedClass is the new class you're making and BaseClass is the class from which that new class inherits.

 

Instructions

On lines 1-4, we've created a class named Shape.

1.    Create your own class, Triangle, that inherits from Shape, like this:

2.  class Triangle(Shape):

3.      # code goes here

4.    Inside the Triangle class, write an__init__() function that takes four arguments: self, side1, side2, andside3.

5.    Inside the __init__() function, setself.side1 = side1, self.side2 = side2, and self.side3 = side3.

Click "Stuck? Get a hint!" for an example.

 

class Shape(object):

    """Makes shapes!"""

    def __init__(self, number_of_sides):

        self.number_of_sides = number_of_sides

 

# Add your Triangle class below!

class Triangle(Shape):

    # code goes here

    def __init__(self, side1, side2, side3):

        self.side1 = side1

        self.side2 = side2

        self.side3 = side3

 

 

Override!

Sometimes you'll want one class that inherits from another to not only take on the methods and attributes of its parent, but to override one or more of them.

class Employee(object):

    def __init__(self, name):

        self.name = name

    def greet(self, other):

        print "Hello, %s" % other.name

 

class CEO(Employee):

    def greet(self, other):

        print "Get back to work, %s!" % other.name

 

ceo = CEO("Emily")

emp = Employee("Steve")

emp.greet(ceo)

# Hello, Emily

ceo.greet(emp)

# Get back to work, Steve!

Rather than have a separate greet_underling method for our CEO, we override (or re-create) the greet method on top of the base Employee.greet method. This way, we don't need to know what type of Employee we have before we greet another Employee.

 

Instructions

1.    Create a new class, PartTimeEmployee, that inherits from Employee.

2.    Give your derived class acalculate_wage method that overridesEmployee's. It should take self and hoursas arguments.

3.    BecausePartTimeEmployee.calculate_wage overridesEmployee.calculate_wage, it still needs to setself.hours = hours.

4.    It should return the part-time employee's number of hours worked multiplied by 12.00 (that is, they get $12.00 per hour instead of $20.00).

 

 

class Employee(object):

    """Models real-life employees!"""

    def __init__(self, employee_name):

        self.employee_name = employee_name

 

    def calculate_wage(self, hours):

        self.hours = hours

        return hours * 20.00

 

# Add your code below!

class PartTimeEmployee(Employee):

    def calculate_wage(self, hours):

        self.hours = hours

        return hours * 12

 

 

 

This Looks Like a Job For...

On the flip side, sometimes you'll be working with a derived class (or subclass) and realize that you've overwritten a method or attribute defined in that class' base class (also called a parent or superclass) that you actually need. Have no fear! You can directly access the attributes or methods of a superclass with Python's built-in super call.

The syntax looks like this:

class Derived(Base):

   def m(self):

       return super(Derived, self).m()

Where m() is a method from the base class.

Instructions

First, inside your PartTimeEmployee class:

1.    Add a new method called full_time_wage with the arguments self and hours.

2.    That method should return the result of a super call to the calculate_wage method of PartTimeEmployee's parent class. Use the example above for help.

Then, after your class:

1.    Create an instance of thePartTimeEmployee class called milton. Don't forget to give it a name.

2.    Finally, print out the result of calling his full_time_wage method. You should see his wage printed out at $20.00 per hour! (That is, for 10 hours, the result should be 200.00.)

 

 

class Employee(object):

    """Models real-life employees!"""

    def __init__(self, employee_name):

        self.employee_name = employee_name

 

    def calculate_wage(self, hours):

        self.hours = hours

        return hours * 20.00

 

# Add your code below!

class PartTimeEmployee(Employee):

    def calculate_wage(self, hours):

        self.hours = hours

        return hours * 12

   

    def full_time_wage(self, hours):

        return super(PartTimeEmployee, self).calculate_wage(hours)

       

milton = PartTimeEmployee("Bob")

print milton.full_time_wage(10)

 

 

run this program:

 

200.0

 

 

 

Class Basics

First things first: let's create a class to work with.

 

Instructions

Create a class, Triangle. Its __init__()method should take self, angle1, angle2, and angle3 as arguments. Make sure to set these appropriately in the body of the__init__() method (see the Hint for more).

 

class Triangle(object):

    def __init__(self, angle1, angle2, angle3):

        self.angle1 = angle1

        self.angle2 = angle2

        self.angle3 = angle3

 

 

 

Class It Up

Great! Now let's add a member variable and a method to our class.

 

Instructions

Inside the Triangle class:

1.    Create a variable namednumber_of_sides and set it equal to 3.

2.    Create a method named check_angles. The sum of a triangle's three angles should return True if the sum of self.angle1,self.angle2, and self.angle3 is equal 180, and False otherwise.

 

 

class Triangle(object):

    def __init__(self, angle1, angle2, angle3):

        self.angle1 = angle1

        self.angle2 = angle2

        self.angle3 = angle3

    number_of_sides = 3

    def check_angles():

        if self.angle1 + self.angle2 + self.angle3 == 180:

            return True

        else:

            return False

 

 

run this program:

 

return:”Oops,try again.Make sure to pass self as an argument to your check_angles method!

 

Add self:

 

class Triangle(object):

    def __init__(self, angle1, angle2, angle3):

        self.angle1 = angle1

        self.angle2 = angle2

        self.angle3 = angle3

    number_of_sides = 3

    def check_angles(self):

        if self.angle1 + self.angle2 + self.angle3 == 180:

            return True

        else:

            return False

 

 

Instantiate an Object

Let's go ahead and create an instance of our Triangle class.

 

1.    Create a variable namedmy_triangle and set it equal to a new instance of your Triangleclass. Pass it three angles that sum to 180 (e.g. 90, 30, 60).

2.    Print outmy_triangle.number_of_sides

3.    Print outmy_triangle.check_angles()

 

 

class Triangle(object):

    def __init__(self, angle1, angle2, angle3):

        self.angle1 = angle1

        self.angle2 = angle2

        self.angle3 = angle3

    number_of_sides = 3

    def check_angles(self):

        if self.angle1 + self.angle2 + self.angle3 == 180:

            return True

        else:

            return False

 

my_triangle = Triangle(90, 30, 60)

print my_triangle.number_of_sides

print my_triangle.check_angles()

 

 

run this program:

 

3
True

 

 

 

Inheritance

Finally, let's create an Equilateral class that inherits from our Triangle class. (An equilateral triangle is a triangle whose angles are all 60˚, which also means that its three sides are equal in length.)

 

Instructions

1.    Create a class namedEquilateral that inherits fromTriangle.

2.    Inside Equilateral, create a member variable named angleand set it equal to 60.

3.    Create an __init__()function with only the parameterself, and set self.angle1,self.angle2, and self.angle3equal to self.angle (since an equilateral triangle's angles will always be 60˚).

 

class Triangle(object):

    def __init__(self, angle1, angle2, angle3):

        self.angle1 = angle1

        self.angle2 = angle2

        self.angle3 = angle3

    number_of_sides = 3

    def check_angles(self):

        if self.angle1 + self.angle2 + self.angle3 == 180:

            return True

        else:

            return False

 

my_triangle = Triangle(90, 30, 60)

print my_triangle.number_of_sides

print my_triangle.check_angles()

 

class Equilateral(Triangle):

    angle = 60

    def __init__(self):

        self.angle1 = self.angle

        self.angle2 = self.angle

        self.angle3 = self.angle

 

 

新手学python-笨方法学python-ex35-分支和函数

LC 2015-11-15 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex35-分支和函数 - 学习记录

课程内容:


你已经学会了 if 语句、函数、还有列表。现在你要练习扭转一下思维了。把下面的代码写下来,看你是否能弄懂它实现的是什么功能。

from sys import exit

def gold_room():
    print "This room is full of gold.  How much do you take?"

    next = raw_input("> ")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    else:
        dead("You greedy bastard!")


def bear_room():
    print "There is a bear here."
    print "The bear has a bunch of honey."
    print "The fat bear is in front of another door."
    print "How are you going to move the bear?"
    bear_moved = False

    while True:
        next = raw_input("> ")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif next == "taunt bear" and not bear_moved:
            print "The bear has moved from the door. You can go through it now."
            bear_moved = True
        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print "I got no idea what that means."


def cthulhu_room():
    print "Here you see the great evil Cthulhu."
    print "He, it, whatever stares at you and you go insane."
    print "Do you flee for your life or eat your head?"

    next = raw_input("> ")

    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")
    else:
        cthulhu_room()


def dead(why):
    print why, "Good job!"
    exit(0)

def start():
    print "You are in a dark room."
    print "There is a door to your right and left."
    print "Which one do you take?"

    next = raw_input("> ")

    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you starve.")


start()


你应该看到的结果?
下面是我玩游戏的过程:

$ python ex35.py
You are in a dark room.
There is a door to your right and left.
Which one do you take?
> left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?
> taunt bear
The bear has moved from the door. You can go through it now.
> open door
This room is full of gold.  How much do you take?
> asf
Man, learn to type a number. Good job!
$

加分习题:
1.把这个游戏的地图画出来,把自己的路线也画出来。
2.改正你所有的错误,包括拼写错误。
3.为你不懂的函数写注解。记得文档注解该怎么写吗?
4.为游戏添加更多元素。通过怎样的方式可以简化并且扩展游戏的功能呢?
5.这个 gold_room 游戏使用了奇怪的方式让你键入一个数字。这种方式会导致什么样的 bug? 你可以用比检查 0、1 更好的方式判断输入是否是数字吗?int() 这个函数可以给你一些头绪。

    next = raw_input("> ")
    #if "0" in next or "1" in next:
    if str.isdigit(next) == True:
        how_much = int(next)

 

 

至此,笨方法学python-ex35-分支和函数这一小节的学习结束了。

新手学python-笨方法学python-ex33-While 循环

LC 2015-11-14 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex33-While 循环 - 学习记录

课程内容:

接下来是一个更在你意料之外的概念: while-loop``(while 循环)。``while-loop 会一直执行它下面的代码片段,直到它对应的布尔表达式为 False 时才会停下来。

等等,你还能跟得上这些术语吧?如果你的某一行是以 : (冒号, colon)结尾,那就意味着接下来的内容是一个新的代码片段,新的代码片段是需要被缩进的。只有将代码用这样的方式格式化,Python 才能知道你的目的。如果你不太明白这一点,就回去看看“if 语句”和“函数”的章节,直到你明白为止。

接下来的练习将训练你的大脑去阅读这些结构化的代码。这和我们将布尔表达式烧录到你的大脑中的过程有点类似。

回到 while 循环,它所作的和 if 语句类似,也是去检查一个布尔表达式的真假,不一样的是它下面的代码片段不是只被执行一次,而是执行完后再调回到 while 所在的位置,如此重复进行,直到 while 表达式为 False 为止。

While 循环有一个问题,那就是有时它会永不结束。如果你的目的是循环到宇宙毁灭为止,那这样也挺好的,不过其他的情况下你的循环总需要有一个结束点。

为了避免这样的问题,你需要遵循下面的规定:

1.尽量少用while-loop,大部分时候for-loop是更好的选择。
2.重复检查你的while语句,确定你测试的布尔表达式最终会变成False。
3.如果不确定,就在while-loog的结尾打印出你要测试的值。看看它的变化。

在这节练习中,你将通过上面的三样事情学会while-loop:


i = 0
numbers= []

while i < 6:
    print "At the top i is %d" % i
    numbers.append(i)
    
    i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i

print "The numbers: "

for num in numbers:
    print num

 

 

运行该程序:

$python ex33.py
At the top i is 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5

$  

 

加分习题:
1.将这个 while 循环改成一个函数,将测试条件(i < 6)中的 6 换成一个变量。

ex33_1.py

def while_list(number):
    i = 0
    numbers = []
    
    while i < number:
        print "At the top i is %d" %i
        numbers.append(i)
    
        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

调用该函数试试看:

 

>>> import ex33_1
>>> ex33_1.while_list(1)
At the top i is 0
Numbers now:  [0]
At the bottom i is 1
>>> ex33_1.while_list(2)
At the top i is 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
>>> ex33_1.while_list(6)
At the top i is 0
Numbers now:  [0]
At the bottom i is 1
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 6
>>>

2.使用这个 函数重写你的脚本,并用不同的数字进行测试。

ex33_2.py


def while_list(number):
    i = 0
    numbers = []
    
    while i < number:
        print "At the top i is %d" % i
        numbers.append(i)
        
        i += 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i
    
    print "The numbers: "
    for num in numbers:
        print num

nums = int(raw_input("Pls input an int> "))
while_list(nums)

 


3.为函数添加另外一个参数,这个参数用来定义第 8 行的加值 + 1 ,这样你就可以让它任意加值了。

ex33_3.py

def while_lists(number, adds):
    i = 0
    numbers = []
    
    while i < number:
        print "At the top i is %d" % i
        numbers.append(i)
        
        i = i + adds
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i   


调用该函数试试看:

 

>>> import ex33_3
>>> ex33_3.while_lists(10, 2)
At the top i is 0
Numbers now:  [0]
At the bottom i is 2
At the top i is 2
Numbers now:  [0, 2]
At the bottom i is 4
At the top i is 4
Numbers now:  [0, 2, 4]
At the bottom i is 6
At the top i is 6
Numbers now:  [0, 2, 4, 6]
At the bottom i is 8
At the top i is 8
Numbers now:  [0, 2, 4, 6, 8]
At the bottom i is 10
>>>

4.再使用该函数重写一遍这个脚本。看看效果如何。
ex33_4.py

def while_lists(number, adds):
    i = 0
    numbers = []
    
    while i < number:
        print "At the top i is %d" % i
        numbers.append(i)
        
        i = i + adds
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i
        
    print "The numbers: "
    
    for num in numbers:
        print num

while_lists(20, 3)


运行该程序:

$python ex33_4.py
At the top i is 0
Numbers now:  [0]
At the bottom i is 3
At the top i is 3
Numbers now:  [0, 3]
At the bottom i is 6
At the top i is 6
Numbers now:  [0, 3, 6]
At the bottom i is 9
At the top i is 9
Numbers now:  [0, 3, 6, 9]
At the bottom i is 12
At the top i is 12
Numbers now:  [0, 3, 6, 9, 12]
At the bottom i is 15
At the top i is 15
Numbers now:  [0, 3, 6, 9, 12, 15]
At the bottom i is 18
At the top i is 18
Numbers now:  [0, 3, 6, 9, 12, 15, 18]
At the bottom i is 21
The numbers:
0
3
6
9
12
15
18

$

 

5.接下来使用 for-loop 和 range 把这个脚本再写一遍。你还需要中间的加值操作吗?如果你不去掉它,会有什么样的结果?

ex33_5.py

numbers = []
for i in range(6):
    print "At the top i is %d" % i
    numbers.append(i)
    
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i

print "The numbers: "

for num in numbers:
    print num

   

运行该 程序:


$python ex33_5.py
At the top i is 0
Numbers now:  [0]
At the bottom i is 0
At the top i is 1
Numbers now:  [0, 1]
At the bottom i is 1
At the top i is 2
Numbers now:  [0, 1, 2]
At the bottom i is 2
At the top i is 3
Numbers now:  [0, 1, 2, 3]
At the bottom i is 3
At the top i is 4
Numbers now:  [0, 1, 2, 3, 4]
At the bottom i is 4
At the top i is 5
Numbers now:  [0, 1, 2, 3, 4, 5]
At the bottom i is 5
The numbers:
0
1
2
3
4
5

$

 

 


6.很有可能你会碰到程序跑着停不下来了,这时你只要按着 CTRL 再敲 c (CTRL-c),这样程序就会中断下来了。


至此,-ex33-While 循环这一小节的学习结束了。

新手学python-笨方法学python-ex34-访问列表的元素

LC 2015-11-14 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex34-访问列表的元素 - 学习记录

课程内容:

列表的用处很大,但只有你能访问里边的内容时它才能发挥出作用来。你已经学会了按顺序读出列表的内容,但如果你要得到第 5 个元素该怎么办呢?你需要知道如何访问列表中的元素。访问第一个元素的方法是这样的:

animals = ['bear', 'tiger', 'penguin', 'zebra']
bear = animals[0]


你定义一个 animals 的列表,然后你用 0 来获取第一个元素?! 这是怎么回事啊?因为数学里边就是这样,所以 的列表也是从 0 开始的。虽然看上去很奇怪,这样定义其实有它的好处,而且实际上设计成 0 或者 1 开头其实都可以,

最好的解释方式是将你平时使用数字的方式和程序员使用数字的方式做对比。

假设你在观看上面列表中的四种动物(['bear', 'tiger', 'penguin', 'zebra']) 的赛跑,而它们比赛的名词正好跟列表里的次序一样。这是一场很激动人心的比赛,因为这些动物没打算吃掉对方,而且比赛还真的举办起来了。结果你的朋友来晚了,他想知道谁赢了比赛,他会问你“嘿,谁是第 0 名”吗?不会的,他会问“嘿,谁是第 1 名?”

这是因为动物的次序是很重要的。没有第一个就没有第二个,没有第二个也没有第三个。第零个是不存在的,因为零的意思是什么都没有。“什么都没有”怎么赢比赛嘛,完全不合逻辑。这样的数字我们称之为“序数(ordinal number)”,因为它们表示的是事物的顺序。

而程序员不能用这种方式思考问题,因为他们可以从列表的任何一个位置取出一个元素来。对程序员来说,上述的列表更像是一叠卡片。如果他们想要 tiger,就抓它出来,如果想要zebra,也一样抓取出来。要随机地抓取列表里的内容,列表的每一个元素都应该有一个地址,或者一个 “index(索引)”,而最好的方式是使用以 0 开头的索引。相信我说的这一点吧,这种方式获取元素会更容易。这类的数字被称为“基数(cardinal number)”,它意味着你可以任意抓取元素,所以我们需要一个 0 号元素。

那么,这些知识对于你的列表操作有什么帮助呢?很简单,每次你对自己说“我要第 3 只动物”时,你需要将“序数”转换成“基数”,只要将前者减 1 就可以了。第 3 只动物的索引是 2,也就是 penguin。由于你一辈子都在跟序数打交道,所以你需要用这种方式来获得基数,只要减 1 就都搞定了。

记住: ordinal == 有序,以 1 开始;cardinal == 随机选取, 以 0 开始。

让我们练习一下。定义一个动物列表,然后跟着做后面的练习,你需要写出所指位置的动物名称。如果我用的是“1st, 2nd”等说法,那说明我用的是序数,所以你需要减去 1。如果我给你的是基数(0, 1, 2),你只要直接使用即可。 .. code-block:: python

animals = [‘bear’, ‘python’, ‘peacock’, ‘kangaroo’, ‘whale’, ‘platypus’]
1.The animal at 1.
2.The 3rd animal.
3.The 1st animal.
4.The animal at 3.
5.The 5th animal.
6.The animal at 2.
7.The 6th animal.
8.The animal at 4.
对于上述每一条,以这样的格式写出一个完整的句子:“The 1st animal is at 0 and is a bear.” 然后倒过来念:“The animal at 0 is the 1st animal and is a bear.”

animals = [‘bear’, ‘python’, ‘peacock’, ‘kangaroo’, ‘whale’, ‘platypus’]
1.The animal at 1.
-->The 2nd animal is at 1 and is a python.
-->The animal at 1 is the 2nd animal and is a python.
2.The 3rd animal.
-->The 3rd animal is at 2 and is a peacock.
-->The animal at 2 is the 3rd animal and is a peacock.
3.The 1st animal.
-->The 1st animal is at 0 and is a bear.
-->The animal at 0 is the 1st animal and is a bear.
4.The animal at 3.
-->The animal at 3 is the 4th animal and is kangaroo.
-->The 4th animal is at 3 and is a kangarro.
5.The 5th animal.
-->The 5th animal is at 4 and is a whale.
-->The animal at 4 is the 5th animal and is a whale.
6.The animal at 2.
-->The animal at 2 is the 3rd animal and is a peacock.
-->The 3rd animal is at 2 and is a peacock.
7.The 6th animal.
-->The 6th animal is at 5 and is a platypus.
-->The animal at 5 is the 6th animal and is a platypus.
8.The animal at 4.
-->The animal at 4 is the 5th animal and is a whale.
-->The 5th animal is at 4 and is a whale.

使用 python 检查你的答案。

加分习题:
1.上网搜索一下关于序数(ordinal number)和基数(cardinal number)的知识并阅读一下。
2.以你对于这些不同的数字类型的了解,解释一下为什么 “January 1, 2010” 里是 2010 而不是 2009?(提示:你不能随机挑选年份。)
3.再写一些列表,用一样的方式作出索引,确认自己可以在两种数字之间互相翻译。
4.使用 python 检查自己的答案。

1.The animal at 1. -->animals[1]
2.The 3rd animal. -->animals[2]
3.The 1st animal. -->animals[0]
4.The animal at 3. -->animals[3]
5.The 5th animal. -->animals[4]
6.The animal at 2. -->animals[2]
7.The 6th animal. -->animals[5]
8.The animal at 4. -->animals[4]

ex34.py


animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print "The animal at 1 is the 2nd animal and is a python. ", animals[1]
print "The 3rd animal is at 2 and is a peacock. ", animals[2]
print "The 1st animal is at 0 and is a bear.", animals[0]
print "The animal at 3 is the 4th animal and is kangaroo.", animals[3]
print "The 5th animal is at 4 and is a whale.", animals[4]
print "The animal at 2 is the 3rd animal and is a peacock.", animals[2]
print "The 6th animal is at 5 and is a platypus.", animals[5]
print "The animal at 4 is the 5th animal and is a whale.", animals[4]


运行该程序:

$python ex34.py
The animal at 1 is the 2nd animal and is a python.  python
The 3rd animal is at 2 and is a peacock.  peacock
The 1st animal is at 0 and is a bear. bear
The animal at 3 is the 4th animal and is kangaroo. kangaroo
The 5th animal is at 4 and is a whale. whale
The animal at 2 is the 3rd animal and is a peacock. peacock
The 6th animal is at 5 and is a platypus. platypus
The animal at 4 is the 5th animal and is a whale. whale

$


至此,-ex34-访问列表的元素这一小节的学习结束了。

新手学python-笨方法学python-ex32-循环和列表

LC 2015-11-13 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python--ex32-循环和列表 - 学习记录

课程内容:

现在你应该有能力写更有趣的程序处理了。如果你能一直跟得上,你应该已经看出将“if”和“布尔表达式”结合起来可以让程序作出一些智能化的事情。

然而,我们的程序还需要能很快地完成重复的事情,这节习题中我们将使用for-loop(for循环)来创建和打印出各种各样的列表。在做的过程中,你会逐渐明白它们是怎么回事。现在我不会告诉你,你需要自己找到答案。

在你开始使用for循环之前,你需要再某个位置存放循环的结果。最好的方法是使用列表(list),顾名思义,它就是一个按顺序存放东西的容器。列表并不复杂,你只是要学习一点新的语法。首先我们看看如何创建列表:

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]

你要做的是以[(左方括号)开头“打开”列表,然后写下你要放入列表的东西,以逗号给开,就跟函数的参数一样,最后你要用](右方括号)结束列表的定义。
然后Python接收这个列表以及里边所有的内容,将其赋给一个变量。


Warning
对于不会编程的人来说这是一个难点。习惯性思维告诉你的大脑大地是平的。记得上一个练习中的 if 语句嵌套吧,你可能觉得要理解它有些难度,因为生活中一般人不会去像这样的问题,但这样的问题在编程中几乎到处都是。你会看到一个函数调用另外一个包含 if 语句的函数,其中又有嵌套列表的列表。如果你看到这样的东西一时无法弄懂,就用纸笔记下来,手动分割下去,直到弄懂为止。


现在我们将使用循环创建一些列表,然后将它们打印出来。


the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] 

# this first kind of for-loop goes through a list
for number in the_count:
    print "This is count %d" % number

# same as above
for fruit in fruits:
    print "A fruit of type: %s" % fruit
    
# also we can go through mixd lists too
# notice we have to use %r sine we don't know what's in it
for i in change:
    print "I got %r" % i
    
# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print "Adding %d to the list." % i
    # append is a function that lists understand
    elements.append(i)

# now we can print them out too
for i in elements:
    print "Element was: %d" % i 

 


运行该程序:

$python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'dimes'
I got 3
I got 'quarters'
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

$

 


加分习题:
1.注意一下 range 的用法。查一下 range 函数并理解它。

Help on built-in function range in module __builtin__:

range(...)
    range([start,] stop[, step]) -> list of integers

    Return a list containing an arithmetic progression of integers.
    range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
    When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
    These are exactly the valid indices for a list of 4 elements.

 

   
2.在第 22 行,你可以可以直接将 elements 赋值为 range(0,6),而无需使用 for 循环?

elements = range(0, 6)
for i in elements:
    print "Element was: %d" % i

   
运行该程序:

$python ex32-2.py
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

$

 

3.在 Python 文档中找到关于列表的内容,仔细阅读以下,除了 append 以外列表还支持哪些操作?

|  append(...)
|      L.append(object) -- append object to end
|
|  count(...)
|      L.count(value) -> integer -- return number of occurrences of value
|
|  extend(...)
|      L.extend(iterable) -- extend list by appending elements from the iterable
|
|  index(...)
|      L.index(value, [start, [stop]]) -> integer -- return first index of value.
|      Raises ValueError if the value is not present.
|
|  insert(...)
|      L.insert(index, object) -- insert object before index
|
|  pop(...)
|      L.pop([index]) -> item -- remove and return item at index (default last).
|      Raises IndexError if list is empty or index is out of range.
|
|  remove(...)
|      L.remove(value) -- remove first occurrence of value.
|      Raises ValueError if the value is not present.
|
|  reverse(...)
|      L.reverse() -- reverse *IN PLACE*
|
|  sort(...)
|      L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
|      cmp(x, y) -> -1, 0, 1

 

 

写个乘法口诀表试试看:

for i in range(1, 10):
    for j in range(1, 10):
        print " %d * %d = %d " %(i, j, i*j) 

     

 

至此,笨方法学python-ex32-循环和列表这一小节的学习结束了。

新手学python-笨方法学python-ex29-如果(if)

LC 2015-11-12 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex29-如果(if) - 学习记录

课程内容:

下面是你要写的作业,这段向你介绍了“if语句”。把这段输入进去,让它能正确执行。然后我们看看你是否有所收获。


people = 20
cats = 30
dogs = 15


if people < cats:
    print "Too many cats! The world is doomed!"
    
if people > cats:
    print "No many cats! The world is saved!"

if people < dogs:
    print "The world is drooled on!"

if people > dogs:
    print "The world is dry!"


dogs += 5

if people >= dogs:
    print "People are greater than or equal to dogs."
    
if people <= dogs:
    print "People are less than or equal to dogs."

if people == dogs:
    print "People are dogs."


    
   
运行该程序:

$python ex29.py
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

$

    
   
加分习题:
猜猜“if语句”是什么,它有什么用处。在做下一道习题前,试着用自己的话回答下面的问题:

你认为 if 对于它下一行的代码做了什么?
为什么 if 语句的下一行需要 4 个空格的缩进?
如果不缩进,会发生什么事情?
把习题 27 中的其它布尔表达式放到``if语句``中会不会也可以运行呢?试一下。
如果把变量 people, cats, 和 dogs 的初始值改掉,会发生什么事情?

 


至此,笨方法学python-ex29-如果(if)这一小节的学习结束了。

新手学python-笨方法学python-ex30-Else 和 If

LC 2015-11-12 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex30-Else 和 If - 学习记录

课程内容:


前一习题中你写了一些 “if 语句(if-statements)”,并且试图猜出它们是什么,以及实现的是什么功能。在你继续学习之前,我给你解释一下上一节的加分习题的答案。上一节的加分习题你做过了吧,有没有?

1.你认为 if 对于它下一行的代码做了什么? If 语句为代码创建了一个所谓的“分支”,就跟 RPG 游戏中的情节分支一样。if 语句告诉你的脚本:“如果这个布尔表达式为真,就运行接下来的代码,否则就跳过这一段。”
2.为什么 if 语句的下一行需要 4 个空格的缩进? 行尾的冒号的作用是告诉 Python 接下来你要创建一个新的代码区段。这根你创建函数时的冒号是一个道理。
3.如果不缩进, 会发生什么事情? 如果你没有缩进,你应该会看到 Python 报错。Python 的规则里,只要一行以“冒号(colon)” : 结尾,它接下来的内容就应该有缩进。
4.把习题 27 中的其它布尔表达式放到 if语句 中会不会也可以运行呢?试一下。 可以。而且不管多复杂都可以,虽然写复杂的东西通常是一种不好的编程风格。
5.如果把变量 people, cats, 和 dogs 的初始值改掉, 会发生什么事情? 因为你比较的对象是数字,如果你把这些数字改掉的话,某些位置的 if 语句会被演绎为 True,而它下面的代码区段将被运行。你可以试着修改这些数字,然后在头脑里假想一下那一段代码会被运行。
把我的答案和你的答案比较一下,确认自己真正懂得代码“区段”的含义。这点对于你下一节的练习很重要,因为你将会写很多的 if 语句。

把这一段写下来,并让它运行起来:

people = 30
cars = 40
buses = 15


if cars > people:
    print "We should take the cars."
elif cars < people:
    print "We should not take the cars."
else:
    print "We can't decide."
    
if buses > cars:
    print "That's too many buses."
elif buses < cars:
    print "Maybe we could take the buses."
else:
    print "We still can't decide."
    
if people > buses:
    print "Alright, let's just take the buses."
else:
    print "Fine, let's stay home then."

 

运行:
 

$python ex30.py
We should take the cars.
Maybe we could take the buses.
Alright, let's just take the buses.

$


加分习题:
猜想一下 elif 和 else 的功能。
将 cars, people, 和 buses 的数量改掉,然后追溯每一个 if 语句。看看最后会打印出什么来。
试着写一些复杂的布尔表达式,例如 cars > people and buses < cars。
在每一行的上面写注解,说明这一行的功用。

 


至此,笨方法学python-ex30-Else 和 If这一小节的学习结束了。

新手学python-笨方法学python-ex31-作出决定

LC 2015-11-12 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python--ex31-作出决定 - 学习记录

课程内容:


这本书的上半部分你打印了一些东西,而且调用了函数,不过一切都是直线式进行的。你的脚本从最上面一行开始,一路运行到结束,但其中并没有决定程序流向的分支点。现在你已经学了 if, else, 和 elif ,你就可以开始创建包含条件判断的脚本了。

上一个脚本中你写了一系列的简单提问测试。这节的脚本中,你将需要向用户提问,依据用户的答案来做出决定。把这个脚本写下来,多多鼓捣一阵子,看看它的工作原理是什么。

 

print "You enter a dark room with two doors. Do you go through door #1 or door #2?"

door = raw_input("> ")

if door == "1":
    print "There's a giant bear here eating a cheese cake.  What do you do?"
    print "1. Take the cake."
    print "2. Scream at the bear."
    
    bear = raw_input("> ")
    
    if bear == "1":
        print "The bear eats your face off. Good job!"
    elif bear == "2":
        print "The bear eats your legs off. Good job!"
    else:
        print "Well, doing %s is probablybetter. Bear runs away." %bear

elif door == "2":
    print "You stare into the endless abyss at Cthulhu's retina."
    print "1. Bluberries."
    print "2. Yellow jacket clothespins."
    print "3. Understanding revolvers yelling melodies."
    
    insanity = raw_input("> ")
    
    if insanity == "1" or insanity == "2":
        print "Your body survives powered by a mind of jello. Good job!"
    else:
        print "The insanity rots your eyes into a pool of muck. Good job!"

else:
    print "You stumble around and fall on a knife and die. Good job!"

 


这里的重点是你可以在“if 语句”内部再放一个“if 语句”。这是一个很强大的功能,可以用来创建嵌套(nested)的决定,其中的一个分支将引向另一个分支的子分支。

你需要理解 if 语句 包含 if 语句 的概念。做一下加分习题,这样你会确信自己真正理解了它们。

 


玩这个小游戏:

$python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake.  What do you do?
1. Take the cake.
2. Scream at the bear.
> 2
The bear eats your legs off. Good job!

$python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake.  What do you do?
1. Take the cake.
2. Scream at the bear.
> 1
The bear eats your face off. Good job!

$python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu's retina.
1. Bluberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 1
Your body survives powered by a mind of jello. Good job!

$python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu's retina.
1. Bluberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 2
Your body survives powered by a mind of jello. Good job!

$python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu's retina.
1. Bluberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 3
The insanity rots your eyes into a pool of muck. Good job!

$python ex31.py
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There's a giant bear here eating a cheese cake.  What do you do?
1. Take the cake.
2. Scream at the bear.
> apples
Well, doing apples is probablybetter. Bear runs away.

$

 

加分习题:
为游戏添加新的部分,改变玩家做决定的位置。尽自己的能力扩展这个游戏,不过别把游戏弄得太怪异了。

至此,笨方法学python-ex31-作出决定这一小节的学习结束了。

新手学python-笨方法学python-ex27-记住逻辑关系

LC 2015-11-11 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex27-记住逻辑关系 - 学习记录

课程内容:


到此为止你已经学会了读写文件,命令行处理,以及很多 Python 数学运算功能。今天,你将要开始学习逻辑了。你要学习的不是研究院里的高深逻辑理论,只是程序员每天都用到的让程序跑起来的基础逻辑知识。

学习逻辑之前你需要先记住一些东西。这个练习我要求你一个星期完成,不要擅自修改日程,就算你烦得不得了,也要坚持下去。这个练习会让你背下来一系列的逻辑表格,这会让你更容易地完成后面的习题。

需要事先警告你的是:这件事情一开始一点乐趣都没有,你会一开始就觉得它很无聊乏味,但它的目的是教你程序员必须的一个重要技能——一些重要的概念是必须记住的,一旦你明白了这些概念,你会获得相当的成就感,但是一开始你会觉得它们很难掌握,就跟和乌贼摔跤一样,而等到某一天,你会刷的一下豁然开朗。你会从这些基础的记忆学习中得到丰厚的回报。

这里告诉你一个记住某样东西,而不让自己抓狂的方法:在一整天里,每次记忆一小部分,把你最需要加强的部分标记起来。不要想着在两小时内连续不停地背诵,这不会有什么好的结果。不管你花多长时间,你的大脑也只会留住你在前 15 或者 30 分钟内看过的东西。

取而代之,你需要做的是创建一些索引卡片,卡片有两列内容,正面写下逻辑关系,反面写下答案。你需要做到的结果是:拿出一张卡片来,看到正面的表达式,例如 “True or False”,你可以立即说出背面的结果是 “True”!坚持练习,直到你能做到这一点为止。

一旦你能做到这一点了,接下来你需要每天晚上自己在笔记本上写一份真值表出来。不要只是抄写它们,试着默写真值表,如果发现哪里没记住的话,就飞快地撇一眼这里的答案。这样将训练你的大脑让它记住整个真值表。

不要在这上面花超过一周的时间,因为你在后面的应用过程中还会继续学习它们。

逻辑术语?
在 python 中我们会用到下面的术语(字符或者词汇)来定义事物的真(True)或者假(False)。计算机的逻辑就是在程序的某个位置检查这些字符或者变量组合在一起表达的结果是真是假。

and 与
or 或
not 非
!= (not equal) 不等于
== (equal) 等于
>= (greater-than-equal) 大于等于
<= (less-than-equal) 小于等于
True 真
False 假
其实你已经见过这些字符了,但这些词汇你可能还没见过。这些词汇(and, or, not)和你期望的效果其实是一样的,跟英语里的意思一模一样。

真值表?
我们将使用这些字符来创建你需要记住的真值表。

NOT True?
not False True
not True False

OR True?
True or False True
True or True True
False or True True
False or False False

AND True?
True and False False
True and True True
False and True False
False and False False

NOT OR True?
not (True or False) False
not (True or True) False
not (False or True) False
not (False or False) True

NOT AND True?
not (True and False) True
not (True and True) False
not (False and True) True
not (False and False) True

!= True?
1 != 0 True
1 != 1 False
0 != 1 True
0 != 0 False

== True?
1 == 0 False
1 == 1 True
0 == 1 False
0 == 0 True
现在使用这些表格创建你自己的卡片,再花一个星期慢慢记住它们。记住一点,这本书不会要求你成功或者失败,只要每天尽力去学,在尽力的基础上多花一点功夫就可以了。

 


至此,笨方法学python-ex27-记住逻辑关系,这一小节的学习结束了。

新手学python-笨方法学python-ex28-布尔表达式练习

LC 2015-11-11 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex28-布尔表达式练习 - 学习记录

课程内容:


上一节你学到的逻辑组合的正式名称是“布尔逻辑表达式(boolean logic expression)”。在编程中,布尔逻辑可以说是无处不在。它们是计算机运算的基础和重要组成部分,掌握它们就跟学音乐掌握音阶一样重要。

在这节练习中,你将在 python 里使用到上节学到的逻辑表达式。先为下面的每一个逻辑问题写出你认为的答案,每一题的答案要么为 True 要么为 False。写完以后,你需要将python 运行起来,把这些逻辑语句输入进去,确认你写的答案是否正确。

True and True  -->True
False and True  -->False
1 == 1 and 2 == 1  -->False
"test" == "test"  --True
1 == 1 or 2 != 1  -->True
True and 1 == 1  -->True
False and 0 != 0 -->False
True or 1 == 1  -->True
"test" == "testing"  -->False
1 != 0 and 2 == 1  -->False
"test" != "testing"  -->True
"test" == 1  -->False
not (True and False) -->True
not (1 == 1 and 0 != 1)  -->False
not (10 == 1 or 1000 == 1000) -->False
not (1 != 10 or 3 == 4) -->False
not ("testing" == "testing" and "Zed" == "Cool Guy")  -->True
1 == 1 and not ("testing" == 1 or 1 == 0)  -->True
"chunky" == "bacon" and not (3 == 4 or 3 == 3) -->False
3 == 3 and not ("testing" == "testing" or "Python" == "Fun") -->False


在本节结尾的地方我会给你一个理清复杂逻辑的技巧。


所有的布尔逻辑表达式都可以用下面的简单流程得到结果:

找到相等判断的部分 (== or !=),将其改写为其最终值 (True 或 False)。
找到括号里的 and/or,先算出它们的值。
找到每一个 not,算出他们反过来的值。
找到剩下的 and/or,解出它们的值。
等你都做完后,剩下的结果应该就是 True 或者 False 了。
下面我们以 #20 逻辑表达式演示一下:

3 != 4 and not ("testing" != "test" or "Python" == "Python")
接下来你将看到这个复杂表达式是如何逐级解为一个单独结果的:

解出每一个等值判断:
3 != 4 为 True: True and not ("testing" != "test" or "Python" == "Python")
"testing" != "test" 为 True: True and not (True or "Python" == "Python")
"Python" == "Python": True and not (True or True)
找到括号中的每一个 and/or :
(True or True) 为 True: True and not (True)
找到每一个 not 并将其逆转:
not (True) 为 False: True and False
找到剩下的 and/or,解出它们的值:
True and False 为 False
这样我们就解出了它最终的值为 False.


运行一遍看是不是跟自己解出的结果相同:

>>> True and True
True
>>> False and True
False
>>> 1 == 1 and 2 == 1
False
>>> "test" == "test"
True
>>> 1 == 1 or 2 != 1
True
>>> True and 1 == 1
True
>>> False and 0 != 0
False
>>> True or 1 == 1
True
>>> "test" == "testing"
False
>>> 1 != 0 and 2 == 1
False
>>> "test" != "testing"
True
>>> "test" == 1
False
>>> not (True and False)
True
>>> not (1 == 1 and 0 != 1)
False
>>> not (10 == 1 or 1000 == 1000)
False
>>> not (1 != 10 or 3 == 4)
False
>>> not ("testing" == "testing" and "Zed" == "Cool Guy")
True
>>> 1 == 1 and not ("testing" == 1 or 1 == 0)
True
>>> "chunky" == "bacon" and not (3 == 4 or 3 == 3)
False
>>> 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")
False
>>>

 


至此,笨方法学python-python-ex28-布尔表达式练习这一小节的学习结束了。

新手学python-笨方法学python-ex26-恭喜你,现在可以考试了!

LC 2015-11-10 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python--ex26-恭喜你,现在可以考试了! - 学习记录

课程内容:


你已经差不多完成这本书的前半部分了,不过后半部分才是更有趣的。你将学到逻辑,并通过条件判断实现有用的功能。

在你继续学习之前,你有一道试题要做。这道试题很难,因为它需要你修正别人写的代码。当你成为程序员以后,你将需要经常面对别的程序员的代码,也许还有他们的傲慢态度,他们会经常说自己的代码是完美的。

这样的程序员是自以为是不在乎别人的蠢货。优秀的科学家会对他们自己的工作持怀疑态度,同样,优秀的程序员也会认为自己的代码总有出错的可能,他们会先假设是自己的代码有问题,然后用排除法清查所有可能是自己有问题的地方,最后才会得出“这是别人的错误”这样的结论。

在这节练习中,你将面对一个水平糟糕的程序员,并改好他的代码。我将习题 24 和 25 胡乱拷贝到了一个文件中,随机地删掉了一些字符,然后添加了一些错误进去。大部分的错误是Python 在执行时会告诉你的,还有一些算术错误是你要自己找出来的。再剩下来的就是格式和拼写错误了。

所有这些错误都是程序员很容易犯的,就算有经验的程序员也不例外。

你的任务是将此文件修改正确,用你所有的技能改进这个脚本。你可以先分析这个文件,或者你还可以把它像学期论文一样打印出来,修正里边的每一个缺陷,重复修正和运行的动作,直到这个脚本可以完美地运行起来。在整个过程中不要寻求帮助,如果你卡在某个地方无法进行下去,那就休息一会晚点再做。

就算你需要几天才能完成,也不要放弃,直到完全改对为止。

最后要说的是,这个练习的目的不是写程序,而是修正现有的程序,你需要访问下面的网站:

http://learnpythonthehardway.org/book/exercise26.txt


从那里把代码复制粘贴过来,命名为 ex26.py,这也是本书唯一一处允许你复制粘贴的地方。

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words)
    """Prints the first word after popping it off."""
    word = words.poop(0)
    print word

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1
    print word

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print "--------------"
print poem
print "--------------"

five = 10 - 2 + 3 - 5
print "This should be five: %s" % five

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans \ 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
beans, jars, crates == secret_formula(start-point)

print "With a starting point of: %d" % start_point
print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates)

start_point = start_point / 10

print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_pont


sentence = "All god\tthings come to those who weight."

words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)

print_first_word(words)
print_last_word(words)
.print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
prin sorted_words

print_irst_and_last(sentence)

   print_first_a_last_sorted(senence)

  

第一版ex26-1.py,看代码修改,修改并解释:

 

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words)
    """Prints the first word after popping it off."""
    word = words.poop(0)
    print word

def print_last_word(words):
    """Prints the last word after popping it off."""
    #word = words.pop(-1 # here lost a ")"
    word = words.pop(-1)
    print word

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print "--------------"
print poem
print "--------------"

five = 10 - 2 + 3 - 5
# print "This should be five: %s" % five # change %s to %d
print " This should be five: %d" % five

def secret_formula(started):
    jelly_beans = started * 500
    # jars = jelly_beans \ 1000 #change the back-slash to slash
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
# beans, jars, crates == secret_formula(start-point) # change "==" to "="
beans, jars, crates = secret_formula(start-point)

print "With a starting point of: %d" % start_point
print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates)

start_point = start_point / 10

print "We can also do that this way:"
# print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_pont # here lost a ")"
print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point)


sentence = "All god\tthings come to those who weight."

#words = ex25.break_words(sentence) # in a same file, delelte "ex25."
words = break_words(sentence)
#sorted_words = ex25.sort_words(words)# in a same file, delelte "ex25."
sorted_words = sort_words(words)

print_first_word(words)
print_last_word(words)
# .print_first_word(sorted_words) # delete the "."
print_first_word(sorted_words)
print_last_word(sorted_words)
#sorted_words = ex25.sort_sentence(sentence)# in a same file, delelte "ex25."
sorted_words = sort_sentence(sentence)
# prin sorted_words # prin is incorrect
print sorted_words

#print_irst_and_last(sentence) #irst is incorrect,print_irst_and_last is not defined
print_first_and_last(sentence)

#   print_first_a_last_sorted(senence)#1st,the/tab is incorrect;2nd,a is incorrect,print_first_a_last_sorted is not defined;3rd,senence is not defined
print_first_and_last_sorted(sentence)


运行该python程序,出错:

$python ex26-1.py
  File "ex26-1.py", line 10
    def print_first_word(words)
                              ^
SyntaxError: invalid syntax

$


创建函数的规则没有记清楚,第六条,紧跟着参数的是不是括号和冒号? 这里少了冒号,第二版修改,加上冒号。

def print_first_word(words):

运行:

$python ex26-2.py
Let's practice everything.
You'd need to know 'bout escapes with \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explantion

                where there is none.

--------------
 This should be five: 6
Traceback (most recent call last):
  File "ex26-1.py", line 71, in <module>
    beans, jars, crates = secret_formula(start-point)
NameError: name 'start' is not defined

$


修改71行:
beans, jars, crates = secret_formula(start-point) 原来脚本里的start-point没有定义
我们可以看第69行,定义的是start_point;第三版,这里将start-point改为start_point

运行:

 

$python ex26-3.py
Let's practice everything.
You'd need to know 'bout escapes with \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explantion

                where there is none.

--------------
 This should be five: 6
With a starting point of: 10000
We'd have 5000000 jeans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crabapples.
Traceback (most recent call last):
  File "ex26-3.py", line 91, in <module>
    print_first_word(words)
  File "ex26-3.py", line 13, in print_first_word
    word = words.poop(0)
AttributeError: 'list' object has no attribute 'poop'

$

提示list对象没有poop属性

拼写错误,第四版,将poop改为pop
word = words.pop(0)

运行该程序,成功了:

$python ex26-4.py
Let's practice everything.
You'd need to know 'bout escapes with \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explantion

                where there is none.

--------------
 This should be five: 6
With a starting point of: 10000
We'd have 5000000 jeans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crabapples.
All
weight.
All
who
['All', 'come', 'god\tthings', 'those', 'to', 'weight.', 'who']
All
weight.
All
who

$

 


但是我们看结果里面有一些单词拼写或者其他小错误,比如:
“This should be five: 6” 这句话内容相悖啊
jeans这个单词应该是beans啊
god\tthings应该是good things啊
这些就先不管了。

将改完后的程序ex26-4.py贴上来:

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

# def print_first_word(words) # here lost a ":" == ver02
def print_first_word(words):
    """Prints the first word after popping it off."""
#    word = words.poop(0) # 'list' object has no attribute 'poop',change to "pop" == ver04 
    word = words.pop(0)
    print word

def print_last_word(words):
    """Prints the last word after popping it off."""
    #word = words.pop(-1 # here lost a ")" == ver01
    word = words.pop(-1)
    print word

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print "--------------"
print poem
print "--------------"

five = 10 - 2 + 3 - 5
# print "This should be five: %s" % five # change %s to %d == ver01
print " This should be five: %d" % five

def secret_formula(started):
    jelly_beans = started * 500
    # jars = jelly_beans \ 1000 # change the back-slash to slash == ver01
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
# beans, jars, crates == secret_formula(start-point) # change "==" to "=" == ver01
# beans, jars, crates = secret_formula(start-point)# change to "start_point" == ver03
beans, jars, crates = secret_formula(start_point)

print "With a starting point of: %d" % start_point
print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates)

start_point = start_point / 10

print "We can also do that this way:"
# print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_pont 
# here lost a ")" == ver01
print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point)


sentence = "All god\tthings come to those who weight."

# words = ex25.break_words(sentence) # in a same file, delelte "ex25." == ver01
words = break_words(sentence)
# sorted_words = ex25.sort_words(words)# in a same file, delelte "ex25." == ver01
sorted_words = sort_words(words)

print_first_word(words)
print_last_word(words)
# .print_first_word(sorted_words) # delete the "." == ver01
print_first_word(sorted_words)
print_last_word(sorted_words)
#sorted_words = ex25.sort_sentence(sentence)# in a same file, delelte "ex25." == ver01
sorted_words = sort_sentence(sentence)
# prin sorted_words # prin is incorrect == ver01
print sorted_words

#print_irst_and_last(sentence) #irst is incorrect,print_irst_and_last is not defined == ver01
print_first_and_last(sentence)

#   print_first_a_last_sorted(senence)
#1st,the/tab is incorrect;
#2nd,a is incorrect,print_first_a_last_sorted is not defined;
#3rd,senence is not defined == ver01
print_first_and_last_sorted(sentence)

 

 

 

至此,笨方法学python-ex26-恭喜你,现在可以考试了!这一小节的学习结束了。

新手学python-笨方法学python-ex25-更多更多的练习

LC 2015-11-09 Python

跟着个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex25-更多更多的练习 - 学习记录

课程内容:

我们将做一些关于函数和变量的练习,以确认你真正掌握了这些知识。这节练习对你来说可以说是一本道:写程序,逐行研究,弄懂它。

不过这节练习还是有些不同,你不需要运行它,取而代之,你需要将它导入到 python 里通过自己执行函数的方式运行。


def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words
    
def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)
    print word

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1)
    print word

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)
    
def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)
    
def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

 

   
首先以正常的方式python ex25.py运行,找出里边的错误,并把它们都改正过来。然后你需要接着下面的答案章节完成这节练习。

呃。运行返回空,什么都没有。

这节练习我们将在你之前用来做算术的 python 编译器里,用交互的方式和你的.py 作交流。

 

$ python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> wrods
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'wrods' is not defined
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
>>> exit()
$

 


我们来逐行分析一下每一步实现的是什么:

在第 5 行你将自己的 ex25.py 执行了 import,和你做过的其它 import 一样。在 import 的时候你不需要加 .py 后缀。这个过程里,你把 ex25.py 当做了一个“模组(module)”来使用,你在这个模组里定义的函数也可以直接调用出来。
第 6 行你创建了一个用来处理的“句子(sentence)”。
第 7 行你使用 ex25 调用你的第一个函数 ex25.break_words。其中的 . (dot, period)符号可以告诉 Python:“嗨,我要运行 ex25 里的哪个个叫 break_words 的函数!”
第 8 行我们只是输入 words,而 python 将在第 9 行打印出这个变量里边有什么。看上去可能会觉得奇怪,不过这其实是一个“列表(list)”,你会在后面的章节中学到它。
10-11 行我们使用 ex25.sort_words 来得到一个排序过的句子。
13-16 行我们使用 ex25.print_first_word 和 ex25.print_last_word 将第一个和最后一个词打印出来。
第 17 行比较有趣。我把 words 变量写错成了 wrods,所以 python 在 18-20 行给了一个错误信息。
21-22 行我们打印出了修改过的词汇列表。第一个和最后一个单词我们已经打印过了,所以在这里没有再次打印出来。
剩下的行你需要自己分析一下,就留作你的加分习题了。

加分习题:
1.研究答案中没有分析过的行,找出它们的来龙去脉。确认自己明白了自己使用的是模组 ex25 中定义的函数。
2.试着执行 help(ex25) 和 help(ex25.break_words) 。这是你得到模组帮助文档的方式。 所谓帮助文档就是你定义函数时放在 """ 之间的东西,它们也被称作 documentation comments (文档注解),后面你还会看到更多类似的东西。

>>> import ex25
>>> help(ex25)
Help on module ex25:

NAME
    ex25

FILE
    c:\documents and settings\administrator\ex25.py

FUNCTIONS
    break_words(stuff)
        This function will break up words for us.

    print_first_and_last(sentence)
        Prints the first and last words of the sentence.

    print_first_and_last_sorted(sentence)
        Sorts the words then prints the first and last one.

    print_first_word(words)
        Prints the first word after popping it off.

    print_last_word(words)
        Prints the last word after popping it off.

    sort_sentence(sentence)
        Takes in a full sentence and returns the sorted words.

    sort_words(words)
        Sorts the words.


>>> help(ex25.break_words)
Help on function break_words in module ex25:

break_words(stuff)
    This function will break up words for us.

>>>

3.重复键入 ex25. 是很烦的一件事情。有一个捷径就是用 from ex25 import * 的方式导入模组。这相当于说:“我要把 ex25 中所有的东西 import 进来。”程序员喜欢说这样的倒装句,开一个新的会话,看看你所有的函数是不是已经在那里了。
4.把你脚本里的内容逐行通过 编译器执行,看看会是什么样子。你可以执行CTRL-D (Windows 下是 CTRL-Z)来关闭编译器。

 

 


至此,笨方法学python-ex25-更多更多的练习这一小节的学习结束了。

新手学python-笨方法学python-ex24-更多练习

LC 2015-11-08 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex24-更多练习 - 学习记录

课程内容:

你离这本书第一部分的结尾已经不远了,你应该已经具备了足够的 Python 基础知识,可以继续学习一些编程的原理了,但你应该做更多的练习。这个练习的内容比较长,它的目的是锻炼你的毅力,下一个习题也差不多是这样的,好好完成它们,做到完全正确,记得仔细检查。

print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print "--------------"
print poem
print "--------------"


five = 10 -2 + 3 - 6
print "This should be five: %s" % five

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates

    
start_point = 10000
beans, jars, crates = secret_formula(start_point)

print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)

start_point = start_point / 10

print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)

 


运行该程序:

$python ex24.py
Let's practice everything.
You'd need to know 'bout escapes with \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explanation

                where there is none.

--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.

$


加分习题:
1.记得仔细检查结果,从后往前倒着检查,把代码朗读出来,在不清楚的位置加上注释。

2.故意把代码改错,运行并检查会发生什么样的错误,并且确认你有能力改正这些错误。

 


至此,笨方法学python-ex24-更多练习这一小节的学习结束了。

新手学python-笨方法学python-ex21-函数可以返回东西

LC 2015-11-07 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex21-函数可以返回东西 - 学习记录

课程内容:

你已经学过使用 = 给变量命名, 以及将变量定义为某个数字或者字符串。接下来我们将让你见证更多奇迹。
我们要演示给你的是如何使用 = 以及一个新的python词汇return来将变量设置为“一个函数的值”。
有一点你需要及其注意,不过我们暂且不讲,先撰写下面的脚本吧:

def add(a, b):
    print "ADDIND %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b

print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)    
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Herght: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

# A puzzle for the extra credit, type it in anyway.

print "Here's is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

 

现在我们创建了我们自己的加减乘除数学函数: add, subtract, multiply, 以及 divide。重要的是函数的最后一行,例如 add 的最后一行是 return a + b,它实现的功能是这样的:

1.我们调用函数时使用了两个参数: a 和 b 。
2.我们打印出这个函数的功能,这里就是计算加法(adding)
3.接下来我们告诉 Python 让它做某个回传的动作:我们将 a + b 的值返回(return)。或者你可以这么说:“我将 a 和 b 加起来,再把结果返回。”
4.Python 将两个数字相加,然后当函数结束的时候,它就可以将 a + b 的结果赋予一个变量。
和本书里的很多其他东西一样,你要慢慢消化这些内容,一步一步执行下去,追踪一下究竟发生了什么。为了帮助你理解,本节的加分习题将让你解决一个迷题,并且让你学到点比较酷的东西。


运行该程序:


$python ex21.py
Let's do some math with just functions!
ADDIND 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Herght: 74, Weight: 180, IQ: 50
Here's is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDIND 35 + -4426
That becomes:  -4391 Can you do it by hand?

$


加分习题:
1.如果你不是很确定 return 的功能,试着自己写几个函数出来,让它们返回一些值。你可以将任何可以放在 = 右边的东西作为一个函数的返回值。

 

def larger_than(a, b):
    print "If %d is larger than %d?" % (a, b)
    return a > b

def larger_or_equal(a, b):
    print "If %d is larger or equal than %d?" % (a, b)
    return a >= b

def newsum(a, b):
    print "The sum of %d and %d is %d" %(a, b, a+b)
    return a + b
    
no = larger_than(1, 2)
print no
yes = larger_or_equal(2, 1)
print yes
sum = newsum(1, 2)

sums = newsum(newsum(1,2), newsum(3,4))


运行该程序:

$python ex21-1.py
If 1 is larger than 2?
False
If 2 is larger or equal than 1?
True
The sum of 1 and 2 is 3
The sum of 1 and 2 is 3
The sum of 3 and 4 is 7
The sum of 3 and 7 is 10

$


2.这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们链接到了一起,就跟写数学等式一样。这样可能有些难读,不过运行一下你就知道结果了。接下来,你需要试试看能不能用正常的方法实现和这个表达式一样的功能。


def add(a, b):
    print "ADDIND %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b

print "Let's do some math with just functions!"


age = add(30, 5)
print "+++++++++++++++++++++++++++++++++"
height = subtract(78, 4) 
print "+++++++++++++++++++++++++++++++++"   
weight = multiply(90, 2)
print "+++++++++++++++++++++++++++++++++"
iq = divide(100, 2)
print "+++++++++++++++++++++++++++++++++"

print "Age: %d, Herght: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)

# A puzzle for the extra credit, type it in anyway.

print "Here's is a puzzle."

#what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "*********************************"
x1 = divide(iq, 2)
print "*********************************"
x2 = multiply(weight, x1)
print "*********************************"
x3 = subtract(height, x2)
print "*********************************"
what = add(age, x3)
print "+++++++++++++++++++++++++++++++++"
print "x1: %d, x2: %d, x3: %d" % (x1, x2, x3)
print "+++++++++++++++++++++++++++++++++"
print "That becomes: ", what, "Can you do it by hand?"

 


运行该程序:

$python ex21-2.py
Let's do some math with just functions!
ADDIND 30 + 5
+++++++++++++++++++++++++++++++++
SUBTRACTING 78 - 4
+++++++++++++++++++++++++++++++++
MULTIPLYING 90 * 2
+++++++++++++++++++++++++++++++++
DIVIDING 100 / 2
+++++++++++++++++++++++++++++++++
Age: 35, Herght: 74, Weight: 180, IQ: 50
Here's is a puzzle.
*********************************
DIVIDING 50 / 2
*********************************
MULTIPLYING 180 * 25
*********************************
SUBTRACTING 74 - 4500
*********************************
ADDIND 35 + -4426
+++++++++++++++++++++++++++++++++
x1: 25, x2: 4500, x3: -4426
+++++++++++++++++++++++++++++++++
That becomes:  -4391 Can you do it by hand?

$

 

3.一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。

4.最后,颠倒过来做一次。写一个简单的等式,使用一样的函数来计算它。

5.这个习题可能会让你有些头大,不过还是慢慢来,把它当做一个游戏,解决这样的迷题正是编程的乐趣之一。后面你还会看到类似的小谜题。

 

至此,-ex21-函数可以返回东西这一小节的学习结束了。

新手学python-笨方法学python-ex20-函数和文件

LC 2015-11-06 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex20-函数和文件 - 学习记录

课程内容:

回忆一下函数的要点,然后一边做这节练习,一边注意一下函数和文件是如何在一起协作发挥作用的。

from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)


特别注意一下,每次运行 print_a_line 时,我们是怎样传递当前的行号信息的。

运行该程序:


$python ex20.py test.txt
First let's print the whole file:

To all the people out there.
I say I don't like my hair.
I need to shave it off.
Now let's rewind, kind of like a tape.
Let's print three lines:
1 To all the people out there.

2 I say I don't like my hair.

3 I need to shave it off.

$


加分习题:

1.通读脚本,在每行之前加上注解,以理解脚本里发生的事情。

2.每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量。在每次调用函数时,打印出 current_line 的至,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。

3.找出脚本中每一个用到函数的地方。检查 def 一行,确认参数没有用错。

4.上网研究一下 file 中的 seek 函数是做什么用的。试着运行 pydoc file 看看能不能学到更多。
 seek(...)
     seek(offset[, whence]) -> None.  Move to new file position.

     Argument offset is a byte count.  Optional argument whence defaults to
     0 (offset from start of file, offset should be >= 0); other values are 1
     (move relative to current position, positive or negative), and 2 (move
     relative to end of file, usually negative, although many platforms allow
     seeking beyond the end of a file).  If the file is opened in text mode,
     only offsets returned by tell() are legal.  Use of other offsets causes
     undefined behavior.
     Note that not all file objects are seekable.
    
5.研究一下 += 这个简写操作符的作用,写一个脚本,把这个操作符用在里边试一下。

a+=b意思就是a=a+b

>>> x = 100
>>> x += x
>>> print x
200
>>> x += 1
>>> print x
201
>>>

 


至此,笨方法学python-ex20-函数和文件这一小节的学习结束了。

新手学python-笨方法学python-ex19-函数和变量

LC 2015-11-05 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python--ex19-函数和变量 - 学习记录

课程内容:

函数这个概念也许承载了太多的信息量,不过别担心。只要坚持做这些练习,对照上个练习中的检查点检查一遍这次的联系,你最终会明白这些内容的。

有一个你可能没有注意到的细节,我们现在强调一下:函数里边的变量和脚本里边的变量之间是没有连接的。下面这个练习可以让你对这一点有更多的思考:

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print "You have %d cheeses!" % cheese_count
    print "You have %d boxes of crackers!" % boxes_of_crackers
    print "Man that's enough for a party!"
    print "Get a blanket.\n"
    
print "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)

print "Or, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)

print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)

print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)


通过这个练习,你看到我们给我们的函数 cheese_and_crackers 很多的参数,然后在函数里把它们打印出来。我们可以在函数里用变量名,我们可以在函数里做运算,我们甚至可以将变量和运算结合起来。

从一方面来说,函数的参数和我们的生成变量时用的 = 赋值符类似。事实上,如果一个物件你可以用 = 将其命名,你通常也可以将其作为参数传递给一个函数。

运行该程序:


$python ex19.py
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.

Or, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.


$

 

 

加分习题:
1.倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。

2.从最后一行开始,倒着阅读每一行,读出所有的重要字符来。

3.自己编至少一个函数出来,然后用10种方法运行这个函数。

没想到10种,先这么着吧:

def newsum(augend , added):
    sum = augend + added
    print "\nThe Augend is %d\nThe added is %d \nThe sum of %d and %d is %d." % (augend, added, augend, added, sum)
    print "It is say that %d + %d = %d."  % (augend, added, sum)

print """
********************1********************
We can just give the function numbers directly:
"""
newsum(10, 20)

print """
********************2********************
OR, we can use variables from our script:
"""
num1 = 100
num2 = 200
newsum(num1, num2)

print """
********************3********************
We can even do math inside too:
"""
newsum(100 + 10, 200 + 20)

print """
********************4********************
And we can combind the two, variables and math:
"""
newsum(num1 + 1, num2 + 2)

print """
********************5********************
We can set the variables inputed by user
"""
n1 = int(raw_input("Pls input augend: "))
n2 = int(raw_input("Pls input addes: "))
newsum(n1, n2)

print """
********************6********************
We can set the variables inputed by user,and math
"""
newsum(n1 + 1000, n2 + 5000)

print """
********************7********************
We can use argv to do this:"""
from sys import argv

script, x, y = argv
newsum(int(x), int(y))

print """
********************8********************
We can use argv and math to do this:""" 
newsum(int(x) - 100, int(y) - 200)

#print """
#********************9********************
#Also, we can get the the function parameter from file
#"""

 

运行该程序:

$python ex19-3.py 100 200

********************1********************
We can just give the function numbers directly:


The Augend is 10
The added is 20
The sum of 10 and 20 is 30.
It is say that 10 + 20 = 30.

********************2********************
OR, we can use variables from our script:


The Augend is 100
The added is 200
The sum of 100 and 200 is 300.
It is say that 100 + 200 = 300.

********************3********************
We can even do math inside too:


The Augend is 110
The added is 220
The sum of 110 and 220 is 330.
It is say that 110 + 220 = 330.

********************4********************
And we can combind the two, variables and math:


The Augend is 101
The added is 202
The sum of 101 and 202 is 303.
It is say that 101 + 202 = 303.

********************5********************
We can set the variables inputed by user

Pls input augend: 5000
Pls input addes: 6000

The Augend is 5000
The added is 6000
The sum of 5000 and 6000 is 11000.
It is say that 5000 + 6000 = 11000.

********************6********************
We can set the variables inputed by user,and math


The Augend is 6000
The added is 11000
The sum of 6000 and 11000 is 17000.
It is say that 6000 + 11000 = 17000.

********************7********************
We can use argv to do this:

The Augend is 100
The added is 200
The sum of 100 and 200 is 300.
It is say that 100 + 200 = 300.

********************8********************
We can use argv and math to do this:

The Augend is 0
The added is 0
The sum of 0 and 0 is 0.
It is say that 0 + 0 = 0.

$

 

至此,笨方法学-ex19-函数和变量这一小节的学习结束了。

新手学python-笨方法学python-ex18-命名、变量、代码、函数

LC 2015-11-04 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex18-命名、变量、代码、函数 - 学习记录

课程内容:

标题包含的内容够多的吧?
接下来我要教你“函数(function)”了!咚咚锵!说到函数,不一样的人会对它又不一样的理解和使用方法,不过我只会教你现在能用的最简单的使用方式。

函数可以做三样事情:

 1.它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
 2.它们可以接受参数,就跟你的脚本接受argv一样
 3.通过使用#1和#2,它们可以让你创建“微型脚本”或者“小命令”
 
你可以使用def新建函数。我将让你创建四个不同的函数,它们工作起来和你的脚本一样。然后我会演示给你各个函数之间的关系。


# this one is like your scripts with argv

def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r" % (arg1, arg2)

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
    print "arg1: %r, arg2: %r" % (arg1, arg2)
    
# this is just take one argument
def print_one(arg1):
    print "arg1: %r" % arg1
    
# this on takes no arguments
def print_none():
    print "I got nothing."

print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()

 


让我们把你的第一个函数print_two拆解一下,这个函数和你写脚本的方式差不多,因此你看上去应该会觉得比较眼熟:
 
  1.首先我们告诉创建一个函数,我们使用到的命令是def,也就是“定义(define)”的意思。
  2.紧接着def的是函数的名称。本例中它的名称是“print_two”,但是名字可以随便取,就叫“peanuts”也没关系。但最好函数的名称能够体现出函数的功能来。
  3.然后我们告诉函数我们需要*args(asterisk args),这和脚本的argv非常相似,参数必须放在圆括号()中才能正常工作。
  4.接着我们用冒号: 结束本行,然后开始下一行缩进。
  5.冒号以下,使用4个空格缩进的行都是属于print_two这个函数的内容。其中第一行的作用是将参数解包,这和脚本参数解包的原理差不多。
  6.为了演示它的工作原理,我们把解包后的每个参数都打印出来,这和我们在之前脚本练习中所作的类似。
 
函数print_two的问题是:它并不是创建函数最简单的方法。在函数中我们可以跳过整个参数解包的过程。直接使用()里边的名称作为变量名。这就是print_two_again实现的功能。

接下来的例子是print_one,它向你演示了函数如何接受单个参数。

最后一个例子是print_none,它向你演示了函数可以不接受任何参数。

Warning
如果你不太能看懂上面的内容也别气馁。后面我们还有更多的练习向你展示如何创建和使用函数。现在你只要把函数理解成“迷你脚本”就可以了。

运行上面的脚本:

$python ex18.py
arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1: 'First!'
I got nothin'.

$


你应该已经看出函数是怎样工作的了。注意到函数的用法和你以前见过的exists、open,以及别的“命令”有点类似了吧?
其实我只是为了让你理解才叫它们“命令”,它们的本质其实就是函数。也就是说,你也可以在自己的脚本中创建你自己的“命令”。

加分习题:
为自己写一个函数注意事项以供后续参考。你可以写在一个索引卡片上随时阅读,直到你记住所有的要点为止。注意事项如下:

函数定义是以 def 开始的吗?
函数名称是以字符和下划线 _ 组成的吗?
函数名称是不是紧跟着括号 ( ?
括号里是否包含参数?多个参数是否以逗号隔开?
参数名称是否有重复?(不能使用重复的参数名)
紧跟着参数的是不是括号和冒号 ): ?
紧跟着函数定义的代码是否使用了 4 个空格的缩进 (indent)?
函数结束的位置是否取消了缩进 (“dedent”)?


当你运行(或者说“使用 use”或者“调用 call”)一个函数时,记得检查下面的要点:

调运函数时是否使用了函数的名称?
函数名称是否紧跟着 ( ?
括号后有无参数?多个参数是否以逗号隔开?
函数是否以 ) 结尾?


按照这两份检查表里的内容检查你的练习,直到你不需要检查表为止。

最后,将下面这句话阅读几遍:

“‘运行函数(run)’、‘调用函数(call)’、和 ‘使用函数(use)’是同一个意思”

 

定义一个函数试试看:

 

def newsum(a,b):
    print " a = %d , b = %d " % (a, b)
    print "a + b = %d + %d = " %(a, b ), a+b
    

newsum(1,2)

运行该函数:

$ex18-0.py
 a = 1 , b = 2
a + b = 1 + 2 =  3

$


至此,ex18-命名、变量、代码、函数这一小节的学习结束了。


 

新手学python-笨方法学python-ex17-更多文件操作

LC 2015-11-03 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex17-更多文件操作 - 学习记录

课程内容:
现在让我们再学几种文件操作。我们将编写一个脚本,将一个文件中的内容拷贝到另外一个文件中。这个脚本很短,不过它会让你对于文件操作有更多的了解。

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

#we could do these two on one line too, how?
input = open(from_file)
indata = input.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

output = open(to_file, 'w')
output.write(indata)

print "Alright, all done."

output.close()
input.close()

 

你应该很快注意到了我们import了又一个很好用的命令exists。 这个命令将文件名字符串作为参数,如果文件存在的话,它将返回True,否则将返回False。在本书的下半部分,我们将使用这个函数做很多的事情,不过现在你应该学会怎样通过import调用它。

通过使用import,你可以在自己的代码中直接使用其他更厉害的程序员写的大量免费代码,这样你就不需要重写一遍了。

运行上面的程序:
 

 

C:\Documents and Settings\Administrator>python ex17.py ex17-sample.txt copied.txt
We are going to copy ex17-sample.txt to copied.txt
The input file is 80 bytes long.
Does the output file exist? False.
Ready, hit RETURN to continue, or hit CTRL-C to abort.
?
Allright, all done.

$

我们再看看copied.txt这个文件的内容,跟ex17-sample.txt的一样:

To all the people out there.
I say I don't like my hair.
I need to shave it off.

该命令对于任何文件都应该是有效的。试试操作一些别的文件看看结果。不过小心别把你的重要文件给弄坏了。


加分习题:
1.再多读读和 import 相关的材料,将 python 运行起来,试试这一条命令。试着看看自己能不能摸出点门道,当然了,即使弄不明白也没关系。

2.这个脚本 实在是 有点烦人。没必要在拷贝之前问一遍把,没必要在屏幕上输出那么多东西。试着删掉脚本的一些功能,让它使用起来更加友好。


 

from sys import argv

script, from_file, to_file = argv

print "We will copy %s to %s." % (from_file, to_file)
input = open(from_file)
indata = input.read()

output = open(to_file, 'w')
output.write(indata)

output.close
input.close

 

3.看看你能把这个脚本改多短,我可以把它写成一行。

 

暂时只能改成这样,运行成功,但是没办法close()。


4.我使用了一个叫 cat 的东西,这个古老的命令的用处是将两个文件“连接(con*cat*enate)”到一起,不过实际上它最大的用途是打印文件内容到屏幕上。你可以通过 man cat 命令了解到更多信息。

5.使用 Windows 的同学,你们可以给自己找一个 cat 的替代品。关于 man 的东西就别想太多了,Windows 下没这个命令。

6.找出为什么你需要在代码中写 output.close() 。

 

至此,-ex17-更多文件操作这一小节的学习结束了。

 

新手学python-笨方法学python-ex16-读写文件

LC 2015-11-02 Python

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python--ex16-读写文件件 - 学习记录

课程内容:

了解各种文件相关的命令(方法/函数):

close - 关闭文件。跟你编辑器的 文件->保存.. 一个意思。
read - 读取文件内容。你可以把结果赋给一个变量。
readline - 读取文本文件中的一行。
truncate - 清空文件,请小心使用该命令。
write(stuff) - 将stuff写入文件。

这是你现在该知道的重要命令。有些命令需要接受参数,这对我们并不重要。你只要记住write的用法就可以了。write需要接收一个字符串作为参数,从而将该字符串写入文件。

让我们来使用这些命令做一个简单的文本编辑器吧:

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C(^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally,we close it."
target.close()


这个文件是够大的,大概是你键入过的最大的文件。所以慢慢来,仔细检查,让它能运行起来。
有一个小技巧可以让你的脚本一部分一部分地运行起来。先写1-8行,让它运行起来;再多运行5行,再接着多运行几行,一次类推,直到整个脚本运行起来为止。

运行该脚本:

$python ex16.py ex16-sample.txt
We're going to erase 'ex16-sample.txt'.
If you don't want that, hit CTRL-C(^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: the 1st line for test.
line 2: the 2nd line.
line 3: the last line for check...
I'm going to write these to the file.
And finally,we close it.

$

接下来打开你新建的文件(我的是ex16-sample.txt),看看里面的内容。

the 1st line for test.
the 2nd line.
the last line for check...

 

加分习题:
1.如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。

2.写一个和上一个练习类似的脚本,使用 read 和 argv 读取你刚才新建的文件。

from sys import argv

script, filename = argv

print "We are going to erase %r." % filename
print "If you do not want that, hit CTRL-C(^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'w')

print "Truncating the file. GoodBye..."
target.truncate()


print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1) 
target.write("\n")
target.write(line2) 
target.write("\n")
target.write(line3) 
target.write("\n")

print "And finally,we close it."
target.close()

print "To see the new file content."
txt = open(filename)
print txt.read()
txt.close()


运行该脚本:

$python ex16-2.py ex16-sample.txt
We are going to erase 'ex16-sample.txt'.
If you do not want that, hit CTRL-C(^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. GoodBye...
Now I'm going to ask you for three lines.
line 1: abc
line 2: 123
line 3: hi hello
I'm going to write these to the file.
And finally,we close it.
To see the new file content.
abc
123
hi hello


$


3.文件中重复的地方太多了。试着用一个 target.write() 将 line1, line2, line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。
3.1 将6行target.write()换成target.write("%s \n %s \n %s \n" ) % (line1, line2, line3),运行程序,出错
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
3.2上网查了一下,字符串连接用 + :
将6行target.write()换成 target.write(line1 + "\n" + line2 + "\n" + line3 + "\n") ,成功:


 

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename

print """
If you do not want that, hit CTRL-C(^C).
If you do want that, hit RETURN.
"""

print "Opening the file ..."
target = open(filename, 'w')

print "Truncating the file ..."
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

#target.write(line1 "\n" line2 "\n" line3 "\n")
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n") 

print "And finally, we close it."

target.close()

print "Print the new contents of the file..."

newtxt = open(filename)
print newtxt.read()
newtxt.close

 

运行该程序:

$python ex16-3.py ex16-sample.txt
We're going to erase 'ex16-sample.txt'.

If you do not want that, hit CTRL-C(^C).
If you do want that, hit RETURN.

Opening the file ...
Truncating the file ...
Now I'm going to ask you for three lines.
line 1: test1
line 2: test2
line 3: test3
I'm going to write these to the file.
And finally, we close it.
Print the new contents of the file...
test1
test2
test3


$


4.找出为什么我们需要给 open 多赋予一个 'w' 参数。提示: open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作。
默认只读

至此,笨方法学-ex16-读写文件这一小节的学习结束了。