Little Turtle Python3 Notes

Source: Internet
Author: User
Tags assert function definition iterable shallow copy



000-Happy Start



Easy to get started, hard to learn, less code.



Cross-platform: Windows, Mac OS, Linux, UNIX.



  Application area: Operating system WEB 3D Animation enterprise Application cloud computing and so on.



001-My first intimate contact with Python



1. Installation
2. IDLE is a python Shell: a way to interact with a program by typing text.
3.print (' text '), print (5+3), print (123+456), print (' Test ' + ' text '), print (' Test ' * 8), print (' Test \ n ' * 8)
4. Previous Statement shortcut key: ALT + P Next Statement shortcut: ALT + N



002-Design The first game in Python



1. In the idle Ctrl + N create a new editor
2. Write a small game of guessing numbers
3.Tab: Indentation and completion
4.Ctrl + S Save
5. Press F5 to run
6. Indentation is important! There is a colon at the end, and the return is automatically indented.
7. An equal sign is an assignment, and a two equal sign is the judgment equals.
8. Flowchart
9.BIF = = buile-in functions built-in function
10. How many built-in functions are in idle: Dir (__bulitins__)
11: Help (Bif_name)



003-Variables and strings



1. Variable names like our real-world name, when assigning a value to a name, TA is stored inside, called a variable (variable), which in most languages is referred to as "assigning values to variables" or "storing values in variables".
But unlike most other computer languages, Python does not store values in variables, but rather puts names on top of values. So some python programmers would say that Python has no "variables", only "names".
2. Variables can be calculated:



f = 3



s = 8



T = f + S



Print (t)



–> 11



It's also possible to change strings.



3. Places to note when using variables:



(1) Before using the variable, you need to assign a value to the its first.
(2) Variable names can include letters, numbers, and underscores, but variable names cannot begin with a number.
(3) Letters can be uppercase or lowercase, but the case is different.
(4) the equal sign (=) is the meaning of the assignment, is to assign the right value to the left variable name, cannot write the inverse
(5) The variable name theory can take any legal name, but try to take a professional point name:
4. The string we recognize is everything in quotation marks, and we also call the string text. Text and numbers are different.



5. To create a string, enclose the character in quotation marks, either single or double quotes, but must appear in pairs.
6. Escape symbol with \–> ' let\ ' s go! '
7. However, to print the ' c:\now ' file path, you can use ' C:\\now ', which is escaped with escape, but this method if there are a lot of \ is inconvenient
8. For the above problem, we can use the original string is the method of R ' Test ', but note that the original string is the most behind is not add \ The solution is what (I think it can be a character splicing)
9. Long string: To get a text that spans multiple lines, you can use three quotation marks.
10. Symbols must be in English punctuation.
004-Improved mini-games
1. When wrong, the program should give tips
2. Can only guess once, should have more opportunities
3. Each time you run the program, the answer can be random
4. Conditional branching
(1) comparison operator:;, >=, <, <=, = =,! = Reverse true or false compare operators around to add spaces
(2) Branch syntax:
If condition:
Operation performed with Condition True (true)
Else
Action performed on condition False (false)
5.while Cycle
(1) While condition:
The condition is true (true) action performed (for example: while guess! = 8:)
(2) Do not forget the colon and indent.
(3) True if the and logical operators are true at the same time
6. Introduction of Foreign aid: random Module
(1) Each program we write is actually a module
(2) A function called Randint () in the random module returns a random integer.
Example: Random.randint (1,10) generates a random integer from one to 10.
(3) Importing import random



005-Data type



1. String Operations will stitch strings
2. Integral type: Python3 integral type and long integral type and together, the length is unrestricted. The Python2 is separate.
3. Floating-point type: is a decimal, the difference is there is no decimal point
4.E notation: Is the number of scientific methods (positive or negative is to small is to the big)
A = 0.000000000025
A–> 2.5e-11
b = 150000000000
B–>1.5e11
5.. Boolean type: is a special type of integer. True Fales can be used as 0 and 1 can also be calculated.
True +true = 2
True+false = 1
True*false = 0
True/false will error, 0 can not be a divisor
But generally not to calculate.



