A good introduction to Python tutorial _python

Source: Internet
Author: User
Tags add numbers arithmetic data structures function definition sleep sodium uppercase letter python list
Originalhttp://www.hetland.org/python/instant-hacking.php

Instant hacking[Translation]

Translator: Must have come

This is a short introduction to the Python programming language tutorial, the original text here, turned the dictionary translated!

This is a brief introduction to the art of programming, examples of which are written in Python. (If you already know how to program, but want a quick look at Python, you can check out my other article instant Python.) This article has been translated into many languages, such as Italian, Polish, Japanese, Serbian and Brazilian grapes, and is being translated into Korean. (Translator: Of course, the Chinese version is now included, but the author does not know.) )

This article has nothing to do with how to break into someone else's computer system or something. I don't care about that sort of thing, so please don't email me about those things.

Note: To make the examples in this article work correctly, you should write them in a text file and then run them with an interpreter; do not attempt to run them directly in interactive mode--not all of them can run like this. (Don't ask me specifics about this.) It's best to check the Python documentation or email it to help@python.org.

1. Operating Environment

To write a program in Python, you must first install a Python interpreter. It can exist on most platforms (including Macintosh, UNIX, and Windows). More information about this can be found on the Python web site. You should also have a text editor (like Emacs, Notepad, or something like that).

2. What is programming?


Writing a program for a computer is actually giving it a series of instructions to tell it what to do. Computer programs in some ways are like recipes that guide us in how to cook. For example [1]:

Holiday Ham salad

Raw materials:

Pickled juice:
1/4 cups of sour orange juice
1/4 Cup low sodium soy sauce
1/4 cups of water
1 tablespoons vegetable oil
3/4 teaspoon cumin
1/2 tsp cow to
1/4 teaspoon hot pepper powder
2 slices of clove, garlic, mashed

Salad:
1 (12 ounces) canned little sodium lunch meat ham cut into strips
1 onions, slices
Pepper, chopped lettuce.
12 cherry tomatoes, cut half

Method:

Shake the marinade in a jar with a suitable lid. Use a plastic bag on ham, sprinkle with pickled juice, and seal the bag mouth. Marinate in the fridge for 30 minutes. Take the ham out of the plastic bag, prepare 2 tablespoons of pickled juice and boil it in a boiling pot. Add ham, onion, green pepper. Burn for 3-4 minutes until the ham is ripe ...

Of course, no computer will understand this ... And even if you know it, most computers won't be able to bake a salad. So how do we make this more user-friendly for computers? Fundamentally depends on two: first, we must communicate with it in a way that computers can understand, and then talk to it about what it can do.

The 1th means that we have to use a language-a programming language that has been prepared for the interpreter, and 2nd means we can't expect the computer to make a salad for us-but we can make it add numbers or print things on the screen.

3. Hello ...

Programming tutorials have a tradition of printing "Hello, world!" on the screen This program is done as a start. For Python, it's very simple:

Print "Hello, world!"


It's basically like the recipe (albeit much shorter!). )。 It tells the computer what to do: print "Hello, world!". What if you let it print more nonsense? Very simple:

Print "Hello, world!"

Print "Goodbye, world!"


No, it's harder than last, isn't it? But not very interesting ... We hope it can handle more elements, just like salad recipes. So what are the elements that we all have? First, there are strings, like "Hello, world!," and there are numbers in addition. Suppose we're going to let the computer compute the size of the rectangle for us. We can give it the following recipes:

# The area of a Rectangle


# Ingredients:

width = 20
Height = 30

# Instructions:

Area = width * height
Print Area


You can probably see the similarity between it and the ham salad recipe (albeit slightly different). But how does it work? First, the line starting with # is called a comment and is actually ignored by the computer. However, inserting annotations such as this one is important for enhancing the readability of your program.

Next, rows that look like Foo = bar are called assignments. In the case of width = 20, it means to tell the computer to start from here, the width represents 20. It also means that a variable with the name "width" is created (if it had already existed, it would be overwritten). So, when we use this variable later, the computer knows its value. So

Width * height

Essentially the same

20 * 30

It calculates the 600 result and assigns it to the variable named "area." The last sentence of the program prints out the value of the variable "area" on the screen, so you see that the end result of the program running is just

600

Note: In some programming languages, you have to tell the computer at the beginning of the program which variables you will use (like the elements in a salad)-and Python is smart enough so you can create it whenever you need to.

4. Feedback

Now, you can perform some simple, or more complex, calculations. For example, you might want to write a program that calculates the area of a circle rather than the rectangle:


RADIUS = 30

Print radius * radius * 3.14


However, this is actually no more interesting than the program that calculates the rectangular area. At least that's what I think it is. It's a little stiff. What if we see a circle with a radius of 31? How to let the computer know? This is a bit like the salad recipe: "Burn for 3-4 minutes until the ham is ripe." "To know when to cook, we must check." We need feedback, or hints. How does the computer know the radius of our circle? Also need to enter data ... What we can do is tell the computer the radius of how much:


RADIUS = input ("What is the radius?")
Print radius * radius * 3.14


Now the program is getting prettier ... input is something called a function. (soon you will learn to create your own functions.) and input is a built-in Python function. ) Just write down

