Basic of python entry-level programming: python entry-level programming

Source: Internet
Author: User
Tags finally block

Basic of python entry-level programming: python entry-level programming

Python is an object-oriented, interpreted computer programming language. The Python syntax is concise and clear. One of its features is to force the use of blank spaces as statement indentation. The design philosophy of Python is "elegant", "clear", and "simple ".

Python is a type with strong (that is, the variable type is mandatory), dynamic, implicit (variable declaration is not required), and case sensitive (var and VAR represent different variables) and object-oriented programming languages (all objects.

Why is Python available?
System Programming: Provides Application Programming Interface (Application Programming Interface) to facilitate system maintenance and management. One of the iconic languages in Linux is an ideal Programming tool for many system administrators.

Graph processing: supports PIL, Tkinter, and other graphics libraries to facilitate graph processing.

Mathematical processing: The NumPy extension provides a large number of interfaces with many standard mathematical libraries.

Text processing: The re module provided by python supports regular expressions and the SGML and XML analysis modules. Many programmers use python to develop XML programs.

Network Programming: provides a wide range of modules to support sockets programming, allowing you to easily and quickly develop distributed applications. Many large-scale software development plans, such as Zope, Mnet, and BitTorrent. Google, are widely used.

Web programming: The application development language that supports the latest XML technology.

1. Python Basics

1.1Python Data Type Operator

Operator:
Standard Arithmetic Operator: +-* // get the integer % to get the remainder ** Multiplication

Standard Comparison OPERATOR: <=>>==! = <>

Logical OPERATOR: and or not

Basic numeric type:

Int (signed integer): it is usually called an integer or an integer. It is a positive or negative integer without a decimal point.

Long (long integer): or long, which is an infinitely large integer. In this way, an integer is written, followed by an L in upper or lower case.

Float (floating point real value): float or floating point number, indicating a real number, and write an integer part separated by a decimal point and a decimal part. Floating Point Numbers can also be scientific notation, with a power of 10 (2.5e2 = 2.5x102 = 250) expressed in e or E ).
Complex (plural): in the form of a + bJ, where a and B are floating points and J (or j) represent the square root of-1 (this is a virtual number ). A is the real part of the number, and B is the virtual part. Python programming does not use complex numbers.
Data Type-string:

In Python, you can use a pair of single quotes ''or double quotation marks" to generate a string.
A string is an unchangeable data type, that is, a new string is returned through the string method.

Index
For an ordered sequence, you can use the index method to access the values at the corresponding position. A string is an example of an ordered sequence. Python uses [] to index an ordered sequence. The index starts from 0. Python also introduces the negative index value usage, that is, counting starts from the back to the front.
S = "hello world"
S [0] outputs "h"
S [-2] outputs "l"
Parts
Fragment is used to extract the desired sub-sequence from the sequence. Its usage is var [lower: upper: step].
The value range is lower, but not upper, that is, [lower, upper). step indicates the value interval. If not, the default value is 1.
S = "hello world"
S [] outputs "el"
S [1:-2] output "ello wor"
Take a value every two:
S [: 2] Output "hlowrd"

Like java, Python also has many operations on strings:
S. split (), split s by space (including multiple spaces, tabs \ t, line break \ n, etc.), and return all the strings obtained by the split.
Line = "1 2 3 4 5"
Numbers = line. split ()
Print numbers output ['1', '2', '3', '4', '5']
S. replace (part1, part2), replace the specified part of part1 in string s with the desired part of part2, and return the new string.
S = "hello world"
S. replace ('World', 'python ')
Output "hello python"
S. upper (), returns a new string that uppercase all letters in s.
S. lower () returns a new string that contains all letters in s in lowercase.
S. strip () returns a new string that removes extra spaces at both ends of s.
S. lstrip () returns a new string that removes extra spaces starting with s.
S. rstrip () returns a new string that removes extra spaces at the end of s.
Of course there are still many ways
Forced conversion to string:
Str (ob), forced to convert ob into a string.
Repr (ob) is also mandatory to convert ob into a string
Data Type-list:

In Python, the list is an ordered sequence.
The list is generated with a pair of [] elements separated by commas (,). The elements in the list do not need to be of the same type, and the length of the list is not fixed.
The list is defined:
A = [1, 2.0, 'Hello']
Print
List operations. Similar to strings, a list also supports many operations. A list belongs to a variable data type and can be changed through indexes.
The following are some methods for listing operations:
Count (ob) returns the number of times the element ob appears in the list.
Index (ob): returns the index location where the element ob appears for the first time in the list. If the ob is not in the list, an error is returned.
Append (ob) to add the element ob to the end of the list.
Extend (lst) to add the elements of the series lst to the end of the list in sequence
Insert (idx, ob), insert ob at index idx, and then move the elements after the index.
Remove (ob) will delete the first ob in the list. If the ob is not in the list, an error will be reported.
Pop (idx) deletes the element at the index idx and returns this element.
Sort () will sort the elements in the list according to certain rules
Reverse (), which sorts the elements in the list from the back to the front.