I. How to convert each other?
With Bif:int () str () float ()
Int (): Converted to an integer, a = ' 520 ' b = Int (a) b–> 520
You can also convert a floating-point type to an integer, but Python will cut back the number directly and will not be rounded off.
You cannot use the a= ' string ' to convert int



float:a = ' 520 ' or a=520 b = Int (a) b–> 520.0



STR (): Converts to a string.



You cannot use BIF as the variable name.



Two. How to obtain the type of information (judging)
Type (): The content to be judged in parentheses. Returns the type in parentheses.



Isinstance (): There are two parameters one is used to determine the variable, and one is to determine the type of
It returns a Boolean value if it is true and vice versa is Flase
A = ' string '
Isinstance (A,STR)
–> True



Isinstance (123456,STR)
–> Float



More recommended with Isinstance ()



006-Common operators
+: A= a+3 can be written to do a+=3 | b = 3 B-=1 b–> 2

*
/
%: Remainder 5%2–> 1 |11%2–>1
* *: power, i.e. how many times squared
: Floor except 10//8–> 1 | 3.0//2–>1.0



Cases:
A = b = c = d = 10–> a=10 b=10 c=10 d=10
A +=1 a–>11
b-=3 b–>7
c*=10 c–>100
D/=8 d–>1.25



Volt priority problem: The first parenthesis, first multiplication, plus minus.
-3 * 2 + 5/-2-4
–> (-3) * * + 5/(-2)-4
–> ((-3) * *) + (5/(-2))-4
Comparison operators (<,>) have higher precedence than logical operators
3<4 and 4<5
(3<4) and (4<5)
Add parentheses when necessary to increase the readability of your code.



The power operation is lower than the high ratio on the left.
-3 **2 (Normally-3 *-3 should be equal to 9)
–>-(3 * * 2)
–>-9



logical operators
And the left is true.
or left or right is true.
Not about all false is true.



Statistics:



Highest * * But with specificity
Then the sign
Then *///
Then +–
Then < > <= >= = = =!
Then not and OR



007-Branches and Loops 1



I. Composition and structure of the game (playing airplane games)
1. Enter the game is to enter a cycle: As long as not die straight out of the plane
2. Branching conditions change into another alley Hao
3. Airplanes are all the same, so all are copied by an object.
Framework:
1. Loading background music
2. Play Music single cycle
3. The birth of our aircraft



Small airplane interval variable = 0
While True
If the user points off the exit
Break



Interval + = 1
If interval = = 50:
Interval = 0
The birth of a small plane
The small plane moves one position from the top down
Screen Refresh



If User mouse moves
Required position in our aircraft = user mouse position
Screen Refresh



If we have a physical conflict with a small aircraft
We hang up and play percussion music
Modify our aircraft pattern
Print game ove
Fade out stop background music



008-Branching and looping 2



More than 90 points for a,80-90 is divided into b,60-80 for c,60 below D
Write a program when the user enters the score and automatically converts it to ABCD form for printing.



Answer: Implement with If elif else statement!



Hang else? is not possible in Python.



Conditional expressions (ternary operator, trinocular operator)
A unary operator is the number of operands of this operator.
For example A = 1 here = about two operands, so it is a two-dollar operator.
1 minus sign as a minus sign he's a unary operator.
small = x If x<y else y this is a ternary operator.
The syntax is: x if condition else y
When the condition is satisfied, the value of x is given to small, and the Y value is not given to the small immediately.



Assertion (Assert)
Assert is a keyword, called an assertion
When the condition behind this keyword is false, the program automatically crashes
and throws a Assertionerror exception
Example: Assert 3>4
In general, we can use it to go to the checkpoint in the program.
When you need to make sure that a certain condition in the program is true in order for the program
If you work properly, the Assert keyword is very useful.
Tips: This is commonly used for testing programs.



009-Branching and looping 3



While loop: The condition is true and always loops.
While condition:
Loop body