Input

Nothing can be done ... You have to put a pair of braces on the back of it. So input () works-it will simply require the user to enter the length of the radius. The above version may be friendlier to the user because it first prints out a problem. When we will be like the question string "What is the radius"? That sort of thing is placed in parentheses in a function call, this process is called the parameter pass of a function. The contents of the parentheses are called parameters. In the last example we passed a question as a parameter so that input knew what to print first before getting an answer.

But how does the answer get to the radius variable? function input, when invoked, returns a value (like many other functions). You don't have to use this value, but like in our case, we're going to use it. In this way, the following two expressions have a big difference:


Foo = input
bar = input ()

Foo now contains the input function itself (so it can actually be like foo ("What is your age?") This is used; This is called a dynamic function call) and bar contains the values that the user types.


5. Process

Now we can write programs to perform simple tasks (arithmetic and print) and get user input. This is useful, but it is still limited to executing commands sequentially, that is, they must be executed in a prearranged order. Most ham salad recipes are like this in order or linear narration. But what if we're going to let the computer check that the salad is cooked? If it burns well, it should be taken out of the oven-otherwise, it should be burned for a long time or something. How do we express this?

What we want to do is actually the process of controlling the program. It can be carried out in two directions-either take the ham off or keep it in the oven. We can choose if it burns well. This is called conditional execution. We can write this:


Temperature = input ("What is the temperature of the spam?")

If temperature >; 50:
Print "The salad is properly cooked."
Else
Print "Cook the salad some more."


The meaning is obvious: if the temperature exceeds 50 (degrees Celsius), then print out the information to tell the user to burn well, otherwise, tell the user to be fired for a period of time.

Note: Indenting is important in Python. The statement blocks in the conditional execution (and also the loop execution and function definition-see later) must be indented (and an equal number of spaces should be indented; a key is equivalent to 8 spaces) so that the interpreter can know where to start and where to end. This also makes the program more readable.

Let's go back to the previous area calculation problem. Can you see what this program does?


# Area Calculation Program

Print "Welcome to" "Calculation"
Print "---------------------------------------"
Print

# Print out the menu:
Print "Please select a shape:"
Print "1 Rectangle"
Print "2 Circle"

#Get the user ' s choice:
Shape = input (">;")

#Calculate the area:
if shape = = 1:
Height = input ("Please enter the height:")
width = input ("Please enter the width:")
Area = Height *width
Print "the??", Area
Else
RADIUS = input ("Please enter the radius:")
Area = 3.14 * (radius**2)
Print "the??", Area


The new thing in this example:
1. Using print itself will print out a blank line
2. = = Check whether two values are equal, unlike =, which assigns the value on the right side of the expression to the variable on the left. This is a very important difference!
3. * * is the power operator of Python--so the square of the radius is written radius**2
4. Print prints out more than one thing. Just separate them with commas. (They are separated by a single space in the output.) )