Data Type-ancestor:

Similar to the list, Tuple is also an ordered sequence, but the tuples are immutable and generated using.
T = (10, 11, 12, 13, 14)
List conversion to tuples:
A = [10, 11, 12, 13, 14]
Tuple ()
Since tuples are immutable, there are only some immutable methods, such as calculating the number of elements and the element position index. The usage is the same as that of the list.
A. count (10)
A. index (12)
Speed comparison between lists and tuples:
The speed of generating tuples is much faster than that of the list, the iteration speed is faster, and the indexing speed is almost the same.

Data Type-dictionary:

Dictionary, also known as hash and map in some programming languages, is a data structure composed of key-value pairs.
Python uses '{}' or 'dict ()' to create an empty dictionary:
A = {}
A = dict ()
For the purpose of hash, keys of these key-value pairs must be unchangeable in Python, and values can be any Python object.
Dictionary Method:
D. get (key, default = None) returns the value corresponding to the key in the dictionary. If this key is not found, the value specified by default is returned (the default value is None)
D. Delete the pop method and return the value corresponding to the key in the dictionary. If this key is not found, the value specified by default is returned (the default value is None)
D. keys () returns a list Of all keys;
D. values () returns a list composed of all values;
D. items () returns a list of all key-value pairs;
Data Type-set:

List and string are both ordered sequences, while set is an unordered sequence.
Because the set is unordered, when two identical elements exist in the Set, Python only saves one of them (uniqueness). To ensure that the set does not contain the same element, the elements in the collection can only be immutable objects (deterministic ).
You can use the set () function or {} method to generate a set:
A = set ([1, 2, 3, 1])
A = {1, 2, 3, 1}
Python also provides a data structure called an immutable set. Unlike a set, an immutable set cannot be changed once it is created.
An immutable set is mainly used as the dictionary key.
Use frozenset to create:
S = frozenset ([1, 2, 3, 'A', 1])
Collection method:
S. add (a), used to add a single element to the set.
S. update (seq) is used to add multiple elements to the set.
S. remove (ob): removes the element ob from the set s. If it does not exist, an error is returned.
S. pop (), because the set has no order, elements cannot be popped up by position like the list, so the pop method deletes and returns any element in the set. If there are no elements in the Set, an error is returned.
1.2Python judgment statement
Loop statement
Loop statement: while

While expression: # expression conditional expression
While_suite # statements executed cyclically according to conditions
I = 0
Total = 0
While I <1000000:
Total + = I
I + = 1
Print total
Loop statement::

The for loop traverses all elements in <sequence>.
For <variable> in <sequence>:
<Indented block of code>

The for loop in Python is not the same as the for loop in java. It is more like an iteration loop, for example:
Total = 0
For I in xrange (100000 ):
Total + = I
Print total

Continue statement: in the case of continue, the program returns to the beginning of the loop and re-executes it.
Values = [7, 6, 4, 7, 19, 2, 1]
For I in values:
If I % 2! = 0:
# Ignore odd numbers
Continue
Print I/2
Break statement: When a break is encountered, the program jumps out of the loop regardless of whether the loop condition is met.

Condition Statement: if elif else
If expression1: # the blue part can be used separately.
If_suite
Elif expression2: # the green part can be omitted or repeated.
Elif_suite
Else expression3: # Use elif. else expression3 is required.
Else_suite # No switch-case for Python

1.3Python file read/write operations

Read files:
Use the open function or file function to read files, and use the string of the file name as the input parameter.
F = file('test.txt ')
F = open('test.txt ')
Print f. read () # read all file content
Print f. readlines () # Read content by row
F. close () # close the file after reading the file
Import OS # import OS package
OS .remove('test.txt ') # delete the file you just created
Write File:
Use the open function or file function to write files. Use the string of the file name as the input parameter. If the w mode is used, the file will be created if the file does not exist. If the file already exists, the w mode overwrites all previously written content. There is also append Mode a. The append mode does not overwrite the previously written content. You can also use read/write mode w +.
# Default r # r: read; w: write; a: Add; +: read/write; B: binary access
S = open ("e: // data.txt", 'w ')
S. write ("hello ")
S. close ()
Print open ("e: // data.txt"). read ()

1.3Python exception try & try t block

  Exception capture:

During Python compilation, syntax errors are checked, and other errors are detected during runtime.
When an error occurs, the Python interpreter raises an exception and displays details.
Try:
...... # Code exception may occur
......
Handle t IOError, e:
Print 'cause of error ', e
Finally # No matter whether the try block has an exception, the finally block content will always be executed and will be executed before an exception is thrown.

You can also use raise to intentionally raise an exception.

  Custom exception:

Defines an exception class inherited from ValueError. The exception class generally receives a string as the input and treats this string as the exception information.
Class CommandError (ValueError ):
Pass

 

This is probably the basic operation of python. If there are errors or omissions, we hope you can point them out.

 

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.