Python tutorials

Source: Internet
Author: User


Python getting started FROM: http://www.cnblogs.com/taowen/articles/42539.aspxauthor :taowen, billrice
Lesson 1 prepare the Python learning environment
The download address is:
Www.python.org
I will not talk about the linux version, because if you can use linux and install it, you can do everything on your own.
The running environment can be linux or windows:
1. linux
After installing redhat linux, you must have python (required components). Enter python in the command line and press Enter. In this way, you can enter
>>> Prompt
2. windows
After python is installed, find Python2.3-> IDLE in the Start Menu.
>>> Prompt window
Start to try Python
1. input:
Welcome = "Hello! "
Enter
Then return to >>>
2. input:
Print welcome
Enter
Then you can see your input greetings.
Lesson 2's progress after the environment is ready
Python has an interactive command line. Therefore, it is easy to learn and try. You do not need to "Create-archive-compile-Debug", which is very suitable for quick attempts.
Start with the variable (in fact, the variable is more accurate than the object, which can be understood as an object in Python ).
Variable
Welcome = "hello! "
Welcome is the variable name, and string is the variable type. hello! Is the content of the variable. "" indicates that the variable is a string, and "" indicates that the content of the string is in the middle.
People who are familiar with other languages, especially compiling languages, feel that the declaration without variables is very strange. In python, a value assignment is used to indicate that I want such a variable. Even if you don't know what to put, you just need to get a place to put your stuff first:
Store = ""
However, this still indicates that store is a string because.
Have a try
Tmp_storage = ""
Welcome = "hello! "
Tmp_storage = welcome
Print tmp_storage
You will find the same greeting.
String
A string is marked with "", but ''can also be used (not to mention that one is double quotation marks or the other is single quotation marks). There is a slight difference between the two, but you can ignore it. In fact, it is similar. Strings have many operations of their own, the most common is this:
Welcome = "hello"
You = "world! "
Print welcome + you
After running the command, you will find that she has output helloworld !.
More Variables
There are several types of variables.
Quantity
String
List
Dictionary
File
Undoubtedly, these are very, very common. You don't need to talk about numbers. That is:
Radius = 10
Pi = 1, 3.14
Area = pi * radius ** 2
Print "the area is", area
Next lecture list and Dictionary
Lesson 3 mathematical structure in Python
What do you learn most in mathematics? Based on my little experience (although I am from the Mathematics Department), I want to learn the most about collections. No matter what kind of mathematics books, I want to start from the collections. Then, let's talk about the function again. It can be said that set and ing are the most basic structure in mathematics.
Python is wise to have two built-in data structures. In retrospect, the program I wrote C is often first to use struct to spell out a linked list (Repeat ). Python provides two data structures: list and dict. Their prototype is set and ing respectively. You should understand this, but the method is a little different.
List
The list English name is list, so I name it
My_list = []
This generates an empty list. Then assign a value to it.
My_list = [1, 2]
Print my_list
My_list.append (3)
Print my_list
It is easy to understand. A vertex is added before append, which indicates that append is the my_list method. I really don't want to explain to you what an object is, what a Member method is, and then let it go.
List can be indexed:
Print my_list [1]
However, you may not understand why it is 2, rather than 1. Because the index starts from 0, the first element must be output:
Print my_list [0]
Dictionary
Contact = {}
This generates an empty dictionary, contact. Then fill in the content:
Contact = {}
Contact ["name"] = "taowen"
Contact ["phone"] = 68942443
Name is the word you want to search for when you look up the dictionary, and taowen is the content you find. However, you are writing this dictionary instead of querying it. Similarly, the phone entry is added.
Now, I have added the contact information. How can I view it? Find a solution...
If you are savvy enough, you will find that many python operations are common. Since we can print 1, print "", print my_list, there is no reason not to use other data-type variables.
Combined list and Dictionary
Contact_list = []
Contact1 = {}
Contact1 ['name'] = 'taowen'
Contact1 ['phone'] = 68942443
Contact_list.append (contact1)
Contact2 = {}
Contact2 ['name'] = 'God'
Contact2 ['phone'] = 44448888
Contact_list.append (contact2)
It's complicated. Why do you want to use two contact dictionaries ?...
Lesson 4 uses different methods to operate Python
So far, we have used interactive command lines for operations, but they are very convenient, right? However, in some complicated cases, it is not so easy to operate Python in another way.
In IDLE, click File-> New Window to display a New Window (for linux, you must use vim, emacs, or pico to write the source File of the text ). For convenience, first click File-> Save and fill in my_try.py. This allows the editor to know that the source file of python is being edited, and the code you entered will be colored a bit.
Enter the following code:
I = 5
N = 0
While I> 0:
N = n + I
I = I-1
Print n
You will find that after entering:, it will automatically indent. In addition, the {} mark similar to C/C ++ is not found in python, nor is it the pascal in end in pascal ;, in fact, indentation is the Tag Method in python that represents the subordination of a piece of code. N = n + 1 and I = I-1 are both while. The running logic of the program should not be explained. Is the result of running 5 + 4 + 3 + 2 + 1.
Run code
Press F5 and you may be prompted that you have not saved the disk. Just do it.
Use your abilities to calculate the sum of all the even numbers from 1 to 10 (as prompted, it may not be as intelligent as you think ).
Lesson 5 input and judgment in Python
A sound program requires input functions, so you need to learn a simple input:
The raw_input or input function is used for input. The difference is that raw_input directly returns your input as a string, input converts a string to a number based on raw_input. (what if you enter $ @#$ $? Try it yourself ). We can use these two input functions to do something interesting.
Your_name = raw_input ("please input your name :")
Hint = "welcome! % S "% your_name
Print hint
It's not easy. % is there. % S indicates that a string is inserted at this position. % indicates that the parameter provided later is pushed to the previous string. Therefore, % s is pushed out, enter your_name in that place. The printf in C is the same.
Inputed_num = 0
While 1:
Inputed_num = input ("input a number between 1 and 10 ")
If inputed_num> = 10:
Pass
Elif inputed_num <1:
Pass
Else:
Break
Print "hehe, don't follow, won't out"
The pass is the pass. After that, you can do nothing. Break jumps out of this while 1 (infinite loop, 1 is always true, while is always executed ). It's a line feed. You won't forget it all.
Lesson 6 Python Yuxing Program
Code: [copy to clipboard]
From Tkinter import *
Root = Tk ()
W = Label (root, text = "Hello, world! ")
W. pack ()
Root. mainloop ()
Haha, it was a little too advanced, but it was not clear. I just don't want to explain it. Increase your interest.
---------
Let's explain it.
Fromt Tkinter import *
Is to introduce a module, this module is used to create a GUI (Graphic User Interface) window
Tk () creates a main window.
Label () to create a Label
The first parameter of Label is root, indicating that Label is in the main window.
W. pack () means to place the Label in the main window by default.
Root. mainloop () starts a loop that waits for your input.
Lesson 7 integrate the basic syntax elements of Python
The purpose is to try to come up with a comprehensive example of built-in variable types and statements. I 'd like to give an example of the contact table.
################
# Haha, I forgot to comment.
# The first is a complete program
################
Contact = {}
Contact_list = []
While 1:
Contact ['name'] = raw_input ("please input name :")
Contact ['phone '] = raw_input ("please input phone number :")
Contact_list.append (contact. copy ())
Go_on = raw_input ("continue? ")
If go_on = "yes ":
Pass
Elif go_on = "no ":
Break
Else:
Print "you didn't say no"
I = 1
For contact in contact_list:
Print "% d: name = % s" % (I, contact ['name'])
Print "% d: phone = % s" % (I, contact ['phone'])
I = I + 1
First, recall the string.
The string can use both "" And ''. Then there is a very special % operation, which serves to format the string. There is only one % s in the string before, and there are now two % d and % s, insert the decimal value and string at the position marked by % x.
Then the list
A column table is a sequence that is appended with an append. You can also create an index value. Therefore, we can use a variable to save the length of len (contact_list) and traverse each item. However, this shows another very convenient method. It is also worth noting that the parameters in append () use the contact. copy (), you can try to remove copy (), and observe the results, you will know how the so-called append is done, especially if you are very familiar with pointer and other things (but there is no pointer in Python)
Let's look at the dictionary.
A dictionary is an unordered sequence of keys and values. So you need to specify the key (name or phone) when saving it, and the same is true when getting it.
Next we will judge
If is very useful, = indicates to judge whether two are equal, = indicates to assign the right to the left. In addition, you can directly determine whether the strings are equal. This is too convenient. If you have used strcpy (), you will know. Elif indicates the meaning of else if. if it does not meet the conditions, it determines whether the conditions of elif are met, and finally goes to else.
Loop is a subject
While and for are both loops. However, here while is nothing to say, it is also a classic while 1, an endless loop, and then you must use break to jump out. For is different from for in C. for in is a complete statement, which refers to a sequence (such as list) that can take values one by one ), the retrieved values are assigned to the variable specified after for, until the value is null and the loop ends. In fact, the general experience of C for is also similar. You can also use for I in range (1,100) to specify the number to which a range ranges. It can be said that for in fully embodies the considerate and thoughtful python, It is very intuitive to use, and it will not bend around.
The next step is to run it. Let's debug it slowly. Next time, it may be about exception handling, because I think we should learn how to handle exceptions before going deep into the use of various advanced elements. The most common exception should be input (), and the input you give is a string that cannot be converted to a number, so we have to deal with it.
Lesson 8 Error Detection in Python
What is the most important thing to write a program? It is most important to complete the function. However, user input is inevitable in the program. errors that may occur among unknown factors during writing are generally called exceptions. For Exception Handling, different languages have different practices, such as checking the return values of functions, but that method will make the Code a mess. Python is relatively advanced in this aspect. Let's look at it from an example:
Print input ()
Well, let's see it. In fact, input is input, and print is output. That is to say, output the input items immediately. But this and
Print raw_input ()
What is the difference?
The difference is that input () performs some processing after raw_input () receives the "string" input. For example, if you input 1 + 2 and then output 3, raw_input is the output of 1 + 2 of the original version. In code
Eval (raw_input ())
Eval is the value of the expression. Any simple python expression, such as 1 + 2, is sent as a string, and the value can be obtained after eval processing.
Now, after you experiment with "sdfsdf", you will find that you are prompted
Reference:
Traceback (most recent call last ):
File "<pyshell #4>", line 1, in-toplevel-
Input ()
File "<string>", line 0, in-toplevel-
NameError: name 'sdfsdf 'is not defined
If you enter other strange strings and other error prompts, We need to capture such errors caused by user input. In this way:
Try:
Print input ()
Except t:
Print 'there is an error in your input'
No matter how you enter it, there will be no other prompts, that is, the print statement you set as the prompt. Remove the try again t combination and return to print input (). try again:
1/0
This is obviously an error with zero division. Here, we will capture this error:
Try:
Print input ()
Except t ZeroDivisionError:
Print 'can not be divided by 0'
Now you can catch the error of division by zero. Then you try other input, and the error may not be captured. So add the following:
Try:
Print input ()
Except t ZeroDivisionError:
Print 'can not be divided by 0'
Except t:
Print 'there is an error in your input'
Note: The catch of all error counter T must be placed at the last of all counter T. Understand? OK
There are more mistakes that can be captured. Check the manual ). In the future, you will be able to raise your own raise exceptions. However, they are all relatively advanced applications. They have the impression of error handling from the very beginning, and keep in mind that it will be good for writing larger software in the future.
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.

Tags Index: