Python Complete Novice Tutorial _python

Source: Internet
Author: User
Tags data structures error handling exception handling in python
Python Getting Started tutorial from:http://www.cnblogs.com/taowen/articles/11239.aspx Author: Taowen, Billrice
Lesson 1 ready to learn the Python environment
The download address is:
www.python.org
Linux version of I will not say, because if you can use Linux and install a good description you can do everything yourself.
The operating environment can be Linux or Windows:
1, Linux
Redhat Linux must have a Python (required component) to be installed on it, and enter Python return at the command line. This will allow you to enter a
>>> prompt
2, Windows
After you've installed Python, find Python2.3->idle in the Start menu and run into a
>>> Prompt's window
Start trying Python
1, Input:
Welcome = "Hello!"
Enter
And then back to the >>>
2, Input:
Print Welcome
Enter
Then you can see your own type of greeting.
Lesson 2 after the environment to move forward
Python has an interactive command line that everyone has seen. So it can be more convenient to learn and try, do not "new-archive-compile-debug", very suitable for quick attempts.
Start with variables (in fact, variables, more accurately, objects, everything in Python can be understood as objects).
Variable
Welcome = "Hello!"
Welcome is the variable name, the string is the type of the variable, hello! is the content of the variable, "" means the variable is a string, "" The middle of the string is the content.
People who are familiar with other languages, especially the language of the compiled type, find it strange to say that there are no variables. The assignment in Python means that I want a variable, even if you don't know what to put in it, you just have to get a place to put your things, so write:
store = ""
But this still shows that the store is a string because of "".
Have a try
Tmp_storage = ""
Welcome = "Hello!"
Tmp_storage = Welcome
Print Tmp_storage
You'll find the same greeting coming up.
String
The string is marked with "", but it's OK (don't say you don't see a double quote, a single quote), there is a slight difference between the two, but you can ignore it. Actually, it's about the same. Strings have many of their own operations, the most commonly used is this:
Welcome = "Hello"
you = "world!"
Print Welcome+you
After running it will find that she has exported helloworld!.
More variables
There are several other types of variables.
Number
String
List
Dictionary
File
Needless to be, these are very, very common. There's no need to talk about numbers, that's:
RADIUS = 10
PI = 3.14
Area = pi*radius**2
Print "the??", Area
Next Talk list and dictionary
Lesson 3 The mathematical structure in Python
What do you learn most in maths? I think according to one of my shallow experiences (although I am a mathematics department), the most learned is the collection, no matter what the math books are starting from the collection. Then speak the function, and the mapping must be repeated again. It can be said that collection and mapping are the most basic structure in mathematics.
Python for the data structure is very sensible built-in two, recall my writing C program, is often the beginning is to use struct to spell a linked list (repetitive labor). There are two data structures for lists (list) and dictionaries (dict) in Python. Their respective prototypes are sets and mappings. This you should understand, just means that the method is a little different.
List
The English name of the list is lists, so I'll take a name called
My_list = []
This results in an empty list. and assign it a value.
My_list = [1,2]
Print My_list
My_list.append (3)
Print My_list
Very easy to understand. The append is preceded by a point, which means that the append is a my_list method. I really do not want to explain to you what is the object, what is the member method, and then pull out a large paragraph out.
The list can be indexed:
Print My_list[1]
But you may not understand why it is 2, not the 1. Because the index starts at 0, you want to output the first element:
Print My_list[0]
Dictionary
Contact = {}
This produces an empty dictionary, contact. and fill it with content:
contact={}
contact["name"]= "Taowen"
contact["Phone"]=68942443
Name is the word you look for when you look it up in the dictionary, and Taowen is what you find. But now you are not looking, but are writing this dictionary. Similarly added the phone this term.
Now add a good look at the content of the contact, how to view? Find a way to do it yourself ...
If you have enough savvy, you'll find that Python's operations are generic, and since you can print 1, print "", and print my_list, there's no reason why variables of other data types will not work.
Combining lists and dictionaries
Contact_list=[]
contact1={}
contact1[' name ']= ' Taowen '
contact1[' phone ']=68942443
Contact_list.append (Contact1)
contact2={}
contact2[' name ']= ' God '
contact2[' phone ']=44448888
Contact_list.append (CONTACT2)
Oh, it's complicated enough. Can you think of a reason why I should use two contact dictionaries?
Lesson 4 to manipulate python in different ways
So far, we have used interactive command lines to operate, but it is very convenient, right? However, the complexity of the situation is not so well, in a different way to manipulate the python
Click file->new window in the idle and a new window appears (for Linux, you'll have to use vim or Emacs or Pico to write the source file of the text). For convenience, first click file-> Save and fill in the my_try.py. This allows the editor to know that editing Python's source files will give you a little bit of color in the code you enter.
Fill in the following code:
i = 5
n = 0
While i>0:
n = n + i
i = I-1
Print n
You will find the input: After that, the indentation is automatically given. And there are no similar {} tags found in Python and the Begin end in Pascal, which is actually a markup method of the dependencies in Python that represent a piece of code. It means 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, you may be prompted not to save, just do it.
Use your ability to compute all even numbers from 1 to 10 (hints that may not be as smart as you might think).
Lesson 5 input and judgment in Python
A sound program is always required to enter the function, so to learn a simple input:
Input to use is the raw_input or input function, the difference is that raw_input directly to your input as a string return, and input is on the basis of Raw_input to convert the string to digital return (if you enter $@#$$ what to do?) Try it yourself). We use these two input functions to do some interesting things.
Your_Name = raw_input ("Please input your name:")
hint = "welcome! %s '% your_name
Print hint
It's not easy, there are%. %s represents inserting a string at this location, and% means to "push" the arguments provided later into the previous string, so the result of the push is to put the%s out and fill the your_name into that place. printf knows, 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"
Pass is passed, and after that, nothing is done. Break is to jump out of this while 1 (infinite loop, 1 is always true, while always executing). It's a line of change, not all of it.
Lesson 6 python Cabaret
Code: [Copy to Clipboard]
From Tkinter Import *
root = Tk ()
W = Label (Root, text= "Hello, world!")
W.pack ()
Root.mainloop ()
Oh, once too advanced a little, but also not explain unclear. I simply do not explain it. Give us a little more interest.
---------
Let's just explain.
FROMT tkinter Import *
is to introduce a module that is used to create the GUI (Graphic User Interface) window
Tk () creates a main window
Label () to create a label
The first parameter of the label is root, which indicates that the label is in the main window.
W.pack () refers to the default way to place a label in the main window
Root.mainloop () begins a loop that is waiting for your input loop.
Lesson 7 python Basic grammatical elements to mobilize
The goal now is to try to come up with a comprehensive example of something that is limited to built-in variable types and statements, and I think that's the case for that contact sheet.
################
#呵呵, and forgot to speak the notes
#第一个算是完整的程序
################
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 contacts in Contact_list:
Print "%d:name=%s"% (i, contact[' name '))
Print "%d:phone=%s"% (i, contact[' phone ')]
i = i + 1
The first is to recall the string
Strings can also be used with the "". Then there is a very distinctive% operation, which acts as a format string, preceded by only one%s in the string, and now has%d and%s two, representing the insertion of decimal values and the position of the string at the%x mark, respectively.
And then the list.
Lists are sequential sequences that are appended with append, and can also be indexed by index values. So we can use a variable to save Len (contact_list) of the length, and then iterate one by one, but here is another very convenient way to show. And note that the parameters in append (), I used the contact.copy (), you can try to remove the copy (), observe the results you know what the so-called append is done, Especially if you have a feeling for pointers and things like that (but there is no pointer in Python)
Look at the dictionary again.
A dictionary is an unordered sequence of keys (key) and a corresponding combination of values (value). So you have to specify the key (name or phone) when you save it, and the same is true when you take it.
The next step is to judge
If is very useful, = = To determine whether two are equal, = to the right of the assignment to the left. And can directly determine whether the string is equal, this is too convenient, if you have used strcpy (), you know. Elif is meant to indicate else if, if not satisfied, to determine whether the elif condition is satisfied, and finally to else.
A loop is a body
While and for are loops. But here there is nothing to say, but also a classic while 1, dead loop, and then must be inside with a break to jump out. For and C for is not the same, for in is a complete statement, refers to a single value from a sequence (such as a list), one of the fetch value assigned to the variable after the for, until the empty, loop end. In fact, recall the general use of C for the experience, but also generally so. You can also specify a range from how many to how much by using the for-I in range (1,100). You can say for-in fully embodies the thoughtfulness of Python, it is intuitive to use, not detours.
The next is running, everyone slowly debugging it. The next time it might be about exception handling, because I think it's important to learn how to deal with exceptions before you dive into the various advanced elements. The most common exception should be input (), and then the input you give is a string that cannot be converted to a number, so we're going to deal with it.
Lesson 8 error detection in Python
What is the most important thing to write a program? The completion function is most important. However, the program will inevitably have the user input, for these written when unpredictable factors may occur in the middle of the error, generally known as abnormal. For exception handling, different languages have different practices, such as checking the return value of the function, and so on, but that approach will make the code into a paste. Python is more advanced in this regard, and we take a look at it from an example:
Print input ()
Oh, look different. In fact input is inputs, print is output. Which is to output the input immediately. But this and
Print Raw_input ()
What difference does it have?
The difference is, input () will be Raw_input () received the "string" input after some processing, such as you are input 1+2, and then output is 3, and raw_input is the 1+2 output. The code representation is
Eval (raw_input ())
Eval is the value of an expression, and any simple Python expression, like 1+2, is sent as a string to fetch the value from the eval process.
Now that you've experimented with "sdfsdf," you'll find that you're 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 bizarre strings and there may be other error prompts, all we have to do now is to catch this error caused by user input. So to do:
Try
Print input ()
Except
print ' There is a error in your input '
No matter how you enter it will not have any other prompts, is your own set of print statements as a hint. Now remove the combination of try except and return to print input () and try again:
1/0
This is obviously a mistake, by 0 in addition to the error. So specifically to capture this error:
Try
Print input ()
Except Zerodivisionerror:
print ' Can not being divided by zero '
This allows you to catch errors that were removed by 0. Then you try another input, and the error may not be captured. So I'll fill in the following:
Try
Print input ()
Except Zerodivisionerror:
print ' Can not being divided by zero '
Except
print ' There is a error in your input '
Note that the except that captures all errors must be placed at the end of all except. I see? Ok
There are more to be able to catch the error, check the manual yourself (you can not see the manual is OK, take it slow). You can raise (throw) an exception later. However, that is a relatively advanced application, for error handling from the beginning of the impression, and remember that in the heart of the future to write a large number of software is good.

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.