The program is simple: It takes a number and tells it that the user is going to let it compute the size of the rectangle or the circle. Then, use an if statement (conditional execution) to determine which statement block should be executed to compute the area. The two statement blocks are essentially the same as the block of statements used in the previous area calculation example. Note how annotations make your code more readable. The first commandment of programming is: "You should comment!" "In any case--it is a good habit that should be developed."

Exercise 1:


Expand the above program so that it includes the calculation of the square area, the user just enter the length of one side of it can be. Before doing this exercise you need to know one thing: if you have more than two choices, you can write like this:


if foo = = 1:
# do something ...
elif Foo = = 2:
# do something else ...
elif foo = = 3:
# If All else fails ...


The elif here is the mysterious code meaning "else if":). So, if Foo equals 1, do something; otherwise, if Foo equals 2, do something else, and so on. You can also add other options to the program--like triangles and freeform polygons. Whatever you have to do.

6. Cycle

Sequential execution and conditional execution are only two of the three basic block schema methods for programming. The third one is loop execution. In the last paragraph I assumed a situation in which the ham had been burnt, but it was obvious that it did not apply. What should I do if the ham is still not burning at the next inspection? How do we know how many times we need to check? In fact, we don't know. And we don't need to know. We can ask the computer to keep checking until it is ready to burn. How do you express this? You guessed--we use loops, or repeat execution.

Python has two types of loops: the while loop and the For loop. The For loop is probably the simplest. As an example:


For food in "spam", "eggs", "tomatoes":
print "I Love", food


It means: For the list "spam", "eggs", "tomatoes" in each element, print out you like it. The statement blocks in a loop are executed once for each element, and the current element is assigned to the variable food (in this case) each time it executes. Another example:


For number in range (1, 100):
Print "Hello, world!"
Print "Just", 100-number, "More to go ..."

Print "Hello, World"
Print "That is the last one ... Phew! "


Function range Returns a list of numbers for a given range (including the first number, excluding the last ...). This example is [1]. 99]). So, explain it this way:

The Loop body is 1 (including) to 100 (excluding) between the number each executed once. (which is the loop body and what the subsequent expressions actually do to stay for practice.) )

But this has no real help for our cooking problems. If we're going to check the Ham 100 times, that's a good solution, but we don't know if it's enough--or too much. We just want it to continue to check when the temperature is not up (or until it is hot enough-roughly a certain state). So, we use while:


# spam-cooking Program

# Fetch the function sleep
From time import sleep

