A good Python getting started tutorial

Source: Internet
Author: User
Tags mathematical functions sodium python list

OriginalHttp://www.hetland.org/python/instant-hacking.php

Instant Hacking [translation]

Translator: Yes

This is a short getting started tutorial on the python programming language. The original Article is here, translated from the dictionary!

This is a brief introduction to the art of programming. The example is written in python. (If you already know how to program python, but want to know Python briefly, you can refer to my other article Instant python .) This article has been translated into many languages, including Italy, Poland, Japan, Serbia, and the Brazilian grape language, and is being translated into Korean. (TRANSLATOR: Of course, the Chinese version has been included, but the author does not know it .)

This article has nothing to do with how to break into other people's computer systems. I don't pay attention to such things, so please don't ask me those things by email.

Note: To make the examples in this article run correctly, you should write them in a text file and run them with the interpreter; do not try to run them directly in interactive mode-not all of them can run like this. (Do not ask me the specific details related to this. It is best to check the python documentation or e-mail the help@python.org ).

1. Runtime 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 can be found on the python website. You should also have a text editor (such as emacs, notepad, or something similar ).

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 are like recipes in some ways that guide us in cooking. For example, [1]:

Holiday ham salad

Raw materials:

Pickled juice:
1/4 cup of Sour orange juice
1/4 cup low-sodium soy sauce
1/4 glasses of water
1 tbsp Vegetable Oil
3/4 teaspoon fennel
1/2 teaspoon niuzhi
1/4 teaspoon hot pepper
2 slices of cloves, garlic, mashed

Salad:
1 (12 ounces) canned sodium-less luncheon meat ham cut into strips
1 onion, sliced
Pepper, chopped lettuce
Cut 12 cherry tomatoes in half

Method:

Shake the pickled juice in a wide-mouth bottle with a proper lid. Put ham in a plastic bag, pour the pickled juice on it, and seal the mouth of the bag. Marinate in the refrigerator for 30 minutes. Extract ham from a plastic bag; prepare 2 tablespoons of pickled juice and cook it in a boiling pot. Add ham, onion, and green pepper. Cook for 3 to 4 minutes until the ham is cooked ......

Of course, no computer will understand this ...... Even if you understand it, most computers cannot cook a salad. So how can we make these more friendly to computers? Fundamentally speaking, it depends on two points: first, we must communicate with it in a computer-understandable way, and second, we need to talk to it about what it can do.

The first point means that we must use a language-a programming language for which an interpreter has been prepared, the second point means that we cannot expect a computer to make a salad for us-but we can make it accumulate numbers or print things on the screen.

3. Hello ......

There is a tradition in the Programming Tutorial, which usually prints "Hello, world!" on the screen !" This program starts. For python, this is very simple:

print "Hello, world!"

It is basically like the recipe above (although much shorter !). It tells the computer what to do: Print "Hello, world !". How can I print more nonsense? Simple:

print "Hello, world!"
print "Goodbye, world!"

Not as difficult as the previous one, right? But not very interesting ...... We hope it can process more elements, just like salad recipes. So what elements do we have? First, there are strings like "Hello, world !", There are also numbers. Suppose we want the computer to calculate the area of the rectangle for us. We can give it the following recipe:

# 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 (although slightly different ). But how does it work? First, the line starting with # is called a comment, which will be ignored by the computer. However, inserting comments like this is important to enhance the readability of your program.

Next, a row like foo = bar is called a value assignment. In the case of width = 20, it is to tell the computer that width is 20 from here. It also means that a variable named "width" has been created since then (if it already exists, it will be overwritten again ). Therefore, when we use this variable later, the computer will know its value. Therefore,

Width * height

Essentially the same

20*30

Calculate the result of 600 and assign it to the variable named "area. The last sentence of the program prints the value of the variable "area" on the screen, so the final result of the program running is only

600

Note: In some programming languages, you must tell the computer at the beginning of the program what variables you will use (like the elements in the salad)-And python is smart enough, therefore, you can create them at any time as needed.

