Python BASICS (1): python Basics

Source: Internet
Author: User
Tags floor division printable characters uppercase letter

Python BASICS (1): python Basics
1. Variables and data types: 1.1 Variables

1. Each variable stores a value-information associated with the variable.

2. The variable can be an integer or floating point number, a string, or any data type.

1.1.1 variable naming and usage

Variable names can only contain letters, numbers, and underscores,And the number cannot start.Variable names cannot contain spaces, but can be separated by underscores. Python keywords and function names cannot be used as variable names. The variable name should be short and descriptive. Use lowercase letters l and uppercase letters O with caution, because they may be incorrectly regarded as numbers 1 and 0.

1.1.2 avoid naming errors when using variables

When an error occurs, the interpreter provides a traceback (backtracking ). Traceback is a record that points out what is in trouble.

1.2 string str

1.StringIs a series of characters. Is a data type, used in PythonQuotation marksIt can contain strings.Single quotesOrDouble quotation marks.

2. Unicode standards are also evolving, but the most common feature is to use two bytes to represent a single character (four bytes are required if very remote characters are used ). Modern Operating Systems and most programming languages support Unicode directly. Converts Unicode encoding to UTF-8 encoding of variable length encoding.

3. Python uses single quotation marks or double quotation marks with a B prefix for bytes data: x = B 'abc '. Str represented by Unicode can be encoded as the specified bytes through the encode () method.

'Abc'. encode ('ascii ')

B 'ABC

If we read byte streams from the network or disk, the data we read is bytes. To change bytes to str, you need to use the decode () method:

B 'abc'. decode ('ascii ')

'Abc

4. For the encoding of a single character, Python provides the ord () function to obtain the integer representation of the character. The chr () function converts the encoding to the corresponding character:

>>> Ord ('A ')

65

>>> Ord ('zhong ')

20013

>>> Chr (66)

'B'

>>> Chr (1, 25991)

'Wen'

5. to calculate the number of characters in str, you can use the len () function, and the len () function to calculate the number of characters in str. If it is changed to bytes, the len () function calculates the number of bytes. It can be seen that a Chinese character is usually 3 bytes after being encoded by a UTF-8, and 1 English character only occupies 1 byte.

1.2.1 string operations

1. The method is the operations that Python can perform on data.

2. title () is used to display each word in uppercase, that is, to change the first letter of each word to uppercase.

3. upper () converts all strings to uppercase. The lower () character string is changed to lowercase letters.

4. If a string contains at least one letter and all letters are in upper or lower case, the isupper () and islower () Methods return a Boolean value of True accordingly. Otherwise, this method returns False.

5. salpha () returns True if the string contains only letters and is not empty;

6. isalnum () returns True if the string contains only letters and numbers and is not empty;

7. sdecimal () returns True if the string contains only numeric characters and is not empty;

8. sspace () returns True. If the string contains only spaces, tabs, and line breaks, it is not empty;

9. istitle () returns True if the string only contains words starting with an uppercase letter and followed by lowercase letters.

10. The startswith () and endswith () Methods return True if the strings they call start or end with the strings passed in by this method. Otherwise, the method returns False.

11. The join () method is called on a string. The parameter is a string list and a string is returned.

>>> ','. Join (['cats', 'rds', 'BATs'])

'Cats, rats, bats'

>>> ''. Join (['my, 'name', 'is, 'simon '])

'My name is Simon'

>>> 'Abc'. join (['my, 'name', 'is, 'simon '])

'Myabcnameabcisabcsimon'

12. The split () method does the opposite: it calls a string and returns a string list. You can also pass in a split string to the split () method to specify that it is separated by different strings.

>>> 'My name is Simon '. split ()

['My, 'name', 'is, 'simon ']

13. The padding methods must () and ljust () return the filled version of the strings that call them, and align the text by inserting spaces. The first parameter of the two methods is an integer length used to align the string. The second optional parameter of the just ust () and ljust () Methods specifies a fill character, replacing the space character.

>>> 'Hello'. Must (20 ,'*')

* Hello'

>>> 'Hello'. ljust (20 ,'-')

'Hello ---------------'

14. The center () string method is similar to ljust () and just ust (), but it centers the text, rather than align left or right.

15. sort () sorts strings.

16. Be sure to note that the Python program isCase SensitiveIf the case is incorrect, the program reports an error.

17. Merge -- Python uses the plus sign + to merge strings

18. You can add r before the start of the string to make it the original string. All escape characters are ignored after the "original string", and all the backslashes of the string are printed.

>>> Print (R' That is Carol \'s cat .')

That is Carol \'s cat.

