Python - 3.6 first day of learning

 

before the start

Basic example

The basics of Python syntax, the python syntax is relatively simple, and the compression method is adopted.

# print absolute value of a integer
a = 100
if a >= 0: print(a) else: print(-a)

It can be seen that comments start with # , python variables do not need any prefixes, and line endings do not need ending symbols, which is very in line with our natural language reading and writing habits. A :condensed statement is considered a block of code when it ends with a statement.

Python is case-sensitive, and this requires special attention.

input and output

Python can use the input() function to read user input and print() to output to the screen. By default, the input is of character data type.

type of data

integer

Python can handle integers of any size, and the representation in the program is exactly the same as the mathematical way of writing, and 0xff00the hexadecimal can be represented in the same way.

Use / to perform division in Python, and the result is a floating point number. Use // for division, and the result is an integer. Use % to take the remainder.

floating point number

Floating-point numbers are decimals, which can be expressed in mathematical notation, such as: 1.23, -9.01, or in scientific notation, such as: 1.23e9, 1.2e-5.

string

A string is any text enclosed in ` or " . You can use * to escape special characters. You can use the form of r'' to indicate that the internal string is not escaped by default. For the newline in the string, etc. The content of the line can be in the form of '''...''' , and r* can also be added before the multi-line characters .

In the latest Python 3 version, strings are encoded in Unicode, that is, Python strings support multiple languages. For the encoding of a single character, Python provides the ord() function to obtain the integer representation of the character, and the chr() function to convert the encoding to the corresponding character. The str expressed in Unicode can be encoded into the specified bytes through the encode()>>> 'ABC'.encode('ascii’) method, such as: . Conversely, if we read a stream of bytes from the network or disk, the data read is bytes. To turn bytes into str, you need to use the decode() method

In Python, the format used is the same as in C, as follows:
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)

Boolean value

Boolean: True , False . It can also be expressed in Boolean algebra: 3 > 2 ,* 3 < 2 . Operators for Boolean values: and , or , not*.

null

A null value is a special value in Python, represented by None .

variable

Variables in Python are dynamic variables, that is, the attributes of variables are determined at the time of assignment. The variable name must be a combination of uppercase and lowercase English, numbers and *_*, and cannot start with a number. There is no concept of constants in Python, and variables in all uppercase are usually used to represent constants.

list list

A list is an ordered collection to which elements can be added and removed at any time. The element at each position in the list is accessed by index, which starts at 0. When the index is out of range, Python will report an IndexError error. If you want to get the last element, in addition to calculating the index position, you can also use -1 as the index to get the last element directly.

>>> classmates = [‘Michael’,’Bob’,’Tracy'] >>> classmates [‘Michael’,’Bob','Tracy’] >>> len(classmates) 3 >>> classmates[0] ‘Michael’ >>> classmates.append('Adam’) #追加元素到末尾 >>> classmates ['Michael', 'Bob', 'Tracy', 'Adam’] >>> classmates.insert(1, 'Jack’) #追加元素到指定位置 >>> classmates ['Michael', 'Jack', 'Bob', 'Tracy', ‘Adam’] >>> classmates.pop() #删除末尾的元素,使用pop(i)可以删除指定位置的元素 'Adam' >>> classmates ['Michael', 'Jack', 'Bob', 'Tracy']

tuple tulp

Tulp tulp is   also an ordered list, the difference from list is that once initialized, it cannot be modified. There are no append, insert and other methods.
tulp is defined as follows:

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

The elements of the tulp itself cannot change, but if the element is a list, the contents of the list are mutable.

dictionary dict

The full name of dict is dictionary, which is called map in other languages. In PHP, it is actually Array. It is stored in the way of key-value (Key-Value) and has extremely fast search speed. Usage example

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} #dict的定义 >>> d['Michael’] #dict取值的方式 95 >>> d['Adam'] = 67 #dict设置新值的方式 >>> 'Thomas' in d #判断key是否存在 False >>> d.get('Thomas’) #get方式取值,如果不存在则返回None >>> d.get('Thomas',-1)#指定不存在时的返回值 -1 >>> d.pop('Bob’) #删除某个key 75

set

Similar to dict, set is also a collection of keys, but does not store value. The following example:

>>> s = set([1, 2, 3]) #初始化时提供一个list作为输入集合 >>> s {1, 2, 3} >>> s.add(4) #使用add方法添加元素 >>> s {1, 2, 3, 4} >>> s.remove(2) #使用remove方法 >>> s {1, 3, 4}

A set can be regarded as a collection of unordered and non-repetitive elements in a mathematical sense. Therefore, two sets can perform operations such as intersection and union in a mathematical sense.

control statement

Conditional judgment

Conditional judgment is relatively simple, mainly don't forget to write :, look at the example.

>>> age = 3 >>> if age >= 18: ... print('your age is', age) ... print('adult') ... else: ... print('your age is', age) ... print('teenager') ... your age is 3 teenager

More conditional judgments.

>>> age = 3 >>> if age >= 18: ... print('adult') ... elif age >= 6: ... print('teenager') ... else: ... print('kid') ... kid

cycle

There are two kinds of loops in Python, one is the for...in loop, which iterates over each element in the list or tulp in turn.

>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy'] >>> for name in classmates: ... print(name) ... Michael Jack Bob Tracy

The second kind of loop is the while loop. As long as the conditions are met, it will continue to loop, and when the conditions are not met, it will exit the loop.

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

To break out of the loop , you can use  break to break  out of the loop.
To skip this cycle , you can use  continue  to skip this cycle and continue to the next cycle.

function

Call functions

There are many functions built into Python that can be called directly. In interactive mode, you can help(abs)view the usage of the function by looking at it.

define function

In Python, to define a function, you need to use a defstatement. Write the function name, parentheses, parameters in parentheses, and colon: in turn. Then, write the function body in an indented block, and the return value of the function is returned with a returnstatement. If there is no return statement, the function will return the result after execution, but the result is None. return None can be shortened to return.

An example is as follows:

def my_abs(x): if x >= 0: return x else: return -x

When defining functions in the Python interactive environment, pay attention to the prompts that Python will present. After the function definition ends, you need to press Enter twice to return to the >>> prompt.

return multiple values

In other languages, generally only one value or an array or object can be returned. In Python, multiple values ​​can be returned through tulp.

import math

def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny >>> x, y = move(100, 100, 60, math.pi / 6) >>> print(x, y)

Syntactically, the parentheses can be omitted when returning a tuple, and multiple variables can receive a tuple at the same time and assign the corresponding value by position. Therefore, Python's function returning multiple values ​​is actually returning a tuple, but it is more convenient to write.

positional parameters

Python's function definition is very simple, but it is very flexible. In addition to the required parameters that are normally defined, default parameters, variable parameters and keyword parameters can also be used, so that the interface defined by the function can not only handle complex parameters, but also simplify the caller's code.

def power(x): #x 就是一个位置参数 return x * x def power(x, n): #x,n都是位置参数 s = 1 while n > 0: n = n - 1 s = s * x return s def power(x, n=2): #x,n都是位置参数,n设置了默认值 s = 1 while n > 0: n = n - 1 s = s * x return s

There are a few points to pay attention to:
First, the required parameters are first, and the default parameters are last, otherwise the Python interpreter will report an error.
Second, when the function has multiple parameters, put the parameters with large changes in the front, and the parameters with small changes in the back. . Parameters with small changes can be used as default parameters.
When there are multiple default parameters, the default parameters can be provided in order when calling. It is also possible to provide some default parameters out of order. When some default parameters are provided out of order, the parameter names need to be written.
It should be noted that the default parameter must point to an immutable object!

variable parameter

def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum

Defining a variable parameter is compared to defining a list or tuple parameter by simply prefixing the parameter with a *number. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when calling this function, you can pass in any number of parameters, including 0 parameters. Python allows you to add a * sign in front of a list or tuple to turn the elements of the list or tuple into variable parameters.

keyword arguments

Keyword arguments allow you to pass in zero or any number of arguments with parameter names, and these keyword arguments are automatically assembled into a dict inside the function.

def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw)

What are keyword arguments for? It can extend the functionality of the function. For example, in the person function, we are guaranteed to receive the two parameters name and age, but if the caller is willing to provide more parameters, we can also receive them. Imagine that you are doing a user registration function. Except for the user name and age, which are required, the others are optional. Using keyword parameters to define this function can meet the registration requirements.

#可以先组装出一个dict,然后,把该dict转换为关键字参数传进去
>>> extra = {'city': 'Beijing', 'job': 'Engineer'} >>> person('Jack', 24, city=extra['city'], job=extra['job']) name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'} #简化的写法 >>> extra = {'city': 'Beijing', 'job': 'Engineer'} >>> person('Jack', 24, **extra) name: Jack age: 24 other: {'city': 'Beijing', 'job': ‘Engineer'}

extra means to pass all the key-values ​​of the extra dict into the kw parameter of the function with keyword parameters, kw will get a dict, note that the dict obtained by kw is a copy of extra, changes to kw will not affect the function extra.

named keyword arguments

If you want to limit the names of keyword arguments, you can use named keyword arguments, for example, only accept city and job as keyword arguments. The functions defined in this way are as follows. Named keyword arguments require a special separator *, *and arguments that follow are treated as named keyword arguments.

def person(name, age, *, city, job): print(name, age, city, job) >>> person('Jack', 24, city='Beijing', job='Engineer') Jack 24 Beijing Engineer

If there is already a variadic parameter in the function definition, the following named keyword parameters no longer need a special delimiter *.

def person(name, age, *args, city, job): print(name, age, args, city, job)

parameter combination

To define a function in Python, you can use required parameters, default parameters, variable parameters, keyword parameters and named keyword parameters, all of which can be used in combination. Note, however, that the order of parameter definitions must be: required parameters, default parameters, variadic parameters, named keyword parameters, and keyword parameters.

Reference:
Liao Xuefeng's Python tutorial

Guess you like

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