Python3-2 notes

Source: Internet
Author: User
Tags function definition numeric value shallow copy

I. Deep copy and shallow copy
1. Referencing and assigning values
A reference is a value that points to some data
A list reference is a value that points to a list
When you assign a list to a variable, you actually assign the ' reference ' of the list to the change variable.
ID (): A unique space in memory equivalent to index >>> a=[1,2,3]

>> B=a
>> ID (a)
6699720
>> ID (b)
6699720
>> b[0]=111
>> ID (a)
6699720
>> ID (b)
6699720
>> A
[111, 2, 3]
>> b
[111, 2, 3]
>> c=[1,2]
>> d=[1,2]
>> ID (c)
7438408
>> ID (d)
7438536
>> Print (ID (a) ==id (b))
True

Copy () and Deepcopy () of the copy module
Copy (): Copies the first level list, fully specifies in another space, other levels specified in the same piece of space
Deepcopy (): Completely copied, nothing will be repeated reference to the same memory space.
Shallow copy mechanism: (copy)

>> Import Copy
>> A
[111, 2, 3]
>> C=copy.copy (a)
>> Print (ID (a) ==id (c))
False
>> c[1]=333
>> C
[111, 333, 3]
>> A
[111, 2, 3]
>> a=[1,2,[3,4]]
>> D=copy.copy (a)
>> D
[1, 2, [3, 4]]
>> Print (ID (d) ==id (a))
False
>> Print (ID (d[2]) ==id (a[2]))
True
>> d[2][0]=300
>> A
[1, 2, [300, 4]]
>> D
[1, 2, [300, 4]]
>>

Deep copy: (deepcopy)

>> E=copy.deepcopy (a)
>> E
[1, 2, [300, 4]]
>> e[2][1]=4444
>> E
[1, 2, [300, 4444]]
>> A
[1, 2, [300, 4]]

Two. Control flow-Conditional judgment