4. Feedback

Now, you can perform some simple or more complex calculations. For example, you may want to write a program to calculate the area of the circle instead of the rectangle:


radius = 30

print radius * radius * 3.14

However, this is actually not more interesting than the program that calculates the rectangle area. At least in my opinion. It is stiff. What if we see a circle with a radius of 31? How to let the computer know? It's a bit like the salad recipe: "it's three to four minutes until the ham is cooked ." To know when to cook, we must check. We need feedback or prompt. How does the computer know the radius of our circle? You also need to enter materials ...... What we can do is tell the computer's radius:


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

Now the program has become more beautiful ...... Input is a function. (Soon you will learn how to create your own functions. Input is a python built-in function .) Write down

Input

Nothing to do ...... You must put a pair of parentheses behind it. So input () can work-it simply requires the length of the input radius. The version above may be more user-friendly, because it first prints out a problem. When we send a question string such as "What is the radius ?" When something like this is placed in the brackets of the function call, this process is called the parameter transfer of the function. The content in the brackets is called a parameter. In the previous example, we passed a question as a parameter so that the input can know what to print before obtaining the answer.

But how does the obtained answer reach the radius variable? Function input. A value (like many other functions) is returned during the call ). You don't have to use this value, but in this case, we need to use it. In this way, the following two expressions are quite different:


foo = input
bar = input()

Foo now contains the input function itself (so it can actually be like foo ("What is your age? ") Used in this way; this is called a dynamic function call) and bar contains the user-typed value.


5. Process

Now we can write a program to execute simple tasks (operations and printing) and get user input. This is useful, but it is still limited to executing commands in order, that is, they must be executed in a pre-arranged order. Most ham salad recipes are described in sequence or in linear form. But how can we tell the computer to check if the salad is burned? If it is burned, it should be taken out from 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 program. It can be executed in two directions-either take the ham off or keep it in the oven. We can choose whether or not it is installed. This is called conditional execution. We can write as follows:


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."

Obviously: If the temperature exceeds 50 (degree Celsius), print out the information to tell the user to burn it. Otherwise, tell the user to burn it for a while.

Note: indentation is important in python. The statement block in condition execution (and loop execution and function definition-see the following) must be indented (and the number of spaces must be indented; a key is equivalent to 8 spaces) so that the interpreter can know where they start and where they end. This also makes the program more readable.

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


# 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 is ", area
else:
radius = input("Please enter the radius: ")
area = 3.14 * (radius**2)
print "The area is ", area

New things in this example:
1. Only print itself will print a blank line
2. = check whether the two values are equal. Different from =, the latter assigns the value on the right of the expression to the variable on the left. This is a very important difference!
3. ** is the power operator of python-therefore, the square of the radius is written as radius ** 2
4. print can print more than one thing. You only need to use commas to separate them. (They are separated by a single space in the output .)

This program is simple: it requires a number to tell it the user wants to calculate the area of a rectangle or circle. Then, an if Statement (conditional execution) is used to determine which statement block should be executed to calculate the area. These two statement blocks are essentially the same as the statement Blocks Used in the previous area calculation example. Pay attention to how annotations make the code more readable. The first rule of programming is: "You should comment !" Whatever it is, it is a good habit.

Exercise 1:

Expand the above program to include the calculation of the square area. You only need to enter the length of one side of the square area. Before doing this exercise, you need to know one thing: if you have more than two options, you can write like this:


if foo == 1:
# Do something...
elif foo == 2:
# Do something else...
elif foo == 3:
# If all else fails...

Here, elif refers to the mysterious code of "else if :). So, if foo is equal to 1, do something; otherwise, if foo is equal to 2, do other things, and so on. You can also add other options in the program-like triangles and arbitrary polygon. Follow your needs.

6. Loop

