Python learning-simple Python tutorial

Source: Internet
Author: User
Tags natural string
ArticleDirectory
    • Self = Java's this

Why use python? The development efficiency is high and can be transplanted.

Syntax:

String:

1,Use single quotation marks (') = use double quotation marks (") = Java double quotation marks (")

2. Use three quotation marks (''' or ") to merge multiple rows.

3. Escape, similar to '\' in Java. Note (in a string, a separate backslash at the end of the line indicates that the string continues in the next line, rather than starting a new line .)

4. A natural string is prefixed by adding a character stringROrR.

5. the string is variable, similar to Java.

6. the string is cascaded literally.

Variable: (similar to Java)

Object: everything in python is an object.

It is strongly recommended that:PersistenceWrite only one logical row in each physical row

Python requires strict indentation

Operator: similar to Java.

Process control:

If:

IfGuess = Number:
Print'Congratulations, you guessed it .'# New block starts here
Print"(But you do not win any prizes !) "# New block ends here
ElifGuess <Number:
Print'No, it is a little her than that'# Another block
# You can do whatever you want in a block...
Else:
Print'No, it is a little lower than that'
# You must have guess> number to reach here

While:

WhileRunning:
Guess =Int(Raw_input('Enter an integer :'))

For:

ForIInRange(1,5):
PrintI

Break:

BreakThe statement is usedTerminationLoop statement, that is, even if the loop condition is not calledFalseOr the sequence has not been completely recursive, and the execution of loop statements is also stopped.

An important note is that if youForOrWhileCirculatingTermination, Any corresponding LoopElseBlockNoRun.

Continue:

ContinueThe statement is used to tell python to skip the remaining statements in the current loop block, and thenContinueFor the next round.

 

Function:

#! /Usr/bin/Python
# Filename: func_doc.py

DefPrintmax(X, y ):
'''Prints the maximum of two numbers.
The two values must be integers .'''

X =Int(X)# Convert to integers, if possible
Y =Int(Y)
IfX> Y:
PrintX,'Is maximum'
Else:
PrintY,'Is maximum'
Printmax (3,5)
PrintPrintmax. _ Doc __

Module:

Import _ name __= = '_ main _' indicates the masterProgram

You can use the built-inDirFunction to list the identifier defined by the module. Identifiers include functions, classes, and variables.

 

Data structure:

Array: zoo = ('Wolf','Elephant','Penguin'), Zoo [1], zoo [0]

Map: note that you can only use immutable objects (such as strings) as Dictionary keys, but you can use immutable or variable objects as Dictionary values. Basically, you should only use simple objects as keys.

AB = {'Swaroop':'Swaroopch @ byteofpython.info',
'Larry':'Larry @ wall.org',
'Matsumoto':'Matz @ ruby-lang.org',
'Spammer':'Spammer @ hotmail.com'
}

AB ['Larry '], Len (AB)

List:

Shoplist = ['Apple','Mango','Carrot','Bana']

Shoplist. Sort (),Shoplist. append ('Rice')

ListAndArrayVery similar,ArrayLike a stringImmutableYou cannot modifyArray.

Sequences: Lists, arrays, and strings are all sequences. But what are sequences? Why are they so special? The two main features of the sequence are:IndexOperator andSliceOperator. The index operator allows us to capture a specific item from the sequence. The Slice operator allows us to obtain a slice of a sequence, that is, a part of the sequence.

Shoplist [1:3],Shoplist [2:], Shoplist [:],Shoplist [-1],Shoplist [0.

When you create an object and assign it a variable, this variable is onlyReferenceThe object instead of the object itself!

Object-oriented:

Self = Java's this

_ Init __Method: similar to Java Constructor

_ Del __: called when the object disappears. Java finalizne

Class variablesShared by all objects (instances) of a class. Only one class variable is copied, so when an object changes the class variable, this change will be reflected on all other instances.

Object VariablesIt is owned by each object/instance of the class. Therefore, each object has its own copy of this domain, that is, they are not shared. In different instances of the same class, although the object variables have the same name, however, they are unrelated. This is easy to understand through an example.

All class members (including data members) in Python arePublic, All methods areValid.
Only one exception: if the data member name you use usesDouble underline prefixFor example_ PrivatevarThe name Management System of Python effectively uses it as a private variable.
In this way, there is a convention that if a variable only needs to be used in a class or object, it should be prefixed with a single underscore. Other names are public and can be used by other classes/objects. Remember that this is just a convention and is not required by Python (different from the double-underline prefix ).
Similarly, note that_ Del __Method andDestructorThe concept is similar.

Inheritance:

ClassTeacher(Schoolmember ):
'''Represents a teacher .'''
Def_ Init __(Self, name, age, salary ):
Schoolmember. _ init _ (self, name, age)
Self. Salary = salary

Print'(Initialized Teacher: % s )'% Self. Name
DefTell(Self ):
Schoolmember. Tell (Self)

Print'Salary: "% d "'% Self. Salary

Input and Output:

File:

You can createFileClass Object to open a file, respectively useFileClassRead,ReadlineOrWriteMethod To properly read and write files. The ability to read and write files depends on the mode specified when you open the file. Finally, when you complete file operations, you callCloseMethod To tell Python that we have used the file.

F =File('Poem.txt','W')# Open for 'W' riting
F. Write (POEM)# Write text to file
F. Close ()# Close the file

Memory:

Python provides a standard module calledPickle. You can store it in a file.AnyPython object, and then you can obtain it completely. This is calledPermanent locationStorage objects.

ImportCpickleAs P
# Import pickle as P

Shoplist = ['Apple','Mango','Carrot']
# Write to the file
F =File(Shoplistfile,'W')
P. Dump (shoplist, F)
# Dump the object to a file
F. Close ()

# Read back from the storage

F =File(Shoplistfile)
Storedlist = P. Load (f)

Exception:

Class Shortinputexception (Exception ):
'''A user-defined exception class .'''
Def _ Init __ (Self, length, atleast ):
Exception. _ init _ (Self)
Self. Length = Length
Self. Atleast = atleast

Try :
S =
Raw_input ( 'Enter something -->' )
If Len (S) < 3 :
Raise shortinputexception (
Len (S ), 3 )
# Other work can continue as usual here
Except Eoferror:
Print '\ Nwhy did you do an EOF on me? '
Except Shortinputexception, X:
Print 'Shortinputexception: the input was of length % d ,\
Was expecting at least % d'
% (X. length, X. Atleast)
Finally :
Print 'No exception was raised .'

Standard library, and more others

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.