#if条件分支
Age=eval (Input (' Please enter your age '))
#eval (): auto-Convert to data type
If 18<=age<150:
Print (' You can fall in love! ‘)
Elif age>150:
Print (' Demon Ji ')
Else
Print (' You're not adult ', end= ', ')
Print (' Can't Puppy Love ')

Case one: Enter a number, output the number of days of the week
Num=eval (Input (' Please enter a number: '))
If num==1:
Print (' Monday ')
Elif num==2:
Print (' Tuesday ')
Elif num==3:
Print (' Wednesday ')
Elif num==4:
Print (' Thursday ')
Elif num==5:
Print (' Friday ')
Elif num==6:
Print (' Saturday ')
Elif num==7:
Print (' Sunday ')
Else
Print (' Input number not valid ')

Case two: Run year judgment (the year can be divisible by 4 but not divisible by 100 or divisible by 400)
Num1=eval (Input (' Please enter a year: '))
if (num1%4==0 and num1%100!=0) or num1%400==0:
Print (' is run year ')
Else
Print (' Not a leap year ')

#年龄段的判断 (note indent)
Age=eval (Input (' Please enter your Age: '))
If 0< age<18:
Pass (not shown by pass)
#print (' You're a teenager ')
Else
If 18<=age<30:
Print (' You're a young man ')
Else
If 30<age<=50:
Print (' middle age ')
Else
If 65<age<120:
Print (' Seniors ')
Else
Print (' You're a freak ')

Second, the circular statement
1.while
I=0 # What if it's i=1?
While i<100: #那么i =101
Print (' << kingdoms >> I watched%d episodes '% (i+1))
I=i+1
Print (' Always have read, cry as a dog ')

Break: If you encounter a beak statement, you will immediately jump out of the while Loop statement
Continue: If the program execution encounters continue, it jumps back to the beginning of the loop and re-loops the condition evaluation.

#死循环
#陷入无限循环中
While True:
Print (' Love You ')

For Loop and range () functions
With a condition of true, the while loop continues to loop (this is the origin of its name).
But what if you have a block of code that performs a fixed number of times?
This can be done through a For loop statement and a range () function.
"For Syntax"
"For keyword
A variable name
in keyword
Call the range () method to pass up to 3 parameters
Colon
At the beginning of the next line, indent the block of code (called A FOR clause) "

Range ()
Some functions can be called with more than one parameter, separated by commas, range ()
is one of them can change the integer passed to range () to implement various integer sequences
Includes starting from a value other than 0 range (start,end,step) return list
Start start value, end end value, step step value defaults to 1

For I in Range (1,101):
Print (' I ran%d laps '%i)
Print (' I'm thin ')

For I in range (100):
Print (' I ran%d laps '% (i+1))
Print (' I'm thin ')

Case One
Enter a numeric value that outputs all the odd numbers from 0 to this number. and a line every 10 numbers
Num=eval (Input (' Please enter a value: '))
For I in Range (1,num+1,2):
Print (i,end= ")
#每隔10个数换一行
if (i+1)%20==0:
Print ()

Case Two
Known Big Rooster 5 Yuan, hen 3 yuan, chick 1 yuan 1. (hundred yuan to buy hundred chickens)
sum=100
#i, J, K, respectively, the number of cocks, hens, chickens:
For I in range (20):
For j in Range (33):
for k in range (0,100,3):
If I+j+k==sum and I5+j3+k/3==sum:
Print (' Rooster buys%d, hen buys%d, chick buys%d '% (i,j,k) ')

Case Three
If the first number is known to be 1, the second number is 1, and the equation F (x) =f (x-1) +f (x-2) is satisfied, calculate the value of the room (100). (Fibonacci series)
list1=[1,1]
For I in range (100)
List1[i].append (List1[i-1]+list1[i-2])

Print (%d value%d '% (I,list1[i]))

Print (list1[99])

Graphics output
For I in Range (1,9):
Print ('i)

For I in range (9):
Print ("(i+1))

U. Exception capture
Syntax: Try .... except
Abnormal:
Encountering an error, or exception, in a Python program means the entire program crashes. We don't want this to happen in real-world programs, instead, you want the program
Can detect errors, process them, and then run normally.
Catching Exceptions:
Once an exception is generated, it is captured and then processed.
The purpose is to ensure the normal execution of the program, not to produce an exception and terminate the program to continue to implement.
list1=[0,1]
Try
Print (list2[2])
Except Nameerror as E:
Print (e)
Except Indexerror as E:
Print (e)
Except Baseexception as E:
Print (e)
Print (' program works ')
Print (' program works ')

Function:
def hello ():
Print (' Hello ')
Print (' tom!! ')
Print (' Hello there ')

Hello ()
Hello ()
Hello ()

A. The first line is the DEF statement, which defines a function named Hello ();
The code block after the B.DEF statement is the function body, which is executed in the function call
C. The hello () statement after the function is a function call. (function call is function name and parentheses)

def hello (name):
Print (' Hello, ' +name)

Hello (' TOM ')
Hello (' XP ')
A. In the hello () function definition of this program, there is a variable named name;
B. A change member is a variable that is stored in a function call.
C. The value saved in the variable is lost when the function returns.

return value and return statement
If the Len () function is called and a parameter called like ' Hello ' is passed to him, it evaluates to an integer of 5, which is the length of the passed string
In general, the result of a function call evaluates to a function's return value.

The A.return statement contains the following sections
. return keyword
The value or expression that the function should return
B. If an expression is used in the return statement, the return value is the result of the expression evaluation.
C. If you use a return statement without merit (that is, the return itself), then the long return is none.
1
def hello (name):
Return ' Goodbye '
Print (Hello (' Zhou's teacher '))
2.
def hello (name):
Return or pass
Print (Hello (' Zhou's teacher '))

Draw Small Program:
Defines a function that returns an identical string based on the mathematical parameters passed in

Steps:
1. Import random number module (import random)
2. Building a function body
3. Generate Random Numbers
4. Calling functions
#导入随机数模块
Import Random
#产生一个1-9 Random real integers
A=random.randint (1,9)
#print (a)
def Answer (num):
If num==1:
Return ' first prize '
Elif num==2:
Return ' second Prize '
Elif num==3:
Return ' third prize '
Elif num==4:
Return ' participation Award '
Else
Return ' Thank you for participating '
Print (Answer (a))

lambda expression definitions (also known as anonymous functions)
A.lambda is just an expression, the function body is simpler than def
The B.LAMDBA body is an expression, not a block of code, that encapsulates only a limited amount of logic in a lambda expression.
(1) No Parameter form
A=lambda: ' Ixp '
Print (A ())
(2) Parameter form:
A=lambda x:x**2
Print (A (10))
(3) Remove each of the x, twice times the number of the part to traverse out
B=LAMDBA x:[i for I in X if i%2==0] #生成器
Print B ([1,2,3,4,5,6,])

#生成器
C=lambda x:[i for I in X if i%2==0]
#取出X的每一项, the multiples of 2 are all traversed.
Print (c ([1,2,3,4,5,6]))

Filter (), map (), reduce ()
Python has built-in special functions that are very python-specific.
You can make your code more concise. Filter,map,reduce three functions are similar, are applied to the sequence of the built-in functions, the common sequence includes list, tuple, str.
Typically used with lambda expressions.

1.filter function
The filter function performs a filtering operation on the specified sequence and fetches it in batches.
The definition of the filter function:
Filter (function or NONE,SEQ)-->list,tuple,or string
The filter function calls the function function for each element in the sequence parameter sequence, and the result that is returned contains the element that invokes the result to true.

Case one:
Take out the list of elements divisible by 3
FOO=[2,18,9,22,17,24,8,12,27]
Print filter (Lambda:xx%3==0,foo)

2.map function
The Map function does batch processing of the specified sequence based on the provided function.
Definition of the Map function
Map (function,seq,[seq,...]) >list
As you can see by definition, the first parameter of this function is a function, and the remaining arguments are one or more sequences.
Functions can be understood as a one-to-one or many-to-a function, and the function of map is to call function functions with each element in the parameter sequence, returning the containing each function
Returns the list of worth.

Case TWO:
1. Perform a square operation on each element in a sequence:
Map (Lambda x:x**2,[1,2,3,4,5])

#map
B=map (Lambda x:x**2,[1,2,3,4,5])
Print (list (b))

2. Sum the elements in the two sequence sequentially.
Map (Lambda x,y:x+y,[1,3,5,7,9],[2,4,6,8,10])
Note: When there are multiple sequences of parameters, the function function is called in turn with the elements in the same position in each sequence.

C=map (Lambda x,y:x+y,[1,3,5,7,9],[2,4,6,8,10])
Print (list (c))

3. When the function is none.
Map (none,[1,3,5,7,9],[2,4,6,8,10])
C=map (none,[1,3,5,7,9],[2,4,6,8,10])
Print (c) (only this type of output)

Reduce function
The reduce function computes the overall calculation of the elements in the parameter sequence.
Definition of the Reduce function;
Reduce (fuction,seq,initial)->value
The function parameter is a parameter with two parameters, and reduce sequentially takes an element from the SEQ, and the last call to function
The result of the parameter call function again.
The first time you call function, if you supply the inital parameter, the first element in the SEQ and the
Inital calls function as a parameter, otherwise it invokes function with the first two elements in the sequence seq.
#reduce批量计算
#python3要引入模块functools
Case THREE:
1.reduce (Lambda x,y:x+y,[2,3,4,5,6],1)
The result is 21 (((((((((1+2) +3) +4) +5) +6))
Import Functools
D=functools.reduce (Lambda x,y:x+y,[2,3,4,5,6],1)
Print (d)
#Y =1,x=2 X=x+y
#x =3,y=3
#x6, y=4
#x10, y=5
#x =15, y=6
#x =21
2.reduce (Lambda x,y:x+y,[2,3,4,5,6])
The result is 21 (((((((((1+2) +3) +4) +5) +6))

Import Functools
D=functools.reduce (Lambda x,y:x+y,[2,3,4,5,6])
Print (d)
#Y =2,x=3
#x =5,y=4
#x9, y=5
#x14, y=6
#x =21
#否则会以序列seq中的前两个元素作参数调用function.
function cannot be none

Summary:
Filter function
Syntax: Filter (funtion or NONE.SEQ)
Application: Batch extraction of data

Map function
Syntax: Map (funtion,seq,[seq,...])
Application: Batch extraction of data

Reduce function
Syntax: Reduce (funtion,sequence,[initial])
Application: Overall calculation of the data

Python3-2 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.