Sequential execution and conditional execution are only two of the three basic statement block architectures of program design. The third is loop execution. In the previous section, I assumed a situation where I checked whether the ham was burned, but obviously it was not applicable. What if the ham is not burned during the next check? How do we know how many times to check? In fact, we don't know. And we do not need to know. We can ask the computer to continue the check until it is ready. How to express this? As you guessed, we use a loop or repeated execution.

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


for food in "spam", "eggs", "tomatoes":
print "I love", food

It means that for each element in the "spam", "eggs", "tomatoes" list, it is printed out that you like it. The statement block in the loop is executed once for each element, and the current element is assigned to the variable food (in this example ). Another example:


for number in range(1, 100):
print "Hello, world!"
print "Just", 100 - number, "more to go..."

print "Hello, world"
print "That was the last one... Phew!"

The range function returns a list of numbers in a given range (including the first number, excluding the last number ...... In this example, [1 ...... 99]). So, explain it as follows:

The number between the cycle body 1 (inclusive) and 100 (excluded) is executed once each time. (Which is the loop body and the subsequent expressions actually do what is left for exercise .)

However, this does not actually help us with cooking. If we want to check the ham for one hundred times, this is a good solution; but we don't know if it is enough-or too many. We just want it to be continuously checked when the temperature does not reach (or until it is hot enough-roughly in a certain state. Therefore, we use the 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 is, 3*60 seconds)...
sleep(180)

print "I'm baaack :)"

# How hot is 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 is it now?")

print "It's hot enough - You're done!"

New things 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 of python (the number of seconds it takes to commit ). (It is also possible to create your own module ......)

Exercise 2:

Write a program that continues to get data from the user and then add it together until their sum is 100. Write another program, get 100 data from the user, and print out their sum.

Bigger Programs-Modify action

If you want to know the general content of a book, you won't go through all the pages-you just look at the directory, right? It lists the main contents of a book. Now -- imagine writing a recipe. Many recipes, such as "cream ham macaroni" and "Swiss ham pie", may include the same things, such as ham, in this case-You certainly won't plan to repeat how to make ham in each recipe. (Okay ...... You may not actually do it ...... But for example, Please endure it :)). You will put the recipe for making ham in a separate chapter, instead of referencing it in other chapters. In this case, instead of the complete description in each recipe, you only need to reference the chapter name. In computer programming, this is called abstraction.

Have we 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 this ...... Similarly ...... We are not really doing ham :)) but simply using input-a function instead. In fact, we can construct our own functions to apply them to this type of abstraction.

Suppose we want to find the maximum 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)" for a given number )". (In fact, this can be handled using the python built-in function int. However, please bear it for another example ......) What should we do? A simple solution is to try 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 the cycle ends when the floor is no longer smaller than or equal to the given number; we add too much 1 to it. Therefore, we must subtract 1 from it. What if we want to apply it to a complete mathematical operation? We have to write a complete loop to calculate the base ("floor"-ing) of each number. This is uncomfortable ...... You may have guessed what we replaced: Put it in our own function and name it "floor ":


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

New things in this example ......

1. The function is defined by the keyword def. The function name is immediately followed by brackets to enclose the required parameters.
2. if the function is required to return a value, use the return keyword for processing (It also automatically ends the function definition ).

After defining a function, we can use it as follows:


x = 2.7
y = floor(2.7)

After execution, the value of y should be 2. It is also possible to define a function with multiple parameters:

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

Exercise 3

Write a function and use the Euclidean method to find a common factor of two numbers. The process is as follows:

1. Assume that two numbers, a and B, and a are greater than B.
2. Repeat the following steps until B changes to 0:
1. The value of a to B
2. B changes to a before the value is changed divided by the remainder of B before the value is not changed
3. Return the last value of.

Tip:

* Use a and B as function parameters
* Simply set a to be greater than B
* The remainder of x divided by z is calculated using the expression x % z.
* Two variables can be assigned together as follows: x, y = y, y + 1. Here, x is assigned with the value y (which means that the value of y has been previously specified) and y is incremented by 1.

7. In-depth Functions