For loop, calculator loop:
For target in expression (list, tuple):
Loop body
Example:
A = ' Lvyang '
For I in A:
Print (I, end= ') # Note the Print End statement here indicates what the output ends with



num = [' A ', ' BCCC ', ' bcf ', ' dd ', ' e ', ' F ']
For each in Num:
Print (Each,len (each)



Range ():
Syntax: Range ([strat,]stop[, Step=1])
There are three parameters, two of which are enclosed in brackets, that are optional.
-step=1 indicates that the default value for the third parameter is 1. If you do not actively set up step is 1.
-rang the function of this bif is to generate a value from the start parameter to the stop parameter
The ending sequence of numbers.
Range () is often combined with for-in:
Range (5) –> range (0,5)
List (range (5)) –> [0,1,2,3,4]
Example:
For I in range (5):
Or
For I in Range (2,9):
Or
For I in range (1,10,2):–> The third parameter is the meaning of step.



Two key statements: Break and Continue
Break: Terminates the loop and jumps out of the loop body.
Continue: Stop this cycle and start the next cycle, note that it will test before starting the next round loop
The condition of the next cycle. It only starts the next cycle when the next round is true. If not,
It will exit the loop.



010-List



All types can be loaded in.
One, create a list of three ways
1. Create a general list:
member = [' xx ', ' oo ', ' dd ', ' CC ']
can also num = [1,2,3,4]
2. Create a hybrid list:
Mix = [1, ' ddd ', 3.14,[1,2,3]] You can also add a list to it.
3. Create an empty list
empty = []



Second, add elements to the list
1.append () Method: Member.append (' oooxxx ') can only add one element. Added to the tail of the list.
Len (member) –> the length of the back list
. The following is the method that belongs to the list object
2.extend () extension, extending another list with one list.
Member.extend ([' Run around ', 12345, ' Dafa Quest ') appends a list to the end of a list.
3.insert () Method: There are two parameters, the first one represents the position in the list, and the second parameter inserts the element.
Inserts an element at the position specified by the first parameter.
Member.insert (1, ' JJ ')
Position is calculated from 0, if you want to put in the first position to write 0



011-List 2
I. Get the element from the list
1.member[0] get first
Member[1] get first
The first and second elements of the member list to swap positions
Temp = member[0] Put the first element in a temporary variable
Member[0]=member[1] changes the first element to the second element
Member[1]=temp adds a temporary variable to the second element position.
Two. Remove elements from the list
1.remove ()
Member.remove (' oo ') parameter is the name of the element to delete
If no given parameter is used
2.del
It is not a list of methods, it is a statement.
Del Member[1] Removes the first element.
Del member removes the entire list.
3.pop ()
Member.pop () deletes the last element and returns the contents of the deleted element.
We can assign the contents of the Delete name = Member.pop () so that
Pop () has a parameter, Member.pop (index)
three. List slices (slice)
You need to get more than one element at a time. Get a copy of the original list
member[:]
Member[1:3]
Member[:3]
member[2:]
Member[:-1]



012-List 3
I. Comparison operators
Cases:
Ist1 = [123]
List2 = [234]
List1 > List2
Cases:
List1 = [123,456]
List2 = [234,123]
List1 > List2
Tips: The list is compared from the No. 0 element, and if the No. 0 wins it wins, regardless of the elements behind it.
Cases:
List3 = List1 = [123,456]
(List1 < List2) and (List1 = = list3) –>true
Cases:
List4 = List1 +list2
But generally do not use, generally to use list.extend () more standard.
Cases:
List1 + ' big ' –> error
The type of the object with the + number must be the same.
Cases:
List1 * 3
Cases:
List3*=3 or List3 *= 5
Cases:
123 in List3–>true
' 233 ' not in List3–>false
Cases:
What about the list of tables?
Lists = [123,[' People ', ' from '],456]
' People ' in Lists–>false
Can do this
' Person ' in lists[1]–> True
Lists[1][1]–> ' from '



Two. The list of Bif:dir can be found
1.count calculates the number of occurrences of a parameter in a list.
List3.count (123)
2.index Index, the position of the inverse parameter in the list.
List3.index (123)



The arguments that follow the List3.index (123,3,7) can specify the range you want to find.
3.reverse () flips in place.
List3.reverse ()
4.sort () Sorts the list in the specified manner.
The default is small to large
LIST6 = [4,3,2,5,9,23,32,0]
List6.sort () –> from small to large rows
Sort (reverse = false) –> List6.sort (reverse=true)
5. Copy of the list
Assignment is not equal to copy
Copy and paste, shortcut the difference.
It's easy to get errors.



013-tuple (tuple)



-Parameters inside, immutable, very similar to the list when used



1. Create: Tuple1 = (1,2,3,4,5,6,7,8)
Create an empty tuple: Tuple2 = ()
2. Access: Tuple1[1] can also tuple1[5:] or Tuple1[:5]
You can also copy a list tuple2 = tuple1[:]
3. Elements in a tuple cannot be modified
Note: temp = (1) –> temp–> type (temp) –> <class ' init ' >
To create a tuple of only one element, the inverse type is actually
Init thinks that it is a workaround variable
If you want to create a tuple with only one element, temp = (1,) or temp = 1,
Add a comma to the back of the element.



Temp2 = 2,3,4,5–> type (TEMP2) –> <class ' tuple ' >
Create variables of multiple elements, even if no parentheses get tuples



So the parentheses are not the key, and the comma is the key.



Cases:
8 * (8) –> 64
8 * (8,) –> (8,8,8,8,8,8,8,8) because it's a tuple.



4. Update and delete a tuple
temp = (' A ', ' B ', ' C ',)
temp = temp2[:2]+ (' dd ',) +temp[2:]
Tip: It is not possible to delete an element, only the above method can be used to reorganize
To delete an entire tuple, you can use the DEL statement: Del temp
Generally no del statement, because there is an intrinsic recovery mechanism
5. Tuple-related operators
+ Stitching
* Repeat
>,<
In,not in
And Or not



014-String
– slices can also be useful on strings: str1 = ' 123456789 ' –>str1[:5] can also be retrieved with an index.
– Strings and tuples cannot be arbitrarily modified, if you really want to modify them, refer to the tuples above.
– Related operators and tuple lists are basically the same


Method of String
1. captalize-the first character of uppercase
2. casefold-change the entire string to lowercase
3. Center (50)-Centers the string and fills the new string with a width of length with a space
4. Count (' str ')-find several ' str ' in the string, with optional parameters start and end
5. Encode ()
6. EndsWith (' x ')-check if it is ' x ' end, also have optional parameters start and end
7. Expandtabs ()-Converts the ' \ n ' space to tab with the default of 8 length ' (can be specified) ', as well as the optional parameter start and end
8. Find ()-detects if the contents of the parentheses are contained in the string, back to the index. Otherwise return -1,start and end
9. Index ()-Same as the Find method, but an exception is generated if the contents of the parentheses are not in the string.
Isainum ()-Returns True if the string has at least one character and all characters are letters or numbers, otherwise false
Isalpha ()-Returns True if the guest has at least one character and all characters are letters, and false if no
Isdecima ()-Returns True if the string contains only decimal digits, otherwise false
IsDigit ()-Returns True if the string contains only a number, otherwise false
Islower ()-Lowercase,
IsNumeric ()-Returns True if the string contains only numeric characters
Ispace ()-If the string contains only spaces return true
Istitle ()-Returns True if the string is a header (capitalized first letter)
Isupper ()-Returns True if the string contains at least one case-sensitive character, and the characters are uppercase.
Join (sub) – Inserts a string as a delimiter between all the characters in a sub.
Ljuest (width)-Returns a left-aligned cameo and fills it with a space to a new cameo length of width
Lower ()-converts all uppercase letters in a string to lowercase.
Lstrip ()-all spaces to the left of the string last year
Partition (sub)-found
Too many jumps ~
/T is a tab


015-String Formatting format
Example 1: ' {0} love {1},{2} '. Format (' lv ', ' ren ', ' zhen ') positional parameters
Example 2: ' {W} love {t},{y} '. Format (w= ' LV ', t= ' ren ', y= ' zhen ') keyword parameter
Example 3: ' {0} love {t},{y} '. Format (' LV ', t= ' ren ', y= ' zhen ') position and keyword, but be sure to position it before the keyword
Example 4: ' {{0} '. Format (' print ') –> {0} to print {} Use this method to escape curly braces
Example 5: ' {0:.1f}{1} '. Format (2.688, ' GB '): A colon represents the beginning of a formatted symbol, leaving a decimal rounded.
Formatting operators:
1. Formatted characters and ASCII code '%c%c%c '% (97, 98, 99):–> a B C
2. Format string '%s '% ' abc ':
3. Format integer ' d '
4. Formatting unsigned octal numbers%o
5. Formatting unsigned hexadecimal number%x
6. Formatting unsigned hexadecimal number (uppercase)%x
7. Format fixed-point number, you can specify the precision after the decimal point%f (the default is accurate to 6 bits)
8. Format fixed-point numbers with scientific notation%e
9. As with%E, the fixed-point number is formatted with scientific notation%E
10.%g depends on the size of the value to use%f or%e
11.%g action with%G depending on the size of the value is determined using%f or%e
Formatting Operations Auxiliary Commands:
M.N m is the minimum part width displayed, n is the number of digits after the decimal point%5.1f or%.2e%27.658
– For left alignment
+ Show plus sign in front of positive number
# in octal number before hundred display (' 0′) in hexadecimal number before display ' 0x ' or ' 0X ' to tell you directly how many binary
0 The number shown is preceded by 0 in place of a space.



String escape character meaning
\ ' Single quotation mark
\ "Double quotation marks
\a emits system ring tones
\b Backspace
\ n line break
\ t Horizontal tab tab
\v Portrait tab
\ r return character
\f Page Break
\o the characters represented by the octal number
\x hexadecimal number represents the character
\ s represents a null character
\ \ counter Slash



016-sequence!
1. List. The common denominator of tuples and strings
Each element can be indexed by an index
The default index value always starts at 0
May slice
There are a lot of common operators * + and so on
2. bif of the sequence
List () converts an iterative object into a table
List () empty lists
List (Iterahle) with an iterator parameter
Tuple () Converts an iterative object to a tuple
As with List ()
STR () Converts the object to a string
Len () Back length
Max () inverse of a sequence or the maximum value in a parameter if the argument is a string is a comparison of ASCII code
Min () and Max () return to minimum value
– Using the Max () and Min () methods must ensure that the data types in the parameters are uniform
SUM (iterable[,start=0]) reverse sequence iterable and optional arguments the sum of start can also be integers or floating-point numbers only
The sorted () sort is the same as the list's sort.
Reversed () has a reverse more than the list. The iterator object is reversed. Flip
Enumerate () enumeration generates tuples of indexes and values for each element [(0, ' a '), (0, ' B ')]
Zip () reversed by each parameter A = [1,2,3,4,5,6,7,8] b=[4,5,6,7,8] Zip (A, b) –>[(1,4), (2,5), (3,6), (4,7), (5,8)]
017. Lego bricks for function-python
– Function Object Module
Def myfirstfunction ():
Print (' hello.world! ')
Print (' This is the first function! ')
The runtime throws the def directly into memory, looks up when it is called, and executes. If you don't find it, you'll get an error.



Parameter function:
def mysecondfunction (name):
Print (name+ ' I love You ')
Add the parameters when you call them.



Multiple parameters separated by commas can be, support many parameters (try not to too much, write good documents)
def add (NUM1, num2):
result = Num1 + num2
Print (Result)



Function back:
return with the keyword.
def add (NUM1, num2):
Return (NUM1 + num2)



18-function is flexible and powerful (parametric)
I. Formal parameters (parameter) and arguments (argument)
1. The name in the function definition process is called formal parameter (because he is just a form that represents a parameter position)
Print (' passed in ' +name+ ' is called an argument, because he is a parameter value for Hugh. ')
2. Myfirstfunction (' hehe ')
The small turtle that passes in is called the argument, because TA is the specific parameter value.
Two. function documentation write the document to the function! will be stored as part of the function.
myfirstfunction.__doc__
You can recall the description of the function. You can also use Help () to view
Three. Keyword parameters
In order to be afraid of the mistake
def saysome (name, words):
Print (name+ ' >>> ' +words)
is to write the name of the parameter at the time of the call: Saysome (name = ", words =")
Four. Default parameters
A default value is given to the parameter when the function is defined. Name = ", words ="
The given parameter is used if the given argument.
Five. Collecting parameters (variable parameters)
Add the * number to the front of the parameter.
def test (*params): # Add the * number to give a lot of parameters
Print (' parameter length is: ', Len (params))
Print (' second parameter is: ', params[1])
!! If you want to add parameters after collecting the parameters, you will use the keyword parameter and set the default parameters for the keyword parameter.
Otherwise the parameters are entered into the collection parameters, the error will be
The first parameter of the print () bif is the Collect parameter. The following parameters also have default values



19. Functions-My turf, listen to me.
I. Functions and procedures
–python strictly speaking, only functions have no process.
def hello ():
Print (' Hello World ')
temp = Hello ()
Print (temp) –> None
Type (temp) –> class ' Nonetype '
Two. Inverse function
You can return multiple values (you can reverse a list, or you can separate a tuple with a comma).


Three. Scope of the variable (local Variable, global Variable)
1. Local Variables:
def discounts (price, rate):
Final_price = Price * Rate
Old_price = 88 # Here is an attempt to modify a global variable.
Print (' Modified Old_price value is: ', Old_price)
Old_price = float (input (' Please enter the original price: '))
Rate = Float (input (' Please enter discount ratio: '))
New_price = Discounts (Old_price, rate)
Print (the value of the modified Old_price is: ', Old_price)
Print (' Price after Discount: ', New_price)
Parameters defined within the function cannot be found outside the function, variables, functions, variables within the parameters scope are only in the function
2. Global variables
Variables defined on a polygon by a function are global variables. Their scope is the entire block of code. That is, you can also access it within a function.
Use global variables be careful not to modify global variables in Def
Because if you try to modify a global variable in a function, Python will automatically create a new local variable with the same name as the global variable (masking protection mechanism)
So it will be changed at that time, but in the outside, the re-visit will be changed before the content.
20. Functions-inline functions and closures.
I. Global keyword You can change the globals (try not to use!!!)
Two. Create another function inside the inline function function
Example
Def fun1 ():
Print (' fun1 runing .... ')
Def fun2 ():
Print (' fun2 runing .... ')
Fun2 ()
With inline functions, only fun1 can call fun2.
Three. Closures (programming paradigm) language used by genius programmers
def funx (x):
def funy (y):
Return X*y
Return Funy
i = Funx (8) –>function–> I (5) –> 40 or can also Funx (8) (5)
If in an intrinsic function a reference is made to a variable in the outer scope, then the intrinsic function is a closure.


Def fun1 ():
x = 5
def fun2 ():
X*=x
return x
return fun2 ()
is called after an error because fun2 is equivalent to changing global variables when calling X. So it's wrong. , how do I fix it?:
def fun1 ():
x = [5]
def fun2 ():
X[0]*=x[0]
return x[0]
The solution is to store the data in a container. It can be used.
There is also a keyword: Nonlocal uses the same method as above.



21. Function-lambda expression (anonymous function)
one. Lambda expression
def ds (x):
Return 2 * x + 1
can be written as: x:2*x+1
So two parameters?:
def Add (x, y ):
Return x+y
can be written as: the important role of the lambda x,y:x+y
lambda expression:
1.Python While writing some execution scripts, using lambda can save you from defining function procedures,
For example, we just need to write a simple script to manage server time, so we don't need to
define a function and then write the call, and use lambda to make the code more streamlined.
2. For some abstract and complete program execution only need to call the function one or two times,
sometimes give a function name is also a headache problem, using lambda does not need to consider the problem of
naming.
3. Simplify the readability of the code, because the normal cock silk function reading often jumps to the switch def definition section,
using the lambda function can omit such steps.
Two. Two BIF
1.filter () filter. Usage: Filter (function or None, iterable)
Example:
Filter (None,[1,0,false,true]) –> fun –>[1,true] Returns the content as true.
Filter Odd filters:
def Add (x):
return x% 2
temp = range (ten)
Show = filter (odd, temp)
List (show) –>[ 1,3,5,7,9]
The contents can be written as:
List (filter (lambda x:x%2,range))
2.map () map parameters (functions, iterations)
List (map (lambda x:x*2 , Range (ten))



22-Recursion
– Ordinary programmers use iterations, and genius programmers use recursion. (use recursion in the right place.)
– Must be mastered but not always used. It is a step that needs to be mastered but dangerous. And it consumes time and space.
–python default recursion depth is 100 layer (adjustable) import sys–> sys.setrecursionlimit (10000000)
Example:
def recursion ():
return recursion ()
Will always invoke the error
Example: (correct)
Write a function of factorial:
Non-recursive version:
def factorial (x):
result = X
For I in Range (1,x):
Result *= I
return result
Recursive version:
def factorial (x):
if n = = 1:
Return 1
Else
return n *factorial (n-1)
1. Call the function itself 2. Sets the inverse value of the function itself.



Recursive explanation:
Factorial (5) = 5 * factorial (4)
Factorial (4) = 4 * factorial (3)
Factorial (3) = 3 * Factorial (2)
Factorial (2) = 2*factorial (1)
Factorial (1) = (return)
1. Hanoi
2. Tree structure definition
3. Sierpiński Triangle.
Recursive slightly later complement



25-Dictionary 1
– The dictionary is not a sequence type, it is a mapping type. mapping, building relationships
– Keys (key)
– Values (value)
Each pair of key-value combinations is called: item
Brand = [' Li ning ', ' Anta ', ' Artie ']
slogan = [' Everything is possible ', ' keep moving', ' Impossible is nonthing ']
–>print (' Artie slogan: ' slogan[brand.index[' Artie ']] trouble
In dictionary:
Dict1 = {' Li ning ': ' Everything is possible ', ' Anta ': 'keep moving ', ' Artie ': ' Impossible is nonthing '}
Print (' Li Ning's slogan is: ', dict1[')



Dict2 = {1: ' One ', 2: ' Both ', 3: ' Three '}
–>DICT2[2]



Dict3 = {} Empty dictionary
or Dict () to create an empty dictionary
Dict () Simple usage: Dict5 = dict ((' F ', ' d '), (' C ', ' 115 '), (' s ')
Create a dictionary with a corresponding relationship.
DICT6 = Dict (Lu Yang = ' haha ') the key in front cannot be quoted



Assign a value directly to the key in the dictionary, if there is a change, if there is no creation.
dict7[' Lu Yang '] = ' haha haha haha '



26-Dictionary 2
Built-in methods for dictionaries:
1.fromkeys ()
Dict1 () = {}
Dict1.fromkeys ((+))
Dict1.fromkeys ((+), ' number ')
Dict1.fromkeys ((-), (' 1′, ' 2′, ' 3′ ') is wrong and is not automatically assigned
Dict1.fromkeys ((1,3), ' number ') wrong can not batch modify, but re-create a new dictionary
2. How to access the dictionary Key,values,items
Dict1 = Dict.fromkeys (range (32), ' likes ')
For Eachkey in Dict1.keys ():
Print (Eachkey) automatically typing key values



For Eachitem in Dict1.items ():
Print (Eachitem)
Use tuples to set key and values
3.key is dict in the
Get method
Dict1.get (32) If none will return none
Dict1.get (32, ' Eyes have ') if there is no return to the target



You can also use the member operator:
+ In dict1–> flase
In False–> True



4. Empty Dict
Dict1.clear ()
5.copy method Shallow Copy
A = {1: ' One ', 2: ' One '}
b = A.copy ()
c = A
ID (a)
ID (b)
ID (c)
Shallow copy and direct assignment are not the same
c[3]= ' Tree '
C
A
B
6.pop () and Popitem ()
A.pop (2)
A.popitem ()



7. Auto-Add not found
A.setdefault (' haha ')
8.update updating another dictionary with a dictionary or mapping relationship
b={' I ': 1}
A.update (b)



27-Collection unordered!, go to the heavy cannot index
num = {}
Type (num) –> ' dict '
Num2 ={1,2,3,4,5}
Type (num2) –> ' Set '



num2 = {1,1,1,1,1,2,2,2,,2,,2}
–> {}
1. Two ways to create
Enclose the numbers in {}.
Set (): Set1 = set ([1,1,1,1,2,2,2,2,2,2])
2. How to access the values in set
For printing
In Method 1 in NUM1
3.num2.add (9) Add
4.num2.remove (9) Delete



Frozen frozen, set an immutable set
num3 = Frozeset ([1,2,3,666])
This set cannot be added



28-file-want to output.
1. Open File
Open the file by using opening.
Help ()



Little Turtle Python3 Notes


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.