19. Delete blank space: Method rstrip () Right lstrip () left strip () on both sides

20.Syntax error:It is an error that may occur from time to time. In a string enclosed in single quotes, if it contains an apostrophes, it will lead to an error. No double quotation marks.

21. Print (). The comma will be blank.

22. The pyperclip module has the copy () and paste () functions, which can send text to or receive text from the computer clipboard.

23. The string has a replace () method.

>>> A = 'abc'

>>> A. replace ('A', 'A ')

'Abc'

1.2.2 Null Value

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

1.2.3 constant

A constant is a variable that cannot be changed. For example, a common mathematical constant π is a constant. In Python, variable names in all uppercase are usually used to represent constants: PI = 3.14159265359

1.2.4 assignment

In Python, equal sign = is a value assignment statement, which can assign any data type to a variable. The same variable can be assigned multiple times and can be of different types:

A = 123 # a is an integer

Print ()

A = 'abc' # a is a string

Print ()

Assignment Statement: a, B = B, a + B

T = (B, a + B) # t is a tuple

A = t [0]

B = t [1]

1.2.5 format

There are two formats for formatting in Python: % and {} format.

'Hello, % s' % 'World'

The % operator is used to format strings. Inside the string, % s indicates replacing with a string, and % d Indicates replacing with an integer. How many %? Placeholder, followed by several variables or values. The order must be consistent.If only one%?Brackets can be omitted.Common placeholders:

% D integer

% F floating point number

% S string

% X hexadecimal integer

 

To Format integers and floating-point numbers, you can also specify whether to fill in the digits of 0 and integer and decimal places:

>>> '% 2d-% 02d' % (3, 1)

'3-01'

>>> '%. 2f' % 3.1415926

'3. 14'

If you are not sure what to use, % s will always work, and it will convert any data type to a string.

In some cases, % in the string is a common character and needs to be escaped. % is used to represent a %.

The second formatting method, format, is replaced.

1. Normal use

>>> Print ("My name is {}, I am {} years old this year". format ("Xiao Li", 20 ))

My name is Xiao Li. I am 20 years old.

2. You can also enter numbers in brackets to modify the formatting order.

>>> Print ("My name is {1}, {0} years old this year". format ("Xiao Li", 20 ))

My name is 20. This year, Xiao Li is

3. Get the variable using the key

>>> Print ("My name is {name}, I am {age} years old this year". format (name = "Xiao Li", age = 20 ))

My name is Xiao Li. I am 20 years old.

1.2.6 escape characters

Blank: any non-printable characters, such as spaces, tabs, and line breaks.

Escape Character \ can escape many characters \ t tab \ n line feed

The character \ itself must also be escaped, so the character \ represents is \

If many characters in the string need to be escaped, r'' can be used in Python to indicate that internal strings are not escaped by default:

>>> Print ('\ t \\')

\\

>>> Print (R' \ t \\')

\\\ T \\

1.3 digit 1.3.1 integer int

You can perform four arithmetic operations.

Because the computer uses binary, it is convenient to use the hexadecimal notation to represent integers. The hexadecimal notation is indicated by the 0x prefix and 0-9, a-f, for example, 0xff00, 0xa5b4c3d2,.

Division of IntegersIs accurate. In Python, there are two types of Division. One division is/, and the/Division calculation result is a floating point. Even if two integers are exactly divisible, the result is also a floating point. Another division is //, called floor Division. The Division of two integers is still an integer.

% Returns the remainder.

1.3.2 floating point float

Python calls all digits with decimals a floating point number. It is called a floating point number because the decimal place of a floating point number is variable according to the scientific notation. For example, 1.23x109 and 12.3x108 are completely equal.

For large or small floating point numbers, we must use scientific notation to represent 10 with e, 1.23x109 is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5.

1.3.3 use the str () function to avoid errors

You can use the built-in isinstance () function to check data types:

Def my_abs (x ):

If not isinstance (x, (int, float )):

Raise TypeError ('bad operand type ')

If x> = 0:

Return x

Else:

Return-x

1.4 annotations

1. The statement starting with # Is a comment, which is displayed to people and can be any content. The Interpreter ignores the comment. Each other row is a statement. When a statement ends with a colon (:), The indented statement is considered as a code block.

#......

2. Because Python source code is also a text file, so when your source code contains Chinese, when saving the source code, you must specify to save as UTF-8 encoding. When the Python interpreter reads the source code, we usually write these two lines at the beginning of the file to make it read in UTF-8 encoding:

#! /Usr/bin/env python3

#-*-Coding: UTF-8 -*-

3. comment on the document string """"""

1.5Python Zen The Zen of Python, by Tim Peters

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.