Liao Python Study notes one

Source: Internet
Author: User

1. Liao Python Study notes

Large classifications such as functions with level two headings, below with three levels such as input and output

1.1.1. Input Output 1.1.1.1. Output

Use print () to add a string to the parentheses to output the specified text to the screen.
The print () function can accept multiple strings, separated by commas (,) , and sequentially output
A comma is encountered to output a space.

1.1.1.2. Input

Provides an input () that allows the user to enter a string and store it in a variable.

name = input()print(name)
1.1.2. Variables

It is the use of the basic knowledge of algebra learned in junior high school mathematics.

  • Integers (integer): negative, positive (without decimal points)
  • Floating point (float): With decimal point
  • String: Any text enclosed in single quotation mark ', double quotation mark ', single quote is also text, requires double quotation marks, double quotation marks need to be added.
  • Multi-line string, with "...", need to escape more, can take advantage of R ', means that the internal string is not escaped by default
  • Boolean (BOOL): A Boolean value of only true false two values
  • Null (none): With none, just a special null value
  • Variables: concepts are basically consistent with the equation variables of practice algebra.
  • The remainder operation 1.1.3. Strings and encodings

    character encoding :
    ASCII, UTF-8, Unicode
    string :

  • Ord gets the integer representation of the character
  • The CHR function converts the encoding to the corresponding character

Formatting:

Output format string: Implemented in % , inside string:%s%d%f, outside with% boot multiple variables

print(‘%2d-%02d‘ % (3, 1))print(‘%.2f‘ % 3.1415926)#----------3-013.14

Another format is formatted with Format ()

‘Hello, {0}, 成绩提升了 {1:.1f}%‘.format(‘小明‘, 17.125)#---‘Hello, 小明, 成绩提升了 17.1%‘
1.1.4. Use list and tuple1.1.4.1. List

A data type built into Python is a list:
List is an ordered set of elements that can be added and removed at any time

>> s = [‘python‘, ‘java‘, [‘asp‘, ‘php‘], ‘scheme‘]>> len(s)4
1.1.4.2. Tuple

Another ordered list is called a tuple: tuple
Tuples cannot be modified by one amount of initialization
Defined form: t = (t=) or t= (1,)--an element followed by a comma

1.1.5. Condition Judgment

Do not write fewer colons (:)

if &lt;条件判断1&gt;:<执行1&gt;elif &lt;条件判断2&gt;:<执行2&gt;elif &lt;条件判断3&gt;:<执行3&gt;else:<执行4&gt;
1.1.6. Loops
  • For
  • While
  • Break continue
1.1.7. Use Dict and Set1.1.7.1. Dict

Python built-in sub-dictionary: dict support, dict full name Dictionary
Use the health-value (Key-value), with extremely fast search speed
Dict has the following features:

  • Find and insert very fast and do not increase as key increases
  • Takes up a lot of memory and consumes more memory
    &gt;&gt; d = {‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85}&gt;&gt; d[‘Michael‘]95
#### 1.1.7.2. Set>set和dict类似,也是一组key的集合,但不存储value,同于key不能重复,值是唯一的```python>>> s = set([1, 1, 2, 2, 3, 3])>>> s{1, 2, 3}

Operation Method:

    • Adding Add (Key)
    • Delete Remove (key)
1.1.8. Functions

Python not only has the flexibility to define functions, but it has built in many useful functions that can be called directly

1.1.8.1. Abstraction

Abstraction : A very common concept in mathematics
Call to function
Built-in functions, direct call can be, just need to know the function name and parameters , to interact with the command line through Help (function name) to see the functions of the helper information

1.1.8.2. Data type Conversions

The built-in common functions include type conversion functions such as int (),

1.1.8.3. Defining functions

Define a function to use the def statement, write down the function, the parentheses, the arguments in parentheses, and the colon (:), and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.

#coding:utf-8def my_abs(x):if x &gt;= 0:return xelse:return -x#调用print(my_abs(-99))

Note:
When the statement inside the function body executes, once it executes to the return statement, the function is executed and the result is returned

1.1.8.4. Empty functions

You want to define an empty function that doesn't do anything, you can use the PASS statement

   def nop():       pass

Summary

When defining functions, it is necessary to determine the number of function names and parameters ;
If necessary, the data type of the parameter can be checked first;
The function body can return the function result at any time with return;
Automatically return none when the function has finished executing and there is no return statement.
A function can return multiple values at the same time, but is actually a tuple.

1.1.8.5. Parameters of the function

When defining a function, we determine the name and position of the parameter, and the interface definition of the function is completed.
For the caller of the function, just know how to pass the correct arguments, and what values the function will return is enough

Position parameters
def power(x, n=2):s = 1while n &gt; 0:n = n - 1s = s * xreturn s

To set the default function, pay attention to the following points:

  • The first is the required parameter before the default parameter is
  • The second is how to set the default parameters
Variable parameters

To define a mutable parameter and define a list or tuple parameter, just precede the argument with an * number

Keyword parameters

Variable parameters allow you to pass in 0 or any of these parameters, which can be automatically assembled into a tuple when the function is called.
The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict

Named keyword parameters

For the keyword argument, the caller of the function can pass in any unrestricted key parameter.

Summary
Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.
Default parameters must be used immutable objects, if it is a mutable object, the program will run with a logic error!
Be aware of the syntax for defining mutable parameters and keyword parameters:
*args is a variable parameter, and args receives a tuple;
**KW is the keyword parameter, and kw receives a dict. Learn
And how to pass in the syntax for variable and keyword arguments when calling a function:
Variable parameters can be passed directly: Func (1, 2, 3), or the list or tuple can be assembled first, and then passed through args: Func ((1, 2, 3));
Keyword parameters can be directly passed in: Func (A=1, b=2), can be assembled dict, and then passed through **kw: func (**{' a ': 1, ' B ': 2}).
Using *args and **kw is a Python idiom, but it can also be used with other parameter names, but it's best to use idioms.
The named keyword parameter is used to limit the name of the parameter that the caller can pass in, as well as providing a default value.
Define a named keyword parameter do not forget to write the delimiter * If there is no mutable parameter, otherwise the definition will be the positional parameter.

Recursive functions

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function

def fact(n):if n==1:return 1return n * fact(n - 1)

Call Procedure:
===> Fact (5)
===> 5 Fact (4)
===> 5
(4 fact (3))
===> 5
(4 (3 fact (2)))
===> 5 (4 (3 (2 fact (1))))
===> 5 (4 (3 (2 1))
===> 5 (4 (3 2))
===> 5
(4 6)
===> 5
24
===> 12

小结使用递归函数的优点是逻辑简单清晰,缺点是过深的调用会导致栈溢出。

Liao Python Study notes one

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.