Print "Please start cooking the spam." (I'll be 3 minutes.) "

# Wait for 3 minutes (which is, 3*60 seconds) ...
Sleep (180)

Print "I ' m baaack:)"

# How are hot enough?
Hot_enough = 50

Temperature = input ("How hot is the spam?")
While temperature < hot_enouth:
Print "Not hot enough ... Cook it a bit more ... "
Sleep (30)
Temperature = input ("OK, how hot are It now?")

Print "It ' s hot enough-you ' re done!"

The new thing in this example ...

1. Some useful functions are stored in modules and can be imported. In this example, we imported the function sleep from the time module in Python (it stops for a given number of seconds). (It's also possible to do your own module ...) )

Exercise 2:

Write a program that continues to get data from the user and then adds it up until their sum is 100. Write a program to get 100 data from the user and print out their and.

Bigger programs-abstraction

If you want to know the general content of a book, you don't go through all the pages-you just look at the catalogue, don't you? It will list the main contents of the book. Now--Imagine writing a cookbook. Many recipes, like "Cream Ham and pasta" and "Swiss ham Pies" are likely to contain the same things, such as Ham, in which case-you certainly don't plan to repeat how to make ham in every recipe. (OK ...) You may not actually make ham ... But in order to do the example, please endure:). You'll put the recipe for ham in a separate chapter, and just refer to it in other chapters. So--instead of a complete description in each recipe, you just have to refer to the name of the chapter. This is called abstraction in computer programming.

Are we already running something like this? Yes. We didn't tell the computer in detail how to get an answer from the user (well--we didn't really do it ...). In the same way ... We don't really do ham:) but simply use a input--function instead. We can actually construct our own functions to apply to this type of abstraction.

Suppose we want to find the largest integer smaller than the given positive number. For example, given 2.7, this number should be 2. This is often referred to as the "bottom line (floor)" of a given number. (This can actually be done with Python's built-in function int, but, again, bear with me as an example ...) What should we do? A simple solution is to start by trying every possible number from 0:


Number = input ("What is the number?")

Floor = 0
While floor <= number:
Floor = floor + 1
Floor = floor-1

Print "The floor of", number, "is", floor


Note that when the floor is no longer less than (or equal to) the given number, the loop ends; we add too much 1 to it. So we have to subtract 1 for it. What if we want to apply it to a complete mathematical operation? We have to write a complete loop for the cardinality of each number ("Floor"-ing). It's not comfortable ... You might have guessed what we're going to replace it with: put it in our own function, named "Floor":


def floor (number):
result = 0
While result <= number:
result = result + 1
result = Result-1
return result


The new thing in this example ...

1. Functions are defined with the keyword Def, followed by the function name and enclose the required arguments in parentheses.
2. If a function is required to return a value, it is handled using the keyword returns (it also automatically ends the function definition).

After defining a function, we can use it like this:


x = 2.7
y = Floor (2.7)


After execution, the value of y should be 2. It is also possible to define a function that has more than one parameter:


def sum (x, y):
return x + y


Exercise 3

Write a function that looks for a common factor of two numbers in Euclidean method. The work process is like this:

1. Assuming two numbers, a and b,a greater than B
2. Repeat the following steps until B becomes 0:
1. A becomes a value of B
2. b becomes the remainder of B before changing the value without changing the value
3. Returns the last value of a

Tips:

* Use a and B as parameters for the function
* Simple set A is greater than B
* x divided by z remainder is computed with expression x Z
* Two variables can be assigned like this: x, y = y, y+1. Here x is assigned a value of Y (this means that Y is already specified on this front) and y is incremented by 1.

7. Deep function

How do you do the exercises above? Is it difficult? Not quite sure about the function? Don't worry-I haven't finished my topic yet.

The extraction method we use when building functions is called process abstraction, and many programming languages use the same keyword process as functions. In fact, the two concepts are different, but in Python they are called functions (because they are more or less defined and used in the same way).

What is the difference between a function and a procedure (in other languages)? Well--as you can see in the previous paragraph, the function returns a value. The difference is that the procedure does not return such a value. In many cases, it is useful to divide a function into two types--the return value and not the return value--in this way.

A function (procedure) that does not return a value can be used as a subroutine or routine. We call these functions, they make certain materials, like foam milk. We can use this function in many places without having to rewrite its code (which is called Code reuse) and you'll know it's not just here.

Another benefit of such a function (or process) is that it alters the environment (for example, mixing sugar and cream together, their entire external state changes) Let's look at an example:

def hello (WHO):
Print "Hello,", who

Hello ("World")
# prints out ' Hello, world '


Printing out content is part of it, because this is the only thing the function needs to do, it is actually a typical so-called process. But...... It doesn't actually change its operating environment, does it? How can it change? Let's try this:

# The *wrong* way of doing it
Age = 0

Def setage (a):
Age = A

Setage (100)
Print Age
# prints "0"


Where's the mistake? The error in the function Setage creates its own local variable, also named Age, which is only available within the Setage function. How can we avoid this problem? We can use global variables.

Note: Global variables are not commonly used in Python. They are easy to cause bad code organization structure, is called the Spaghetti code. I use them here to elicit a more complex technical problem-if you can try to avoid using them.


[color= #FF0000] not finished translating ... [/color]

rockety back to: 2005-06-06 09:27:59

[color=red] translated, just careless, not in my blog posted on the whole, and did not give indentation. : oops: It was corrected together today. Thanks to WOLFG, and gives the correct indentation. Here are the rest: [/color]

By telling the interpreter that a variable is global (with an expression like global age), we actually
Tells it to use this variable outside of the function, rather than recreating a new local variable. (So, and local
On the contrary, it is global. Therefore, the above program can be rewritten like this:

# the correct, but Not-so-good way of doing it
Age=0

Def setage (a):
Global Age

Setage (100)
Print Age

# prints "100"

After understanding the object (and then talking about it), you will find that a better solution to the problem is to use a
The object of the method of Sex and setage. In the Data structure section, you will also find some functions that change the environment of the better
Example.
Okay-so what's the real function like? What is a function, in fact? Mathematical functions like a "machine"
, get the input and then compute the result. It will return the same result each time if it provides the same input each time.
For example:

def Square (x):
Return x*x

This is the same as the mathematical function f (x) =x*x. It behaves like an exact function, relying only on its loss
into, under no circumstances will change its environment.

So--I'm here to describe two constructors: a type is more like a procedure, and does not return any knots
The other is more like a mathematical function, and (almost) doing nothing is to return a result. Of course, in
It is possible to do something between these two extremes, although when the function changes things, it should be clear that it is changed
Changed. You can differentiate them by labeling them, such as "pure" functions like square.
Nouns and functions like setage use the name of an order such as the word.

9. More types-Data structures

Now-you know a lot: how to input output, how to design complex algorithms (procedures) to hold
Do the math, but the show is still behind us.

What are the components of the program that we have used so far? Numbers and strings, right? Boring kind of
Class...... Now let's introduce two or three other ingredients to make things more interesting.

A data structure is an ingredient of a kind of organization. (Surprise, surprise ...) There's no real data for a single data
Structure, isn't it? But suppose we need to put a lot of it together as a component--that requires some kind of structure.
For example, we might want a list of data. That's easy:

[3, 6, 78, 93]

In the loop I mentioned the list, but didn't really describe it. OK--Here's how you create it. Only
You need to list the elements, separated by commas, plus square brackets.

Look at an example of a calculated prime number that is divisible by only 1 and itself:
 
# calculate all the primes below 1000
#  (not the best  way to do it, but ...)

Result = [1]
Candidates = range (3, 1000)
Base = 2
Product  = base

While candidates:
    while product <  1000:
        if product in candidates:
             candidates.remove (product)
         product = product+base
    result.append ( Base)
    base = candidates[0]
    product =  base
    del candidates[0]
    result.append (base)
    print result

The new thing in this example ...

The built-in function range actually returns a list that can be used like all other lists. (It includes the first
A number, but excluding the last number. )

Lists can be used as logical variables. True if it is not NULL, otherwise false. Therefore, while
Candidates means "while the list that is called candidates is not empty" or simply "while saving
At candidates. "

You can use if someelement in somelist to check whether an element is in the list.

You can use Somelist.remove (someelement) to remove someelement from the somelist.

You can add elements to a list using somelist.append (something). In fact, you can also make
with "+" (like Somelist = Somelist+[something]). But the efficiency is not too high.

You can do this by adding parentheses around the list name to denote the position of an element (oddly, the column
The 1th element of the table, the position is 0, to get an element of the list. So somelist[3] is somelist
The fourth element of the list (by analogy).

You can delete variables using the Keyword DEL. It can also be used to remove elements from the list (just like here).
Del Somelist[0] therefore deletes the first element in the Somelist list. If you delete the front table is [1, 2,
3] After deletion, it becomes [2, 3].

Before continuing to describe the elements in the index list, let me briefly explain the example above.

This is a version of ancient arithmetic, known as "The Sieve of Erastothenes" (like this). It considers a
Series given a number (in this case a list), and then an organized deletion of a number that is known not to be a prime. How to Know
Road? Just see if they can be broken down into two other numbers.

We start with a candidate list that contains a number [2...999]--we know that 1 is prime (in fact, it might
Yes or maybe not, see who you ask), we want all primes less than 1000. (In fact, our waiting
The select list is [3...999], but 2 is also the candidate number because it is our first base. We also have a list called result, which contains the latest results at any time. At first, it contained only 1. We also have a variable called base. Each loop, we delete the number that is its multiple (it is always the smallest number in the candidate list). After each loop, we know that the smallest number remaining is prime (because we have deleted all the numbers that can be decomposed).

So we add it to result and set it to the new base, and then remove it from the list (so it doesn't
It's calculated again). When the candidate list is empty, the result list will contain all the primes. Exquisite, huh!
Think about it: Is there anything special about the first cycle? Base was 2, but it was filtered as well. For what
Do you? Why doesn't this happen to other base values? We're going to be able to determine if it's in the candidate column when we remove product
What about the table? Why?

What's next? Oh, yes...... Index. and a slice. They're getting a single from the Python list
The method of the element. You've seen the normal indexing behavior. It's quite simple. In fact, I've told you all about it.
You need to know something about it, except for one thing: a negative index is computed forward from the end of the list. So
Somelist[-1] is the last element of the somelist, somelist[-2] is an element before it, followed by a class
Push.

Slices, still, are unfamiliar to you. It's similar to the index, except that the slices can get all the
Elements, not just the individual elements. How does this work? Like this:

food = ["spam", "spam", "eggs", "sausages", "spam"]
Print Food[2:4]

# prints ' [' eggs ', ' sausages '] '

10. Continue to abstract-object and object oriented programming

Now there is a popular word called "object-oriented programming."

As the title suggests, object-oriented programming is just another way of abstracting detail. Program through
Naming abstracts simple descriptions into complex operations. In object-oriented programming, we can not only treat programs like this,
They can also be used as objects. (now, this is going to surprise you, huh!) For example, if you write a fire leg
Sequence, we don't have to write a lot of processes to deal with temperature, time, ingredients, etc., we can combine them into a fire
Leg object. Or maybe we can have the stove object and the clock object again ... Then, things like temperature become
A property of the Ham object, while the time can be read from the clock object. To use our program to do certain things, we
We can teach our objects certain ways; For example, the stove should know how to cook ham.

So--How do we do it in Python? We can't make an object directly. Cannot directly create a
Stove, but instead make a recipe to describe what the stove should look like. So this recipe describes a list of what we call
A class of objects of the stove. A very simple stove class may be like this:

Class Oven:

def insertspam (self, spam):
Self.spam = Spam

def getspam (self):
Return Self.spam

Does it look hard to understand, or what?

The new thing in this example ...

The class for the object is defined with the keyword class.

The name of a class usually starts with an uppercase letter, and the names of functions and variables (as well as properties and methods) are written in lowercase
Mother started.

The definition of the method (that is, the function and operation that lets the object know how to do it) is not special, but the
Definition inside.

The first argument for all object methods should be called self (or something like ...). ) The reason is soon clear
Out.

Object properties and methods you can access this: Myspam.temperature = 2 or Dilbert.be_nice
()。

I can guess some of the things in the above example you still don't know. For example, what is self? Also, now we
With object recipes (i.e. classes), how do we actually construct an object?

Let's reverse the order first. Objects are created by referencing the class name like a reference function:

Myoven = oven ()

Myoven contains a oven object, usually called an instance of the oven class. Let's say we have a structure.
A spam class, then we can do it like this:

Myspam = Spam ()
Myoven.insertspam (Myspam)

Myoven.spam will now contain myspam. What's going on? Because, we call a method of an object
, the first argument, usually called self, always contains the object itself. (Ingenious, ha!) Thus, Self.spam =spam this line sets the value of the spam property of the current oven object to the parameter spam. Note that they are two different things, although in this case they are called spam.

11. Exercise 3 Answers

This is a very concise version of the algorithm:

Def Euclid (A, B):
While B:
A, B = B, a%b
Return a

12. For reference
[1] Holiday ham salad Recipes excerpted from 獺 Ormel foods bad loving shadow ideal like live?
Copyright nbsp; Magnus Lie Hetland must have come [translate]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.