Day-3: Python Basics

Source: Internet
Author: User

    • Data types and variables

There are several main types of data that are processed directly in Python:

    1. Integer: Python can directly handle any size of an integer, either positive or negative, can be directly input processing;
    2. Floating-point numbers: floating-point numbers are also called decimals. There are common wording, such as: 1.1, there is also a large or small description of the scientific counting method, there is an e instead of 10, there are 1.3e6, 1.2e-5 and so on;
    3. Strings: "and" means strings, such as ' ABC ', "ABC". However, if the string contains ' or ', then note only ', outside with ', ' is enclosed ', only ', ' outside '. As in C, \ is an escape character, but it is cumbersome to use. If both ' and ' are included, you can precede the string with R to indicate the intent, and the inner escape character is useless. If you want to represent multiple lines of content, you can use
" " Line1line2line3 " "

4. Boolean value: Two values, respectively true and false. Boolean values can be performed in the following types of operations:

    • and operation. The result is true only if both the left and right values are true. Note: 1 and 2 o'clock, if 1 is false, 2 is not calculated because the result has been determined to be false, known as a short-circuit phenomenon;
    • Or operation. The result is true when either of the left or right values is true. Note: As above, due to short-circuit phenomenon, as long as 1 or 2 in 1 is true,2 will not be calculated, the result is directly true;
    • Not operation. For a single-mesh operation, True becomes false,false to true.

5. None: null value, it does not understand that 0,0 is meaningful, and none is a special null value.

Variable:

There are no restrictions on the types of variables in Python, and it is not necessary to define what type to use directly.

    • Python string and encoding

All characters in Python 2.7 are ASCII-encoded by default, and when you want to represent Unicode encoding (multi-lingual), use:

U' ... '

In particular, since there is no Chinese in the ASCII encoding, it is important that you precede it with the Chinese character in the string. (Python3.0 changed to ' .... ' and u ' ... ' are Unicode encoded)

However, ASCII encoding uses 1 bytes, and Unicode encoding generally uses two bytes, especially even 4 bytes. To save space, Unicode encoding becomes a mutable Unicode encoding, the UTF-8 encoding. The following two diagrams are the encoded forms of translation when Notepad edits and browses a Web page:

As you can see, saving time with UTF-8 encoding when storing and transmitting, but choosing Unicode encoding when used, guaranteeing correct display and editing.

Again, the ASCII encoding in Python 2.7 plus the prefix of U becomes Unicode encoded with the encode (' Utf-8 ') method, which turns utf-8 encoding, in turn, the Utf-8 encoding is decoded into Unicode encoding by decode (' Utf-8 '). The process is as follows:

>>> u'English'. Encode ('Utf-8')'\xe4\xb8\xad\xe6\x96\x87' #Note that it becomes a byte encoding format, Utf-8>>>'\xe4\xb8\xad\xe6\x96\x87'. Decode ('Utf-8') U'\u4e2d\u6587' #into a 2 byte encoding, Unicode>>>Print '\xe4\xb8\xad\xe6\x96\x87'. Decode ('Utf-8') Chinese#first changed from Utf-8 to Unicode and then print

  considering Python's cross-platform operation, it is common to add these two lines at the beginning of the file :

# !/usr/bin/env python # -*-coding:utf-8-*-

The first line of comments is to tell the Linux/os x system that this is a python executable and the Windows system ignores this comment;

The second line of comments is to tell the Python interpreter to read the source code according to the UTF-8 encoding, otherwise the Chinese output you write in the source code may be garbled.

Formatted output in Python:

' .... ' % (...)

There are several placeholders in the string, followed by a few variables or constants.

The commonly used placeholders are:

%d integers

%f floating Point

Number of characters in%s

%x hexadecimal integer

    • Three special types of data
    • List

A list is an ordered set of elements that can be added or subtracted at any time. In [], the index starts at 0 and the last is the number-1. He has the following methods:

    • Len (): Gets the number of list elements
>>> len (classmates)3
    • Append (): Add an element at the end of the list
>>>list1 = [1, 2, 3]>>>list1.append (4) # Add an element at the end >>>list1> >>[1, 2, 3, 4]
    • Insert (): List Inserts an element
>>>list1 = [1, 2, 3]>>>list1.insert (2,6) # The first parameter is the insertion position, the second is the element >>>  Print  list1>>>[1, 2, 6, 3]
>>>Print List1.insert (7) # Only one argument is inserted as an element in the last
>>>[1, 2, 6, 3, 7]
    • Pop (): Delete an element
>>> Classmates.pop ()#Delete last element when no parameter'Adam'>>>classmates['Michael','Jack','Bob','Tracy']>>> Classmates.pop (1)#Delete an element of the index position for the parameter'Jack'>>>classmates['Michael','Bob','Tracy']
    • Tuple

Tuple, name Yuan zu. Similar to list, but once a tuple is established, its elements cannot be changed, and there are no methods such as append (). Its significance is to ensure that elements cannot be changed and security is ensured. Index, use (), also starting from 0.

    • Dict

Full name dictionary, using key-value (Key-value) storage, with extremely fast lookup speed.

>>> d = {'Michael'Bob'Tracy ': >>>d['Michael']95

Dict is a hash algorithm that calculates the storage location of value by key, so the value of key is constant. Feature is

    1. The speed of finding and inserting is very fast and will not increase with the increase of key;
    2. It takes a lot of memory, and it wastes a lot of memory.

There are two methods of Get () and pop ():

>>> d.get ('Thomas')    #  returns to none when the Python interactive command line does not display the results. >>> d.get ('Thomas',-1)-1
>>> d.pop ('Bob')75>>> d{' Michael ' ' Tracy ': 85}
    • Set

Set is similar to Dict, except that the only difference is that there is no storage of the corresponding value.

The set needs to provide a list as the input collection, which shows you that the set([1, 2, 3]) set has only 3 elements of the inside of a single, and the [] display does not indicate that this is a list.

The set is added by adding the element to the set with the Add (key) method;

Set removes the element with the remove (key) method.

    • Conditional Judgment and circulation

In Python, the indentation is particularly strict, and it is executed as a block with the same indentation.

Among them, python in the judgment and looping statements, are to: as the indentation of the identity.

The complete form of a judgment statement:

if < condition judgment 1>:    < execute 1>elif < condition 2>    :< execute 2>elif < condition judgment 3>:    < execute 3>else:    < Execute 4>

There are two kinds of circular statements, one is the for...in loop and the other is the while loop.

The for...in loop is as follows:

names = ['Michael'Bob'Tracy ' ] for in names:    Print name

Take each element of the names into name and loop it in turn.

While loop is: As long as the condition is satisfied, the loop continues, and the condition is not satisfied when exiting the loop.

sum == while n > 0:    = sum + n    = n-2print sum

Finally Raw_input () need to be aware that

Birth = raw_input ('Birth:')

The string inside the ' birth ' is displayed on the terminal at runtime birth: But the actual input age of the number, passed to birth is a string, if you want to transfer an integer, you should instead:

birth = Int (raw_input (' Birth: '))

  

Day-3: Python Basics

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.