How to do the above exercises? Hard? Not quite clear about functions? Don't worry -- I haven't finished my topic yet.

The extraction method we use when building a function is called process abstraction. Many programming languages use the keyword process like the function. In fact, these two concepts are different, but in python they are all called functions (because they are more or less defined and used in the same way ).

What is the difference between a function and a process (in other languages? Well -- as you can see in the previous section, a function can return a value. The difference is that the process does not return such a value. In many cases, it is useful to divide a function into two types: return value and no return value.

Functions (procedures) that do not return values can be used as subprograms or routines. We call these functions to make some raw materials, such as foam fresh milk. We can use this function in many places without the need to rewrite its code (this is called code reuse-you will know later that it is not just here ).

Another usefulness of such a function (or process) is embodied in-It changes the environment (for example, mixing sugar and cream together, and their entire external state changes) let's take an example:


def hello(who):
print "Hello, ", who

hello("world")
# Prints out "Hello, world"

Printing out content is one of its functions, because this is the only thing that this function needs to do. It is actually a typical so-called process. But ...... In fact, it does not change its runtime environment, does it? How can it be changed? Let's try:


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

def setAge(a):
age = a

setAge(100)
print age
# Prints "0"

Where is the error? If the setAge function creates its own local variable named "age", it is only available within 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 are easy to cause bad code organization structures, known as pasta code. I use them here to lead to more complex technical problems-if you can try to avoid using them.

[Color = # FF0000... [/Color]

Rockety replied to: 09:27:59

[Color = red] After the translation is complete, I am not careful. I didn't paste all the information on my blog, and I didn't show indentation. : Oops: corrected both today. Thanks to wolfg for posting and correct indentation. [/Color]

By telling the interpreter that a variable is global (using an expression like global age), we actually
Instead of re-creating a local variable, the variable is used outside the function. (So, and local
On the contrary, it is global .) Therefore, the above program can be rewritten as follows:


# The correct, but not-so-good way of doing it
age=0

def setAge(a):
global age

setAge(100)
print age

# Prints "100"

After learning about the object (mentioned later), you will find that the better way to solve this problem is to use
And setAge method. In the data structure section, you will also find that some functions change its environment better.
Example.
Okay -- what is the real function? What is a function, in fact? Mathematical functions are like machines.
To obtain the input and then calculate the result. It returns the same result each time, if the same input is provided each time.
For example:


def square(x):
return x*x

This is the same as the mathematical function f (x) = x * x. Its behavior is like a precise function, only dependent on its input.
And does not change its environment under any circumstances.

So -- Here I describe two constructor Methods: A type is more like a process and no knot is returned.
Result; the other is more like a mathematical function. (almost) nothing is done to return a result. Of course, in
It is possible to do something between these two extreme things, although when a function changes things, it should be clear that it changes
Changed. You can distinguish them by marking their names. For example, for "pure" functions
For a function like a process, use an imperative name like setAge.

9. More types-Data Structure

Now you know a lot: How to input and output, how to design complex arithmetic rules (programs) to implement
But it is still behind the scenes.

So far, what components have we used in the program? Numbers and strings, right? Boring
Class ...... Now let's introduce two or three other ingredients to make things more interesting.

A Data Structure is a component that organizes data. (Surprised, surprised ......) There is no real data for a single piece of data.
Structure, right? But suppose we need to put a lot of data together as a component-then we need a structure.
For example, we may want a data list. It's easy:

[3, 6, 78, 93]

In the loop section, I mentioned the list but did not really describe it. Okay -- this is how you create it. Only
You need to list the elements separated by commas (,) and add the brackets above.

Let's look at an example of calculating a prime number (which can only be divided by 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

New things in this example ......

The built-in function range actually returns a list, which can be used as all other lists. (It includes
A number, but not the last one .)

The list can be used as a logical variable. If it is not empty, it is true; otherwise, it is false. Therefore, while
Candidates indicates "when the while name is the list of candidates, which is not empty" or simply "while storage
In candidates ".

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

You can use someList. remove (someElement) to delete someElement in someList.

You can use someList. append (something) to add elements to a list. In fact, you can also
Use "+" (like someList = someList + [something]). However, the efficiency is not too high.

You can add a number enclosed in parentheses after the list name to indicate the position of an element (strange, column
The first element in the table, with the position 0) to obtain an element in the list. Therefore, someList [3] Is someList.
The fourth element of the list (and so on ).

You can use the keyword del to delete a variable. It can also be used to delete elements in the list (just like here ).
Therefore, del someList [0] deletes the first element in the someList list. If the list 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 (similar to this ). It considers 1
Series given numbers (in this example, a list), and then organized to delete numbers known as not prime numbers. How to know
? You just need to see if they can be divided into two other numbers.

We start with a candidate list containing numbers [2... 999] -- we know that 1 is a prime number (in fact, it may
Yes or not. Check who you asked.) We want to get all prime numbers smaller than 1000. (In fact, we are waiting
The list is [3... 999], but 2 is also a candidate number because it is our first base ). We also have a list named result, which contains the latest results at any time. Initially, it only contains 1. We also have a variable named base. Every cycle, we delete the number that is a multiple of it (it is always the smallest number in the candidate list ). After each loop, we know that the smallest number remaining is the prime number (because we have deleted all the numbers that can be decomposed ).

Therefore, we add it to the result, set it to the new base, and then remove it from the list (this will not
). If the candidate list is empty, the result list contains all prime numbers. Exquisite, ha!
Think: what's special about the first cycle? At that time, base was 2, but it was also filtered. Why
? Why doesn't this happen to other base values? Can we determine whether it is in the Candidate column when we intend to remove the product?
What about tables? Why?

What is next? Oh, yes ...... Index. There are also slices. They are obtained from the python list
Element Method. You have seen Common indexing behaviors. It is quite simple. Actually, I already told you all
One thing you need to know about it is that 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 someList.
Push.

Slice, still, is unfamiliar to you. It is similar to the index, except that slice can obtain all
Element, not just a single element. How can this be done? 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 popular term called "Object-Oriented Programming ".

As the title implies, object-oriented programming is just another way to abstract details. Program passed
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 will surprise you, haha !) For example
We don't need to write a lot of processes to process temperature, time, ingredients, etc. We can combine them into a fire
Leg object. Or, maybe we can have another stove object and clock object ...... Then, things like temperature become
A ham object attribute, and time can be read from the clock object. To use our program to do something, we
Some methods can be taught to objects, for example, the stove should know how to cook ham.

So -- what should we do in python? We cannot directly create an object. You cannot directly create
Instead, make a recipe to describe the stove. This recipe describes what we call
A Class Object of the furnace. A very simple stove class may be like this:


class Oven:

def insertSpam(self, spam):
self.spam = spam

def getSpam(self):
return self.spam

It seems hard to understand. What should I do?

New things in this example ......

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

The class name usually starts with an uppercase letter, while the names of functions and variables (as well as attributes and methods) are written in small form.
Start with the parent.

The definition of methods (that is, to let objects know how to do functions and operations) is not special, but in
Definition.

The first parameter that all object methods should have is self (or similar ......) The reason is clear soon.
.

The properties and methods of the object can be accessed as follows: mySpam. temperature = 2 or dilbert. be_nice
().

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

Let's reverse the order first. The object is created by referencing the class name like a function reference:


myOven = Oven()

MyOven contains an Oven object, usually called an instance of the Oven class. Suppose we have constructed
A Spam class, we can do this as follows:


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 parameter, usually called self, always contains the object itself. (Clever, haha !) In this way, the row self. spam = spam sets the spam attribute value of the current Oven object as the parameter spam. Note that they are two different things, even though they are called spam in this example.

11. Exercise 3 answer

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 recipes are excerpted from marketing ormel Foods, which is a bad movie?
Copyright? Nbsp; Magnus Lie Hetland must have been here.

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.