Python Full Novice Tutorial

Source: Internet
Author: User
Python Getting Started tutorial from:http://www.cnblogs.com/taowen/articles/11239.aspx Author: Taowen, Billrice
Lesson 1 ready to learn the environment of Python
The download address is:
www.python.org
I won't talk about the Linux version, because if you can use Linux and install it, you can do everything yourself.
The operating environment can be Linux or Windows:
1. Linux
Redhat Linux will have a Python (required component) after installation, enter the Python carriage return on the command line. This will allow you to enter a
>>> 's Prompt
2. Windows
After you have installed Python, you can find Python2.3->idle in the Start menu, and the run will enter a
window for >>> prompt
Start trying Python
1. Enter:
Welcome = "Hello!"
Enter
And then back to the >>>
2. Enter:
Print Welcome
Enter
Then you can see the greeting you entered yourself.
Lesson 2 Take care of the environment after the move
Python has an interactive command line, as you can see. So it can be more convenient to learn and try, without "new-archive-compile-debug", very suitable for a quick attempt.
Start at the beginning of the variable (in fact, the variable, more precisely the object, Python can be understood as an object).
Variable
Welcome = "Hello!"
Welcome is the variable name, the string is the type of the variable, hello! is the content of the variable, "" means that the variable is a string, "" In the middle is the contents of the string.
People who are familiar with other languages, especially those with compiled types, find it strange to declare that there are no variables. Using assignments in Python to represent a variable i want, even if you don't know what to put, just get a place to put your stuff, and write it like this:
store = ""
But this still means that the store is a string, because "" for the sake of.
Have a try
Tmp_storage = ""
Welcome = "Hello!"
Tmp_storage = Welcome
Print Tmp_storage
You'll find the same greeting come up.
String
The string is marked with "", but it's OK (don't say you don't see a double quote, one is a single quote), there is a tiny difference between the two, but you can ignore it. Actually, it's almost the same. Strings have a lot of their own operations, the most common is this:
Welcome = "Hello"
you = "world!"
Print Welcome+you
When you run it, you'll find out she's helloworld!.
More variables
There are several types of variables.
Number
String
List
Dictionary
File
Needless to do, these are very, very common. There's no need to talk about numbers:
RADIUS = 10
PI = 3.14
Area = pi*radius**2
Print "The area are", area
Next Lecture list and dictionary
Lesson 3 mathematical structure in Python
What do you learn most in math? I think that according to my little superficial experience (although I am a math department), the most learned is the collection, no matter what math books are starting from the collection. And then the function, and then the map must be again told again. It can be said that collections and mappings are the most basic structures in mathematics.
Python for the data structure is very smart built two, recall I write C program, often is the first to use a struct to spell a list out (repetitive work). Two data structures are available in Python, List and dictionary (dict). The prototypes of their respective counterparts are collections and mappings. You should understand this, just to show that the method is a little different.
List
The list is in the English name, so I'll take a name called
My_list = []
This creates an empty list. and assign it a value.
My_list = [up]
Print My_list
My_list.append (3)
Print My_list
Very easy to understand. Append adds a point to the front, which means 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 pull out a big paragraph.
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. Then fill in the contents:
contact={}
contact["name"]= "Taowen"
contact["Phone"]=68942443
Name is the word you look up when you look up the dictionary, and Taowen is what you find. But you're not looking, you're writing this dictionary. Add the same phone entry.
Now add, look at the contact content, how to view? Find a way to do it yourself ...
If you are savvy enough, you will find Python many operations are generic, since the ability to print 1, print "", print my_list, then the other data types of variables there is no reason not to use.
Combine 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 why I use two contact dictionaries?
Lesson 4 working with Python in different ways
So far, we have been using interactive command line to operate, but it is very convenient, right? However, the complexity of the situation is not so easy, to change the way to operate Python
In the Idle click file->new window and a new one appears (for Linux, you will use Vim or Emacs or Pico to write the source files of the text). For convenience, first click File-> Save, fill in the my_try.py. This allows the editor to know that in the edit Python source file, the code you entered will be processed in a little color.
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. Nor is it found in Python that the {} tag similar to C + + does not have a begin end in Pascal, and in fact the indentation is the markup method in Python that represents the subordination of a piece of code. The expression 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 the disk, just do it.
Play your ability to calculate all the even numbers from 1 to 10 and (hint, probably not as smart as you think).
Lesson 5 input and judgment in Python
A sound program generally requires the input function, so learn a simple input:
The input is to use the raw_input or input function, the difference is that raw_input directly returns your input as a string, and input converts the string to a numeric return on the basis of raw_input (What if you enter $@#$$?). Try it yourself). Let's 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, it's still a%. %s means to insert a string at this location,% means to "push" the arguments provided later into the preceding string, so the result of the push is to roll out the%s, and fill the your_name in that place. printf knows that 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 pass, after all, do not do anything. Break is jumping out of this while 1 (infinite loop, 1 is always true, while always executes). It's a wrap, 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, a bit too ahead of the point, but it is not a clear explanation. I won't explain it at all. Give us a little bit of interest.
---------
Let's just explain.
FROMT Tkinter Import *
is to introduce a module that is used to create a 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 the label in the main window
Root.mainloop () begins a loop that is waiting for you to enter the loop.
Lesson 7 python Basic grammatical elements align mobilization
The goal now is to try to figure out a comprehensive example of what is used only with built-in variable types and statements, and I think that's an example of the Contact table.
################
#呵呵, and forgot to say 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 contact 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 "". Then there is a very distinctive% operation that acts as a formatted string, preceded by only one%s in the string, and now has%d and%s two, respectively, representing the position where the decimal value and the string are inserted in the%x tag.
Then the list
Lists are sequential sequences that are appended with append and can be indexed by index values. So we can use a variable to hold the length of Len (contact_list) and then iterate through it, but here is another very handy way to do it. And it's worth noting that the parameters in append (), I used Contact.copy (), you can try to remove the copy (), observe the results you know how the so-called Append to do, Especially if you have feelings about pointers and stuff (but there's no concept of pointers in Python)
Look at the dictionary again.
A dictionary is an unordered sequence of keys (key) and values (value) that correspond together. So you have to specify the key (name or phone) when you save it, and it's the same when you take it.
Next is to judge
If is very useful, = = To determine whether two are equal, = the right side of the assignment to the left. And you can directly determine whether the string is equal, this is too convenient, if you have used strcpy (), you know. Elif is the meaning of the else if, if the if is not satisfied to determine whether the condition of elif is satisfied, and finally go to else.
A loop is a body
Both while and for are loops. But here while there is nothing to say, but also a classic while 1, the dead loop, and then must be in the inside with break to jump out. For is not the same as in C, the for in is a complete statement, referring to a sequence (such as a list) that can be taken from one value to another, and the value of one is assigned to the variable specified after the for, until it is empty and the loop ends. In fact, recall the general use of C for the experience, but also generally so. And you can also specify a range from how many to how much with a for I in range (1,100). It can be said that for in fully embodies the thoughtful and thoughtful python, it is intuitive to use, will not detours.
The next step is to run, so let's start debugging. Next time I might be talking about exception handling, because I think we should learn how to deal with exceptions before going into the various advanced features. 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 handle it.
Lesson 8 error detection in Python
What's the most important thing about writing a program? The complete feature is the most important. However, it is unavoidable to have the user input in the program, the errors that may occur in the middle of these write-time unpredictable factors are generally referred to as anomalies. For exception handling, different languages have different practices, such as checking the return value of a function, but that way of making the code into a group of pastes. Python is more advanced in this area, and we take a look at it from an example:
Print input ()
Oh, look at different. In fact, input is inputs, print is output. That is, the input of the thing immediately output. But this and
Print Raw_input ()
What's the difference?
The difference is that input () takes some processing after raw_input () receives the "string" input, for example, you are the input 1+2, then the output is 3, and raw_input is the output of the 1+2. In code, that means
Eval (raw_input ())
Eval is the value of an expression, and any simple Python expression, like 1+2, is fed as a string, and the value can be taken out of the eval process.
Now that you've experimented with "sdfsdf", you'll find that you're prompted
Reference:
Traceback (most recent):
File " ", Line 1, in-toplevel-
Input ()
File " ", line 0, in-toplevel-
nameerror:name ' sdfsdf ' are not defined
If you enter other outlandish strings and there may be other error hints, all we have to do now is Captures this error caused by user input. Do this:
Try:
Print input ()
except:
print ' There is a error in your input '
This way you don't have anything else to enter. Prompt, is the print statement you set as a hint. Now get rid of the combination of try except and go back to print input () and try it again:
1/0
This is obviously a mistake that was removed by 0. So specifically to catch this error:
Try:
Print input ()
except zerodivisionerror:
print ' Can not ' is divided by zero '
This allows you to catch the error that was removed by 0. Then you try another input, and the error may not be captured. So make up:
Try:
Print input ()
except zerodivisionerror:
print ' Can not ' is divided by zero '
Exc EPT:
print ' There is a error in your input '
Note that the except that catches all errors must be placed at the last of all except. I see? OK
There are more errors that can be captured, check the manual for yourself (for the time being the manual doesn't matter, take it slow). You will be able to raise (throw) an exception yourself later. However, it is a more advanced application, for error handling from the beginning to have this impression, and remember in the heart for the future to write a larger software is very good.
  • 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.