Python3.5 Beginner Notes

I have studied C, C#, Java and other courses before, and am amazed at the simplicity of python. [laughs]
Just starting to learn, take some notes.
Since python3.0 finally adopts Unicode encoding by default, in order to avoid the problem of garbled characters, first set the encoding to UTF-8 in the compiler, and add the reference tutorial at the beginning of each .py. The
reference tutorial comes from "Liao Xuefeng's official website" http:/ /www.liaoxuefeng.com/

# -*- coding:utf-8 -*-

Python is a dynamic language, case-sensitive, no need to specify variable data type, unlimited size of integer data, ""'' means all strings.

a = 123 # a是整数
print(a)
a = 'ABC' # a变为字符串
print(a)

r'\\', use r' ' to ignore escape characters, use "'..."' to indicate newline, same as '\n'. Such as "'line1...
line2...line3"'. Boolean values ​​can be operated on with and or not.

if age >= 18:
    print('adult')
else:
    print('teenager')

An empty value is None. In python, constants are not guaranteed, like PI = 3.14 is still a variable. str represents the string type, and the bytes type is represented by b. Encode and decode as follows.

>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

The len() function calculates the length, such as print(len('Hello world!')). In the non-command line, print() is used for output.
The format of the statement is similar to the C language.

print('I am %s',%(HB))
name = 'HB' 
print('I am %s',%(name))
n = input('Please input the animal!')
y = (int) input('Please input the age!')
print('There is a %s and it is %d years old',%(n,y))       

list and tuple
list A list is an ordered data type, similar to an array.

names = ['HB','NN','CH']
//求个数
len(names)
//由指定索引得出
names[0]
//还可以倒数
names[-1],name[-2]等等,当然要注意下标越界。

List has insert(index,"), append("), pop()/pop(index), namely insert, append, delete methods. The data type in the list can be different, or it can be another list

 s = ['python', 'java', ['asp', 'php'], 'scheme']

Tuple is similar to list, but tuple cannot be modified once initialized, try to use tuple instead of list, the code is safer. Tuple naturally does not have methods such as insert.

tuple = (1,2,3)
//空tuple
tuple = ()
//注意,定义一个元素的tuple时,要使用" , "避免歧义
tuple = (1,)
//注意,当tuple中有list时,list可变
tuple = (1,2,[4,5])
tuple[2][0] = 1
tuple[2][1] = 3

结果为 tuple = (1,2,[1,3])

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683259&siteId=291194637