A nice tutorial for getting started with Python

Source: Internet
Author: User
Tags mathematical functions sodium uppercase letter
Originalhttp://www.hetland.org/python/instant-hacking.php

Instant hacking[Translation]

Translator: Must have come

This is a short introductory tutorial on the Python programming language, which is translated by a dictionary!

This is a brief introduction to the art of programming, in which examples are written in Python. (If you already know how to program, but want to get a quick look at Python, you can check out my other article instant Python.) This article has been translated into many languages, such as Italy, Poland, Japan, Serbia, and Brazilian grape language, 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 kind of thing, so please don't email me those things.

Note: To make the examples in this article work correctly, you should write them in a text file and run them with an interpreter, and don't try to run them directly in interactive mode--not all of them can run like this. (Don't ask me specific details about this.) It is best to check the Python documentation or email 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 website. 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, the kind that guides us on how to cook. For example [1]:

Holiday Ham salad

Raw materials:

Pickled juice:
1/4 Cup lime juice
1/4 Cup low sodium soy soy sauce
1/4 cups of water
1 tbsp vegetable oil
3/4 tsp cumin
1/2 tsp oregano
1/4 tsp hot pepper powder
2 slices cloves, garlic, mashed

Salad:
1 Servings (12 oz.) canned little sodium lunch pork and ham cut into strips
1 slices of onion, sliced
Pepper, chopped lettuce.
12 cherry tomatoes, cut in half

Method:

Shake the marinade in a jar with a suitable lid. Put the ham on a plastic bag, pour on the marinade and seal the mouth. Marinate in the refrigerator for 30 minutes. Remove the ham from the plastic bag and prepare 2 tablespoons of marinade to boil in a saucepan. 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 will not be able to burn a salad. So how do we make this a little more friendly to computers? Fundamentally, it relies on two points: first, we must communicate with it in a way that computers can understand, and then talk about what it can do.

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

3. Hello ...

Programming tutorials have a tradition, usually to print "Hello, world!" on the screen Such a program is done as a start. For Python, this is very simple:

Print "Hello, world!"


It's fundamentally like the recipe above (though it's 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 the last, isn't it? But not very interesting ... We want it to handle more elements, just like a salad recipe. So, what elements do we have? First, there are strings, like "Hello, world!," and there are numbers. Suppose we're going to have the computer calculate the area 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 how similar it is to the ham salad recipe (albeit slightly different). But how does it work? First, a line that starts with # is called a comment and is actually ignored by the computer. However, inserting annotations such as this small paragraph is important to enhance the readability of your program.

Next, a line that looks like Foo = bar is called an assignment. In the case of width = 20, it is telling the computer to start from here and the width represents 20. It also means that a variable named "width" has since been created (if it had already existed before, it would be overwritten again). So, when we use this variable later, the computer knows its value. So

Width * height

Essentially the same

20 * 30

The result is calculated as 600 and then assigned to a variable with the name "area". The last sentence of the program prints the value of the variable "area" on the screen, so you see that the end result of this program is just

600

Note: In some programming languages, you must tell the computer what variables you will use (like the elements in the salad) at the beginning of the program, and Python is smart enough so that you can create them whenever you want.

4. Feedback

Now, you can do some simple, or more complicated, calculations. For example, you might want to write a program to calculate the area of a circle rather than a rectangle:


RADIUS = 30

Print radius * radius * 3.14


However, this is not actually more interesting than the program that calculates the rectangular area. At least it seems to me. It's a little stiff. What if we see a circle with a radius of 31? How to get the computer to know? It's kind of like a 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 input data ... What we can do is tell the computer what the radius is:


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


Now the program has become more beautiful ... input is something called a function. (soon you will learn to create your own functions.) And input is a python built-in function. ) Just write down

Input

Nothing will do ... You have to put a pair of parentheses behind it. So input () can work-it simply requires 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 like the question string "What is the radius?" When placed in parentheses in a function call, this process is called the function's argument pass. The contents in parentheses are called parameters. In the previous example, we passed a question as a parameter so that input knows what to print before getting an answer.

But how does the answer get to the radius variable? function input, when called, 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 make a big difference:


Foo = input
bar = input ()

Foo now contains the input function itself (so it can actually be like foo ("What's Your Age?") This is used; This is called a dynamic function call) and bar contains the value that the user typed.


5. Process

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

What we want to do is actually the process of controlling the control. It can be carried out in two directions-either take the ham off or continue to leave 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 is more than 50 (degrees Celsius), then print out the information to tell the user to burn, otherwise, tell the user to fire for a period of time.

Note: Indenting is important in Python. The statement block in conditional execution (along with loop execution and function definition-see later) must be indented (and the equivalent number of spaces is indented) 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 the area calculation program"
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 are", area
Else
RADIUS = input ("Please enter the radius:")
Area = 3.14 * (radius**2)
Print "The area are", area


What's new in this example:
1. Print out a blank line only using print itself
2. = = checks 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 is capable of printing more than one thing. Just separate them with commas. (They are separated by a single space when they are output.) )

