Python base notes --Python

Previous:

Here is the record about the contents of their own learning, because it is a white, so a lot of basic things will record it, mainly to deepen your own impression.

Information from the Liao Xuefeng teacher's official website , as well as instructional videos beep station.

 

 

type of data

In Python, data types can be processed directly are the following: integer, floating point numbers, strings, Boolean values, null values, variables, constants. Write to find a few major

String

 

String is single quotes 'or double quotes "any text enclosed in, for example 'abc', "xyz"and the like.

If the string contains both internal 'and contain "can use the escape character \is identified, such as:

'I\'m \"OK\"!'

A string representation of the contents are:I'm "OK"!

 

 

 Escape character \can escape a lot of characters, such as \nnewline, \ttab character, the character \itself must be escaped, it \\represents the character is\

 

 If the internal string has a lot of line breaks, with \nwrite one line is not good reading, in order to simplify, Python allows '''...'''format represents a number of lines, when you finish entering terminator '''and parentheses )after the statement is executed and print the results.

 

Boolean value

Boolean algebra and Boolean value indicating exactly the same, only a Boolean value True, Falsetwo kinds of value, you can use Boolean values and, orand notoperations.

Null

Null is a special value, not 0, use None to represent.

variable

Variables can not only be a number, it can also be any data type.

A variable can be aassigned to another variable b, the operation is actually the variable bpointing to the variable adata points, for example:

 

 And now turned into a XYZ

 

 

 Because the execution a = 'ABC', the interpreter creates strings 'ABC'and variables a, and to apoint to 'ABC':

 

 Execution b = a, the interpreter creates a variable b, and to bpoint to athe string pointed to 'ABC':

 

 Execution a = 'XYZ', the interpreter creates a string 'XYZ', and the apoint to be changed 'XYZ', but bdid not change:

 

Character Encoding

Just say the string is a character type, however, the string comparison is there a particular coding problem.

Only the first 127 characters are encoded in the computer, which is the case letters, numbers and some symbols, the coding table is called ASCIIencoding. But the deal with the Chinese is obviously a byte is not enough, you need at least two bytes, but can not ASCII encoding and conflict around the world there are hundreds of languages in a multilingual mix of text, displayed will be garbled. In order to not conflict Unicode came into being. All Unicode languages are unified into a set encodings, so you do not have a garbage problem.

ASCII and Unicode encoded difference coding : ASCII code is 1 byte, and the Unicode encoding is usually 2 bytes.

If unified into Unicode encoding, the garbage problem disappear. However, if you write essentially all text is in English, then use Unicode encoding than ASCII encoding requires double the storage space on the storage and transport will be very worthwhile.

And the emergence of the Unicode encoding into a "variable length code" UTF-8coding. UTF-8 encoded according to Unicode character to a different size of the figures 1-6 encoded into bytes, commonly used letters are encoded into a byte characters typically 3 bytes, only a rare character will be encoded into bytes 4-6. If you want to transfer the text contains a lot of English characters, use UTF-8 encoding will be able to save space.

 

UTF-8 encoding has an additional advantage is that ASCII encoding can actually be seen as part of UTF-8 encoding, so only supports ASCII encoding a large number of legacy software may continue to operate in UTF-8 encoding.

 

 

 These are the relationships between these three coding. The computer system is now universal character encoding works:

In computer memory, uniform use Unicode encoding, when the need to save time or the hard disk needs to be transmitted, is converted to UTF-8 encoding.

Use Notepad to edit the time, UTF-8 character read from the file is converted to Unicode characters into memory, after the editing is complete, save time and then converted to Unicode UTF-8 to save the file:

 

 

 Browse the Web, the server will dynamically generated content into Unicode UTF-8 and then transmitted to the browser:

 

 

 

 

Python strings

In the latest version of Python 3.x, strings encoded in Unicode, that is, Python strings support multiple languages, such as:

 

 For encoding a single character, Python provides the ord()integer representation of the character acquired function, chr()the function corresponding to the coded characters converted to:

 

Since Python string type strin memory in Unicode, characters corresponding to a plurality of bytes. If you want to transfer over the network or saved to disk, you need to strbecome in order bytes bytes.

Python of bytesdata types tape brepresented prefix single or double quotation marks:

 

'ABC'And b'ABC', the former str, although the latter have to display the contents of the former and the same, but byteseach character only one byte.

In Unicode strby the encode()method may be coded as specified bytes,

 

 To calculate strthe number of characters included, you can use len()the function :

 

 Visible, a Chinese character after the UTF-8 encoding usually takes up three bytes, and an English character occupies only one byte.

When a string operation, we often encounter strand bytesmutual conversion. In order to avoid the garbage problem, you should always stick with UTF-8 encoding strand bytesconversion.

format:  

In Python, using C language format and manner consistent with the %implementation, for example:

 

 

 Common placeholders:

% D-- integer

% F-- float

% S-- string

% X-- hexadecimal integer

Use %%to represent a%

Wherein the integer and floating point format can also specify whether the complement integer and fractional bits 0:

 

 Note: If you can not remember what took %sforever to work, it will forward any data type into a string.

 

 

format()

Another method is to use the format string string format()method, which in turn replaces the placeholder in the string parameter passed, but to a lot of trouble:

 

 

list和tuple

list

Python built-in data type is a list: list. list is an ordered set, which you can add and remove elements at any time.

For example, a list of names of the class:

 

 Variable classmatesis a list. Use len()may be a function of the number of list element obtained:

 

 With an index to access the list of elements in each position, remember that the index is from 0the beginning, when the index is out of range, Python will report a error.

 

 If the last element to take, in addition to calculating the position index, but also can be used -1to index, direct access to the last element, and so on, -2, -3, etc.

 

Elements inserted into the specified location, such as index number 1position; may be added to the list of elements to the end; to remove the element list at the end, by pop()the method; to remove the element designated location, by pop(i)a method in which ian index position; to to replace an element into other elements, it can be assigned directly to the corresponding index position

 

 

list elements can also be another list, it can be seen as a two-dimensional array:

 

 

 

tuple

Another called an ordered list of tuples: tuple. tuple and the list is very similar, but the tuple Once the initialization can not be modified, such as:

 

If you want to define an empty tuple, you can be written ()to only define a tuple 1 elements, can not write t = (1), because the definition is not a tuple, is 1this number, add a comma to disambiguate

 

 You can also write so. . tuple into a "variable" was. .

 

On the surface, the tuple element has indeed changed, but the change is not in fact an element tuple, but the list of elements.

 

Conditional

In the Python program, with the ifrealization statement.

Python indentation according to the rules, if ifthe statement judge True, put the two lines indented print statement is executed, otherwise, do nothing.

Also to ifadd a elsesentence, meaning that if the ifjudgment is False, do not perform ifthe content, to put elseexecuted.

You can elifdo a more detailed judgment. elifIs else ifthe abbreviation can have multipleelif。

IF <1 conditional> :
     <1 performs> 
elif <conditional 2> :
     <performing 2> 
elif <conditional 3> :
     <performed 3>
 the else :
     <performed 4>

Note: Do not write less colon :

 

ifStatement is executed from the judge down, if correctly judge somewhere will no longer down judgment.

Combine the previous thing to do exercises:

Xiao Ming height 1. 75 , weighing 80.5kg. Please formula for BMI (weight divided by height squared) Xiaoming help his BMI index is calculated, and according to BMI index: 

less than 18. A . 5 : too light
 18.5 - 25 : Normal
 25 - 28 : overweight
 28 - 32 : Obesity 
High 32: severe obesity

answer:

name = INPUT ( ' Enter your name: ' ) 
height = INPUT ( ' Enter your height (m): ' ) 
weight = INPUT ( ' Enter your weight (kg): ' ) 
H = a float (height ) 
W = a float (weight) 
BMI = ( a float (W / (H * H)))
 IF BMI> 32.0 : 
    Print ( ' severely obese ' ) 
elif BMI > = 28.0 : 
    Print ( ' fat ' ) 
elif BMI> = 25.0 : 
    Print ( ' heavy ' ) 
elif BMI > = 18.5 : 
    Print ( ' normal ' )
 the else : 
    Print ( " too light " )

 

 Height and weight do not give up, hey, obesity, uncomfortable hey. . . . .

 

cycle

In order for a computer to calculate the repetitive operations thousands of times, we need to loop. So for x in ...cycle each element is assigned to the variable x, and then execute the statement block indentation. such as:

 

 

 

 

 

 Python provides a range()function that can generate a sequence of integers, by then list()can be converted to the list function. Such range(101)generated sequence is less than an integer of from 0 to 101, i.e. 0-100:

 

 

 

 

 

 The second loop is the while loop, as long as the conditions are met, continuous cycle, the loop exits when the condition is not satisfied. For example, we want to calculate the sum of all odd-numbered less than 100, can be achieved using a while loop:

The cycle variables ncontinue to decrement, until it was -1time, no longer satisfied while condition loop exits.

 

 

 

 

 

 

break

In cycling, the breakstatement can exit the loop early.

We make it print out after 1 to 10, followed by the printing END, the program ends.

 

 

 

 

 

continue

In the cycle, but also by continuethe statement, skipping the current cycle, the next cycle started directly.

In 0-10, print only odd, can continuestatement skip cycle:

 

 

 

 

A little test:

Please list using a circulating sequentially print out the name of each of the Hello, XXX! : 

Names = [ ' Bart ', ' Lisa ', ' Adam ']

 

answer:

names = ['Bart', 'Lisa', 'Adam']
for name in names:
    print('Hello,%s!'%(name))

 

Guess you like

Origin www.cnblogs.com/qi-yuan/p/12616919.html
Recommended