Getting Started with Python

Source: Internet
Author: User

The first contact with the concept of Python or in 2013 in the Ruijie Network to do interns, at that time because of project testing needs, have proposed to use Python for automated testing, but due to the actual needs of the project, the end of no use, also shelved the learning of Python, I took the Python tutorial, but also to see the bits and pieces, recently have been thinking about what they should do, confused, as if many languages many tools need to learn, but not enough energy, the latest idea is to go with those training or low threshold of people to rob Android's rice bowls, rather than in their own C + + On the basis of programming, learning the language that a few people will learn, just like the Java language, many say that they will be programmed in the Java language, but really can understand its mechanism and principle, not much, much is to use the framework to write projects.

Python: Simple, elegant, fast

Simple to variable can be used without the definition of direct use, can call many functions, easy to transplant, the data processing speed, but memory consumption

When I learn python, I feel it is like watching the pupils ' homework, of course, just learned the basic part, has not advanced to the higher order, added a Python development group, to the group asked there is no good IDE, enthusiastic people said Pycharm good, loaded down found this is the legendary Python, Sure enough to force.

Organized the basics of getting started with Python.

1. Variables and data types

1.1 Data types

In Python, there are several types of data that can be processed directly:

One, integer

Python can handle integers of any size, including, of course, negative integers, and in a Python program, integers are represented in exactly the same way as mathematical notation.

Second, floating point number

Floating-point numbers, which are decimals, are called floating-point numbers because, when represented by scientific notation, the decimal position of a floating-point number is variable, for example, 1.23x10^9 and 12.3x10^8 are equal.

Integers and floating-point numbers are stored inside the computer in different ways, and integer operations are always accurate (is division accurate?). Yes! ), and the floating-point operation may have rounding errors.

Three, string

strings are ‘‘ "" arbitrary text in or around them , such as ' abc ', 'xyz ', and so on. Note that the' or ' itself is only a representation, not part of a string, so the string has ‘abc‘ only a,b,c these 3 characters.

Four, Boolean value

A Boolean value is exactly the same as a Boolean algebra, with a Boolean value of only True False two values, either, True or, False in Python, you can directly use True and False represent a Boolean value (note case). It can also be computed by Boolean operations.

Boolean values can be used and , or and not operations.

Five, null value

A null value is a special value in Python, None denoted by. None cannot be understood as 0, because 0 is meaningful, and none is a special null value.

Contrast and C language, can find a lot of different, the biggest difference is more abstract and colloquial

1.2 Variables

In a python program, a variable is represented by a variable name, and the variable name must be a combination of uppercase and lowercase English, numeric, and _, and cannot begin with a number .

A = 123    # A is an integer print AA = ' Imooc '   # A becomes a string print a

This type of variable itself is called Dynamic language, which corresponds to static language.