The program is simple: It takes a number and tells it that the user intends to have it calculate the area of a rectangle or circle. Then, use an if statement (conditional execution) to determine which statement block should be executed to calculate the area. These two statement blocks are essentially the same as the block of statements used in the previous area calculation example. Be aware of how annotations make your code more readable. The first commandment of programming is: "You should comment!" "Anyway – it's a good habit to develop."

Exercise 1:


Extending the above program to include the calculation of the square area, the user can simply enter the length of one side of the line. One thing you need to know before doing this exercise: 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 that means "else if":). So, if Foo equals 1, do something, otherwise, if Foo equals 2, then do something else, and so on. You can also include other options-like triangles and freeform polygons-in your program. Whatever you have to do.

6. Cycle

Sequential execution and conditional execution are just two of the three basic statement block architectures that are programmed. The third one is loop execution. In the last paragraph I assumed a case to check if the ham was burnt, but obviously it did not apply. What if the ham is still not burnt on the next check? 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 it-we used loops, or repeated executions.

Python has two types of loops: a while loop and a 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 the loop are executed once for each element, and each time it executes, the current element is assigned to the variable food (in this case). Another example:


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

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


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

The Loop body is 1 (inclusive) to 100 (excluding) the number between each execution once. (which is the loop body and what the subsequent expression actually does to stay as an exercise.) )

But this does not help our cooking problem in real terms. If we're going to check the Ham 100 times, it's a good solution, but we don't know if it's enough-or too much. We just want it to keep checking when the temperature doesn't reach (or until it's 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 back in 3 minutes.) "

# Wait for 3 minutes (that's, 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 are 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 the module and can be imported. In this example, we import the function sleep from the time module that is in Python (it is a given number of seconds to rest). (It's also possible to do your own module ...) )

Exercise 2:

Write a program that continuously obtains the data from the user and then adds it until their sum is 100. Then write a program that obtains 100 data from the user and prints 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 "creamy Ham Tong xin noodles" and "Swiss ham Pies" are likely to contain the same things, such as Ham, in which case-you certainly don't intend to repeat how to make ham in each recipe. (All right ...) You may not actually make ham ... But for example, please bear it:). You will put the recipe for making the ham in a separate chapter, and only refer to it in other chapters. This--instead of a full description in each recipe, you just have to quote the chapter name. This is called abstraction in computer programming.

Have we already run 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 have a ham:) It's a simple use of 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 less than a given positive number. For example, given 2.7, this number should be 2. This is often referred to as the "bottom line" of a given number. (This can actually be handled with Python's built-in function int, but please bear with me again for example ...). What should we do? A simple solution is to try every possible number from 0 onwards:


Number = input ("What's 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 from 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 very uncomfortable ... You may have guessed what we replaced: 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. The function is defined by the definition of the keyword Def, followed by the letter name and enclosed in parentheses to enclose the required parameters.
2. If a function is required to return a value, use the keyword return to handle it (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 multiple parameters:

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


Exercise 3

Write a function that uses the Euclidean method to find a common factor of two numbers. The working process is this:

1. Assume 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 before a divided by the value of no change
3. Returns the last value of a

Tips:

* Use A and B as arguments to functions
* Simple set A is greater than B
* The remainder of x divided by Z is calculated using the expression x% Z
* Two variables can be assigned together like this: x, y = y, y+1. Here x is assigned the value Y (which means that Y has been specified before) and Y is incremented by 1.

7. In-depth functions

What do the above exercises do? Is it difficult? Not sure about the function yet? Don't worry-I haven't finished my talk yet.

The extraction method we use to build our functions is called process abstraction, and many programming languages use the same function as the functions of the keyword process. In fact, these 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 another language)? Well--as you can see in the previous paragraph, the function returns a value. The difference is that the process does not return such values. Many times, it is useful to divide a function into two types--return values and non-return values--in this way.

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

Another usefulness of such a function (or process) is that it changes the environment (for example, by mixing sugar and cream, 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 what it does on one hand, because this is the only thing that this function needs to do, it's actually a typical so-called process. But...... It doesn't actually change its operating environment, does it? How can it be changed? Let's try it:

# The *wrong*-doing it
Age = 0

Def setage (a):
Age = A

Setage (100)
Print Age
# Prints "0"


Where's the mistake? The wrong function setage creates its own local variable named age, which is only available inside the Setage function. So how can we avoid this problem? We can use global variables.

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


[color= #FF0000] did not finish translation ... [/color]

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

[color=red] translated, just careless, not on my blog affixed to the whole, but also did not give the indentation. : oops: It was corrected today. Thank WOLFG for the repost, and gave the correct indentation. Here's the rest: [/color]

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

# the correct, but not-so-good the doing it
Age=0

Def setage (a):
Global Age

Setage (100)
Print Age

# Prints "100"

Once you understand the object (and then talk about it), you'll find a better way to solve this problem is to use an age-dependent
The object of the Setage method. In the Data structure section, you will also find some functions to change the environment of the better
Example.
Okay-so what's the real function? What is a function, in fact? Mathematical functions like a "machine
Input, and then calculate the result. It returns the same result every 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.
Not change its environment under any circumstances.

So--I'm here to describe two kinds of constructors: a type that is more like a process, does not return any knot
The other is more like a mathematical function, and (almost) nothing is done to return a result. Of course, in
It is possible to do something between these two extremes, although it should be clear when the function changes things.
Has changed. You can differentiate them by marking their names, for example, for "purely" functions using square-like
Nouns whereas functions like setage use the name of an imperative such as a.

9. More types-Data structures

Now--you already know a lot: how to input output, how to design complex algorithms (Programs) to
Math, but the show is still behind us.

What ingredients have we used in the process so far? Numbers and strings, right? A boring species.
Class...... Now let's introduce two or three other ingredients to make things more interesting.

The data structure is the constituent of the organization. (Surprise, surprise ...) There is no real data for the individual data
Structure, isn't it? But suppose we need a lot of it together as an ingredient-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 that paragraph I mentioned the list, but did not really describe it. OK--Here's how you create it. Only
The elements need to be listed, separated by commas, and square brackets on the line.

Take a look at an example of a prime number that can only be divisible by 1 and itself:

# Calculate all the primes below 1000
# (not the best-of-the-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 does not include the last number. )

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

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

You can use Somelist.remove (someelement) to delete the someelement in Somelist.

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

You can add a number to the position of an element by enclosing it in parentheses after the list name (strangely, the column
The 1th element of the table, the position is 0) to obtain an element of the list. So somelist[3] is somelist
The fourth element of a list (and so on).

You can use the Keyword del to delete a variable. It can also be used to remove elements from the list (just like here).
So del Somelist[0] deletes the first element in the Somelist list. If the list of deletions 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 above example.

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

Let's start with a candidate list of numbers [2...999]-we know that 1 is prime (in fact, it may
Yes or no, look who you ask, we want all primes less than 1000. (In fact, our waiting
The selection 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. Initially, it contained only 1. We also have a variable called base. For Each loop, we delete the number that is its multiple (it is always the smallest number in the candidate list). After each cycle, we know that the smallest number remaining is prime (because we have deleted all the numbers that can be decomposed).

Therefore, we add it to result and set it to the new base and remove it from the list (so that it does not
It has been calculated repeatedly). When the candidate list is empty, the result list will contain all primes. Smart, huh!
Think about it: what's so special about the first cycle? At that time base was 2, but it was filtered as well. For what
Do you? Why doesn't this happen to other base values? If we are going to remove product, can we determine if it is in the candidate column
What about the table? Why?

What's next? Oh, yes...... Index. There are also slices. They are obtained from a list of Python
The method of the element. You've seen the normal indexing behavior. It's pretty simple. In fact, I have told you all
What you need to know about it, except one thing: A negative index is calculated forward from the end of the list. So
Somelist[-1] is the last element of Somelist, somelist[-2] is an element before it, followed by class
Push.

Slicing, still, is strange to you. It is similar to an index except that slices can get all the
element, not just a single element. How does this work? Like this:

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

# Prints "[' eggs ', ' sausages ']"

10. Continue abstraction-object and object-oriented programming

Now there is a more popular word called "Object-oriented Programming".

As the title of this paragraph implies, 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, it's going to surprise you, huh!) For example, if you write a fire leg
Process, we do not have to write many processes to deal with temperature, time, composition, etc., we can combine them into a fire
Leg object. Or maybe we can have the stove object and the clock object again ... So things like temperature become
A property of the Ham object, and time can be read from the clock object. To use our program to do certain things, we
Some methods that can be taught to us, such as the stove should know how to cook ham and so on.

So-how do we do it in Python? We cannot directly create an object. Cannot directly create a
Stove, instead of making a recipe to describe what the stove should be. So this recipe describes a piece of what we call
A class of objects for a stove. A very simple stove class might be this:

Class Oven:

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

def getspam (self):
Return Self.spam

It seems hard to understand, or what?

The new thing in this example ...

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

The name of the class usually starts with an uppercase letter, and the names of the functions and variables (as well as properties and methods) are lowercase
The mother begins.

Methods (that is, functions and actions that let an object know how to do it) are not specifically defined, but in the class's
Definition inside.

The first parameter of all objects should be called self (or something like ...). The reason was soon clear
The

The properties and methods of the object can be visited in this way: Myspam.temperature = 2 or Dilbert.be_nice
()。

I can guess something in the above example that you still don't know. For example, what is self? And now that we
With an object recipe (i.e., a class), how do we actually construct an object?

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

Myoven = Oven ()

Myoven contains a oven object, often called an instance of the oven class. Let's say we've got it all constructed.
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, often called self, always contains the object itself. (Clever, ha!) This way, 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 this algorithm:

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

12. Reference
[1] Holiday ham salad recipe excerpt from otter Ormel foods bad loving shadow justified like live?
Copyright nbsp; Magnus Lie Hetland must have come [translate]
  • Related Article

    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.