Python3 Learning-Basics

Source: Internet
Author: User

1. Run the. py file directly

It's not working on windows, but it's OK on Mac and Linux by adding a special comment to the first line of the. py file:

# !/usr/bin/env Python3 Print ('helloWorld')

Then, pass the command to hello.py to execute the permissions:

$chmod a+x hello.py

2. Enter

Name=input ()

Input () can display a string to prompt the user:

Name=input ('pleaseenter your name')

The data type returned by input () is STR, which is converted to an integer using int ().

3. Escape character

If ' is a character, then you can enclose it with '.

If the string contains both ' and contains ', it can be identified by the escape character \. Like what:

' I \ ' m \ "Ok\" '

To simplify, Python allows strings that are inside the "R" to be not escaped by default.

"..." means multiple lines of content

4.//means that the floor is removed, only the integer portion of the result is taken.

5. Now the computer Universal character encoding works: In computer memory, Unicode encoding is used uniformly, when the need to save to the hard disk or need to transfer, it is converted to utf-8 encoding. The Ord () function gets the integer representation of the character, and the Chr () function converts the encoding to the corresponding character.

If you know the integer encoding of the character, you can also write the str in hexadecimal:

' \u4e2d\u6587 ' ' Chinese '

The two formulations are completely equivalent.

Because Python's string type is str, it is represented in memory in Unicode and a character corresponds to several bytes. If you want to transfer or save to disk on the network, you need to turn str into bytes in bytes. Python uses single or double quotation marks with a B prefix for data of type bytes:

X=b'ABC'

Be aware of the distinction ‘ABC‘ and the b‘ABC‘ former is str that although the content is displayed in the same way as the former, bytes each character occupies only one byte.

The STR represented in Unicode can be encoded as a specified bytes by using the Encode () method, for example:

'ABC'. Encode ('ASCII')'English'. Encode ('Utf-8')'English'. Encode (' ASCII') B ('ABC') B ('\xe4\xb8\xad\xe6\x96\x87') Error

Pure English str can be ASCII encoded as bytes , content is the same, containing Chinese str can be UTF-8 encoded as bytes . strcannot be encoded in Chinese ASCII because the range of Chinese encoding exceeds the range of the ASCII encoding, and Python will make an error.

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 '

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

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

6. Formatting

' hell0,%s' World 'hello,%s and you had $%d' % (  'Michael', 1000)

%d%f%s%x

formatting integers and floating-point numbers can also specify whether to complement 0 and the number of digits of integers and decimals:

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

Percent escaped, which represents a%

7.list Delete the element at the specified position, using the pop (i) method:

Classmates.pop (1)

I is the index position.

To replace an element with another element, you can assign a value directly to the corresponding index position:

classmate[1]='Sarah'

The data type in the list can be different, and the element in the list can be another list. At this point, the list containing the list can be viewed as a two-dimensional array.

8.tuple

Another ordered list is called a tuple: a tuple. The tuple and list are very similar, but the tuple cannot be modified once it is initialized.

classmates= ('Michael','Bob','Tracy  ')
t= (1)

The above code defines not a tuple, but a number. To eliminate ambiguity:

t= (1,)

When a tuple contains a list, the elements in the list can be changed, but the pointer to the list in the tuple is not changeable.

9.if x If x is a non-0 value, a nonempty string, or a non-empty list, it can be judged as true.

10.dict calculates the storage location of value based on key, the hash algorithm, so the object of key cannot be changed, and list cannot be a key.

11.set is a collection of keys and does not store value. Add () remove (). It can be regarded as a set of disordered and non-repeating elements in mathematical sense, which can be used to make the intersection and set operation in mathematical sense:

S1=set ([S2])=set ([2,3,4]) S1&s2s1|s2

12. If you want to define an empty function that does nothing, you can use the PASS statement.

def NOP ():     Pass

passWhat's the use of a statement that doesn't do anything? passit can actually be used as a placeholder, like the code that's not yet ready to write the function, so you can put one pass in place so the code can run. The pass can also be used in other statements:

if age>=18:    Pass

13. Check the parameter types:

if  not isinstance (x, (Int,float)):     Raise TypeError ('badoperand type')

14. The return value of a function is actually a tuple, and multiple variables can receive a tuple at the same time, assigning the corresponding value by location.

15. The default parameter must point to the immutable object, l=[], as list, is a mutable object that remembers the list before each call.

16. Define variable parameters.

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

If you already have a list or tuple, call a mutable parameter:

nums=[1,2,3]calc (*nums)

Indicates that all elements of the Nums list are passed in as mutable parameters.

17. Keyword Parameters

The keyword parameter has the function of extension function.

extra={'City ':'Beijing','job' :'Engineer'}
Person (' Jack ', 24,**extra)

**extraIt means that extra all the key-value of this dict are passed into the function parameters with the keyword argument **kw , and kw a dict is obtained, the kw dict is a extra copy kw of the Changes do not affect the outside of the function extra .

18. Named keyword parameters

For the keyword argument, the caller of the function can pass in any unrestricted keyword argument. As for what is passed in, it needs to be checked inside the function kw .

Still taking the person() function as an example, we want to check if there are city job arguments:

defPerson (name, age, * *kw):if ' City' inchKW:#There are city parameters        Pass    if 'Job' inchKW:#have job parameters        Pass    Print('Name:', Name,'Age :', Age,'Other :', kw)

If you want to restrict the name of the keyword parameter, use the named keyword parameter:

def person (name, age, *, City, Job):    Print(name, age, city, job)

Unlike keyword Parameters **kw , a named keyword parameter requires a special delimiter * , and * subsequent arguments are treated as named keyword parameters.

The method is called as follows:

Person ('Jack', city= 'Beijing', job=' Engineer '  Beijing Engineer

If there is already a mutable parameter in the function definition, then the named keyword argument that follows will no longer need a special delimiter * :

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

The named keyword argument must pass in the parameter name, which differs from the positional parameter. If the parameter name is not passed in, the call will error.

19. Parameter Combinations

The order of the parameters definition must be: Required parameter, default parameter, variable parameter, named keyword parameter, keyword parameter

defF1 (a,b,c=0,*args,**kw):Print('a='A'b='B'c='C'args=', args,'kw=', kw)defF2 (a,b,c=0,*,d,**kw):Print('a='A'b='B'c='. cn'd='D'kw=', kw)

At the time of the function call, the Python interpreter automatically passes the corresponding parameters according to the parameter location and argument name:

F1 (1, 2) A= 1 b = 2 c = 0 args = () kw ={} f1 (1, 2, c=3) A= 1 b = 2 c = 3 args = () kw ={}f1 (1, 2, 3,'a','b') A= 1 b = 2 c = 3 args = ('a','b') kw ={} f1 (1, 2, 3,'a','b', x=99) A= 1 b = 2 c = 3 args = ('a','b') kw = {'x': 99} f2 (1, 2, d=99, ext=None) A= 1 b = 2 c = 0 d = HP = {'ext': None}

The above functions can also be called through a tuple and dict:

args = (1, 2, 3, 4) kw= {'D': 99,'x':'#'}f1 (*args, * *kw) a= 1 b = 2 c = 3 args = (4,) kw = {'D': 99,'x':'#'}args= (1, 2, 3) kw= {'D': 88,'x':'#'}f2 (*args, * *kw) a= 1 b = 2 c = 3 D ='x':'#'}

For any function, it can be called in a similar func(*args, **kw) manner, regardless of how its arguments are defined.

*argsis a variable parameter, and args receives a tuple;

**kwis a keyword parameter, kw receives a dict.

20. The method of resolving recursive call stack overflow is optimized by tail recursion. Tail recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion, so that the recursive itself, regardless of the number of calls, only occupy a stack frame, there is no stack overflow situation.

def fact (N):     return fact_iter (n, 1)def  fact_iter (num, product):    if num = = 1: c10/>return  product    return fact_iter (num-1, num * product)

Python3 Learning-Basics

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.