Python tutorial 1:python basic data types and variables, strings, and encodings

Source: Internet
Author: User

Video link:

I am playing Python under Linux, Linux is installed by default Python, directly to a pyhon3, Python case sensitive

Let's write the first simple Python program.

# !/usr/bin/env Python3 Print ("HelloWorld")

How does it work? Some say yes./Run, however I tried not to .... That's fine.

Python name.py

  

Print can also output more than one string, separated by, to display the content is a space

# !/usr/bin/python Print ('1'2'3')

The result is

1 2 3

  

We can calculate the numbers.

# !/usr/bin/python Print ('+ + =', 100 + 200)

In Python, single and double quotes are the same, so the single quote is the string, and the result is

100 + 200 = 300

Input and output

Name=input (' pleaseenter your name:')print('Hello ', name)                       #变量可以print出来也可以直接打个变量名


Indent in

A =if a >= 0:        # ends with: The following indented statement is the code block    print(a)      #  Watch out! Indent is best 4 spaces else    :Print(-a)

Data type

1. int integer

2. Float type float

3. Any text with a string enclosed in single or double quotation marks, \ can escape characters

4. The Boolean value is either True or false note the case!!! and or non-

5. Null values are represented by none

Escape character \

Print ('\\\t\\') \        Print (R'\\\t\\')      # The front plus an R is not escaping \\\t\\

Variable

The variable name must be a combination of case English, numeric, and _, and cannot start with a number

A=1                    # variable A is an integer t_001='T007'      # variable t_007 is a string answer=true      #

In Python, variables are divided into dynamic and static languages

# Dynamic Language, which is the variable itself type is indeterminate  #  A is an integer print'ABC'#  a becomes a string  Print(a)
# static language, variable type has been specified  = 123;  "ABC"; Error: Cannot assign string to integer variable

Let's do an exercise.

' ABC '      #创建了字符串 ' abc ' and variable A, and point A to ' abc '= a   'XYZ'print (b)

Q: What is the value of B?
The answer is ' ABC '

Division

There are two types of division in Python

/Division calculation result is floating point number

>>> 9/33.0

In addition to the floor, the result is an integer

>>> 10//33

% Calculation of remainder

>>> 10% 31

Strings and encodings

ASCII code only supports English

GB2312 Support Chinese

.... Support.....

What about the chaos in hundreds of languages around the world? Unicode encoding standards come into being, all languages are supported, but there are drawbacks ,and Unicode encoding requires more storage space than ASCII encoding, which is not cost-effective in storage and transmission. So there's the UTF-8 code.

A Python string

In Python version 3, strings are encoded in Unicode, meaning that Python strings support multiple languages

Print (' str containing Chinese') contains the Chinese str

For the encoding of a single character, Python provides an ord() integer representation of the function to get the character, and the chr() function converts the encoding to the corresponding character

>>> Ord ('A')65>>> ord (' Middle ') 20013>>> chr'B'>>> chr (25991) ' text '

Python bytes uses a b prefixed single or double quotation mark for data of the type to be aware of the distinction ‘ABC‘ and the former, b‘ABC‘ str although the content is displayed as the former, but bytes each character occupies only one byte

x = b'ABC'

The str pass method, expressed in Unicode encode() , can be encoded as specified bytes , for example:

#Plain English strings can be encoded using ASCII as bytes>>>'ABC'. Encode ('ASCII') b'ABC'#Chinese strings can be encoded using Utf-8 as bytes>>>'English'. Encode ('Utf-8') b'\xe4\xb8\xad\xe6\x96\x87'#Chinese strings will be error-coded using ASCII because they do not support>>>'English'. Encode ('ASCII') Traceback (most recent): File"<stdin>", Line 1,inch<module>Unicodeencodeerror:'ASCII'Codec can'T encode characters in position 0-1: Ordinal not in range (+)

Conversely, if we read the byte stream from the network or disk, then the data read is bytes . To turn bytes str it into, you need to use the decode() method:

>>> b'ABC'. Decode ('ascii')'  ABC'>>> b'\xe4\xb8\xad\xe6\x96\x87'. Decode ('utf-8')' Chinese '

Len () function

#calculate how many characters a string contains>>> Len ('ABC')3>>> Len ('English')2#calculate the number of bytes in a bytes>>> Len (b'ABC')3>>> Len (b'\xe4\xb8\xad\xe6\x96\x87')6>>> Len ('English'. Encode ('Utf-8'))6

Because the Python source code is also a text file, so when you include Chinese, you must use UTF-8 encoding when encoding, in order to do so, we usually write two lines at the beginning of the file

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

It's also important to note that in your Python text editor It's best to change the code to Utf-8.

Formatting

' Hello,%s ' '  World ' ' Hello, World ' ' Hi,%s, you have $%d. ' % ('Michael', 1000000)'Hi, Michael, you Have $1000000. '

' %2d-%02d ' % (3, 1)'  3-01'%.2f' % 3.1415926'  3.14'

Sometimes, % what about a normal character inside a string? This time you need to escape and use it %% to represent a%

' growth rate:%d percent ' % 7'growth rate:7%'

Python tutorial 1:python basic data types and variables, strings, and encodings

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.