Python learning notes (1), python learning notes (

Source: Internet
Author: User

Python learning notes (1), python learning notes (

1. The first Applet:

The python syntax is simple and indented as follows:

a = 100if a >= 0:    print aelse:    print -a
Use # for comments. Each other line is a statement. When the statement ends with a colon ":", The indented statement is considered as a code block.

Generally, the Tab key is indented or four spaces are pressed.

Note: python programs are case sensitive.


Ii. Data Types and variables

(1) Data Type:

A. Integer:

Python can process Integers of any size

You can use hexadecimal notation to indicate the integer: 0x prefix and 0-9, a-f. For example, 0xff00, 0xa5b4c3d2


B. Floating Point Number:

A floating point is a decimal point. When expressed in scientific notation, the decimal point of a floating point is variable. For example, 1.23x109 and 12.3x108 are equal.

For large or small floating point numbers, we need to use scientific notation to replace 10 with e. 1.23x109 is 1.23e9 or 12.3e8.


C. String:

In python, strings are enclosed by single quotation marks ''or double quotation marks.

If the single quotation mark (') is a character, it can be enclosed by double quotation marks ("), for example, print" I'm OK"

If a string contains both single quotation marks and double quotation marks, Escape Character \ is used for identification, such as print "I \'m \" OK \""

The right slash \ can escape many characters. For example, \ n represents a line break, \ t represents a tab, \ represents \

If many characters in the string need to be escaped, you need to add a lot of \. To simplify the process, python also allows the use of r'' to indicate that the character strings inside ''are not escaped by default. For example, print R' \ t \\'

>>> print '\\\t\\'\       \>>> print r'\\\t\\'\\\t\\
If the character string contains many line breaks, it is hard to read the lines written in \ n. to simplify it, python allows ''''' format to represent multiple lines of content, for example:

print '''line1line2line3'''

D. boolean value:

A boolean value must be either True or False.

In Python, True and False can be used to represent boolean values.

>>> 3 > 2True>>> 3 > 5False
Boolean values can be calculated using and, or, not

>>> True and TrueTrue>>> True and FalseFalse>>> False and FalseFalse>>> True or TrueTrue>>> True or FalseTrue>>> False or FalseFalse>>> not TrueFalse>>> not FalseTrue


E. Null Value

A null value is a special value in python, expressed as None. None cannot be understood as 0, because 0 makes sense, and None is a special null value.


(2) variables

The variable name must be a combination of letters, numbers, and underscores and cannot start with a number.

You can assign any data type to a variable. The same variable can be assigned multiple times and can be a variable of different types, for example:

A = 123 # a is an integer a = 'abc' # a is a string
This variable is a dynamic language, which is similar to JS. Java is a static language because it must specify the variable type when defining the variable,

For example, int a = 123;


(3) Constants

A constant cannot be a variable. in python, constants are usually capitalized, which is the same as Java.
For example, PI = 3.1415926, but in fact PI is still a variable. Python has no mechanism to ensure that PI will not be changed.


Iii. String and encoding

1. Encoding

ASCII encoding: Only 127 letters are encoded into a computer, including uppercase and lowercase English letters, numbers, and symbols. Only one byte is used for storage.

Unicode encoding: all languages are unified into a set of encoding, so there will be no garbled problem. Generally, two bytes are used to save one character. However, if all languages generate Unicode

Encoding and garbled characters disappear. However, if the text we write is basically in English, Unicode encoding will provide twice as much storage space as ASCII encoding, in terms of storage and transmission

No. In the spirit of saving, there is a UTF-8 encoding that converts Unicode encoding into Variable Length Encoding.


Because the python source code is a text file, when the source code contains Chinese characters, you must specify to save the source code as UTF-8 encoding when saving the source code. When the python parser reads the source code,

To make it read by UTF-8, we usually write these two lines at the beginning of the file:

#!/usr/bin/env python# -*- coding: utf-8 -*-
The first line of comment is to tell the linux system that this is a python executable program.

The second line of comment is to tell the python interpreter to read the source code according to UTF-8 encoding. Otherwise, the Chinese output you write in the source code may contain garbled characters.

2. format the string:

In python, % is used to format the string, % s is used to replace the string, % d is used to replace the integer, and % f is used to represent the floating point. How many %? Placeholder, followed by several variables or values,

The order must be matched. If there is only one % ?, Parentheses can be omitted.

>>> 'Hello, %s' % 'world''Hello, world' >>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)'Hi, Michael, you have $1000000.'
In some cases, % in a string is a common character. What should I do? In this case, you need to escape and use % to represent a %

>>> 'growth rate: %d %%' % 7'growth rate: 7 %'

4. Use list and tuple

(1) list

List is an Ordered Set Built in python. You can add and delete elements at any time.

For example, you can use a list to list the names of all students in the class. The variable classmates is a list

>>> classmates = ['Michael', 'Bob', 'Tracy']>>> classmates['Michael', 'Bob', 'Tracy']

A. Get the number of list elements: len (classmates)

B. Access the element at each position in the list through the index (starting from 0): classmates [0]

If you want to obtain the last element, you can also use-1: classmates [-1], and the second to the last is classmates [-2].

C. append the element to the end of the list: classmates. append ('Jim ')

D. insert the element to the specified position: classmates. insert (1, 'Tom ')

E. Delete the element at the end of the list: classmates. pop ()

F. Delete the element at the specified position: classmates. pop (2)

G. replace an element with another element. You can directly assign a value to the corresponding index location: classmates [2] = 'jack'


Another list can be nested in the list, for example:

>>> s = ['python', 'java', ['asp', 'php'], 'scheme']>>> len(s)4
We can regard s as a two-dimensional array. If you want to get 'php', you can write s [2] [1].

(2) tuple

Tuple is similar to list, but tuple cannot be modified once initialized. Therefore, tuple does not add or delete elements.

>>> classmates = ('Michael', 'Bob', 'Tracy')

What is the use of immutable tuple?

Because tuple is immutable, the code is safer. If possible, use tuple instead of list.


Be careful when using tuple to prevent falling into the trap:

** Trap 1: When tuple is defined with only one element, a comma must be added to eliminate ambiguity, because parentheses make the parser think that it is a parentheses in a mathematical formula.

>>> t = (1,)>>> t(1,)
** Trap 2: tuple is unchangeable, but if a list is saved in tuple, the list is variable.

>>> t = ('a', 'b', ['A', 'B'])>>> t[2][0] = 'X'>>> t[2][1] = 'Y'>>> t('a', 'b', ['X', 'Y'])

5. Condition judgment and Circulation

(1) condition judgment:

Print different content based on the user's age:

age = 3if age >= 18:    print 'adult'elif age >= 6:    print 'teenager'else:    print 'kid'
The if condition can be abbreviated, for example:

if x:    print 'True'
If x is a non-zero value, a non-empty string, or a non-empty list, the value is True. Otherwise, the value is False.


(2) loop

A. for Loop

sum = 0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:    sum = sum + xprint sum
If you want to calculate the sum of integers from 1 to, you can use the range () function to generate an integer sequence.

B. while Loop

Calculate the sum of odd numbers within 100:

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

6. Use dict and set

(1) dict

Like map in java, key-value is used for storage.

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}>>> d['Michael']95
A. Save a value: d ['Adam '] = 67

B. A key corresponds to a value. If the key does not exist, an error is returned. To avoid the error, there are two methods to determine whether the key exists.

First, use in to determine whether the key exists: 'tracy 'in d # Return True

Second, the get method provided by dict: d. get ('Jim ') # returns None.

C. delete a key: d. pop ('bob ')


(2) set

Set is the same as set in java. Keys cannot be repeated and value is not stored.

>>> s = set([1, 2, 3])>>> sset([1, 2, 3])
1. add the element to the set: s. add (4)

2. Delete element from set: s. remove (4)

3. set can be used for intersection and Union operations in the mathematical sense.

>>> s1 = set([1, 2, 3])>>> s2 = set([2, 3, 4])>>> s1 & s2set([2, 3])>>> s1 | s2set([1, 2, 3, 4])

For more information, see Liao Xuefeng.

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.