Static languages must specify the variable type when defining the variable, and if the type does not match, an error is given. For example, Java is a static language, and assignment statements are as follows (//for comments):

int a = 123; A is an integer type variable a = "Mooc"; Error: Cannot assign string to integer variable

Dynamic languages are more flexible than static languages.

1.3 Notes

Single-line comment with "#"

C language with/**/or//

2.list and tuple types

2.1 List: Lists, ordered collections, because Python is a dynamic language, so the elements contained in the list are not required to be the same data type, we can completely include a variety of data in the list , with [element].

Sequential access list: It is important to note that the index starts at 0, that is, the index of the first element is 0, the second element is indexed by 1, and so on.

Reverse access list: The index of the last element is-1, and so on.

Array-like access

add element: With function append (i), such as: L.append ("Hello"), with function Insert (I,H), such as: L.insert (0, "Hello") in the first position of L add "Hello" element, other elements automatically shifted, It's much simpler than adding arrays.

Delete element: Use the function pop (i), delete the element I, when using pop () to delete the last element, the other elements automatically shifted.

Replace element: Replace the element with the original third position with "Hello" directly for position substitution, e.g. L (2) = "Hello"

2.2 Tuple: Ordered list, we call "tuple", once the tuple is created, it cannot be modified, the only difference between creating a tuple and creating a list is ( 元素) substituting [ ]。

However, when the elements inside a tuple are mutable, such as list, the elements of the list can be modified, and a tuple's so-called "invariant" means that each element of a tuple is directed to never change. Point to ' a ', it cannot be changed to point to ' B ', point to a list, cannot be changed to point to other objects, but the list itself is variable.

3. Conditional Judgment and circulation

3.1 If: colon indicates the corresponding code block

To indent

Elif:

To indent

Else

To indent

3.2 for name in L:

To indent, you don't need anything like + +, it's a lot simpler than c.

3.3 While X<n:

Add code to indent

X+=1 or X=x+1

3.4 Exit Loop

Break: Subsequent loop continue: when the secondary loop

4.Dict and set

4.1 Dict:key-value, similar to map, with {element}, and key cannot be duplicated.

4.1.1 When accessing value, to avoid keyerror, there are two ways:

First, determine whether the key exists, with the in operator:

If ' Paul ' in D:    print d[' Paul '

If ' Paul ' is not present, the IF statement evaluates to False, and the print d[' Paul ' is not executed naturally, thus avoiding the error.

The second is to use the dict itself to provide a get method, when key does not exist, return to none:print D.get (' Bart ')

4.1.2 Dict Features: 1. Find Fast, regardless of the amount of data, of course, at the expense of memory, the list is the opposite, the memory is small, but the search speed is slow. 2. stored key-value Order pairs are not sequential, so it is possible to print out the Dict each time is different. 3. as key elements must be immutable, Python's basic types such as strings, integers, floating-point numbers are immutable and can be used as keys. But the list is mutable and cannot be a key

4.1.3 Adding and updating elements: using Assignment statements directly

4.1.4 traversal: For loops, such as:

D = {' Adam ': +, ' Lisa ': $, ' Bart ':}for key in D:    print key

4.2 Set: holds a series of elements, which is much like the list, but the set elements are not duplicates and are unordered, which is like the Dict key.

The elements in the set are case sensitive and can be accessed using: in to determine whether the element exists.

Is Bart a classmate of the class?

>>> ' Bart ' in Strue

Is Bart a classmate of the class?

>>> ' Bart ' in S

False
Features of the 4.2.1 set:

the internal structure of set is much like the dict, the only difference is that it does not store value, so it is very fast to determine whether an element is in set.

The set stored element is similar to the Dict key, and must be an immutable object , so any mutable object cannot be placed in the set.

Finally, the set stores the elements that are not in order.

4.2.2 Traversal: For name in set: Traversing

4.2.3 Update: Add () is added directly, and then removed with remove ()

5. Functions

In Python, define a function to use the def statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, and the return value of the function is returned with a return statement. If there is no return statement, the result is returned after the function is executed, except that the result is none. the function returned by Python is actually a tuple, but it is easier to write.

5.1 Define default parameters : Since the parameters of the function match from left to right, the default parameter can only be defined after the required parameter, define a greet () function, which contains a default parameter, if not passed in, print ' Hello, World ', If incoming, print ' Hello, xxx. ' Where world is set as the default parameter.

5.2 Defining Variable Parameters:

If you want a function to accept any of the arguments, we can define a variable parameter:

DEF fn (*args):    print args

There is an * number in front of the variable parameter, we can pass 0, one or more parameters to the variable parameter.

The Python interpreter assembles the passed set of parameters into a tuple and passes it to the mutable parameter, so the variable args is treated as a tuple directly inside the function. For example, to find the average of any number

6. Slice the list: L[0:10],l[::2],l[0:-1],l[4:50:5]

7. Iteration: In Python, iterations are always taken out of the element itself, not the index of the element.

7.1 List Iteration index: using the Enumerate () function, we can simultaneously bind indexes index and element name in the For loop. However, this is not a special syntax for enumerate (). In fact, the enumerate () function puts:

[' Adam ', ' Lisa ', ' Bart ', ' Paul ']

Into something like this:

[(0, ' Adam '), (1, ' Lisa '), (2, ' Bart '), (3, ' Paul ')]
The enumerate () function is similar to the function of a zip function, except that the zip can specify an index, and the enumerate () function starts at index 0 by default.

The zip () function can turn two lists into a list:

>>> zip ([ten, +,], [' A ', ' B ', ' C ']) [(Ten, ' A '), (+, ' B '), (+, ' C ')]
7.2 dict Iteration Gets values:
Use Dict.values () or dict.itervalues () to get all the values of the Dict.

1. The values () method actually converts a dict to a list containing value.

2. However, the itervalues () method does not convert, and it takes value from dict in sequence during the iteration, so the Itervalues () method saves the memory needed to generate the list, compared to the values () method.

3. Print itervalues () find it returns a <dictionary-valueiterator> object, which shows that in Python, thefor loop can be used to iterate beyond list,tuple,str. Unicode,dict, and so on , any iterator object can be used for a for loop, and the inner iteration of how we usually don't care.

If an object says that it can iterate, then we iterate it directly with a for loop, which is an abstract data operation that does not require any data inside the iteration object.

7.3 Dict Iteration Key and values:

For key, value in D.items ():     ... Print key, ': ', value
Use the function items () or Iteritems ()
8. List generation: List generation you can replace loops with a single line of statements, such as:
[x * x for x in range (1, one) if x 2 = = 0] Conditional filter
[M + N for m in ' ABC ' for n ' 123 ' multiple loops



Getting Started with Python

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.