python basic learning
function
Define a function
- Function code blocks begin with def keywords, followed by function identifier names and parentheses ()
- Any incoming parameters and independent variables must be placed between parentheses, which can be used to define parameters.
- Function content starts with a colon and is indented
- return [expression] ends the function, selectively returning a value to the caller. return without expression is equivalent to returning None
def function name (parameter list): Function Body
function call
Define a function: Give the function a name, specify the parameters contained in the function, and code block structure.
When the basic structure of this function is complete, you can either call another function or execute it directly from the Python command prompt.
# Define function def var(str): print(str) return # The return function is used to derive the function. # Call function var('Life is short, I love it python') var('python Great law is good') >>>Life is short, I love it python >>>python Great law is good
Parameter transfer
Essential parameters
Necessary parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.
Keyword parameters
Keyword parameters allow for inconsistencies between the order of parameters when a function is called and when it is declared
def printme(name,age): print('The name is:',name) print('Age:',age ) return printme(age = 17,name = 'joey') >>>The name is: joey >>>Age: 17
Anonymous function
python uses lambda to create anonymous functions.
lambda [arg1 [,arg2,.....argn]]:expression
sum = lambda arg1,arg2:arg1+arg2 print('Add up to:',sum(10,20)) >>>Add up to: 30
Variable scope
In Python, variables of a program are not accessible anywhere. Access rights depend on where the variable is assigned.
The scope of variables determines which part of the program can access which specific variable name. Python has four scopes:
- L(Local) Local Scope
- In the function outside the closing function of E(Enclosing)
- G lobal scope
- B (Built-in) built-in scope (range of modules where built-in functions are located)
g_count = 0 # global scope def outer(): o_count = 1 # In a function outside a closure function def inner(): i_count = 2 # Local scope
Find with the rule of L -> E -> G -> B, that is, if you can't find it locally, you will find it locally (e.g., closure), if you can't find it, you will find it globally, and then you will find it in the built-in.
global and nonlocal keywords
- Modify the global variable num:
num = 1 def fun1(): global num # Need to use global keyword declaration print(num) num = 123 print(num) fun1() print(num) >>>1 >>>123 >>>123
- Modifying nested scopes
def outer(): num = 10 def inner(): nonlocal num # nonlocal keyword declaration num = 100 print(num) inner() print(num) outer() >>>100 >>>100
File (File) Method
open() method
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
- File: Required, file path (relative or absolute path)
- Mode: Optional, file open mode
- buffering: Setting Buffers
- encoding: Usually utf8 is used
- errors: Error level
- Newline: distinguish newline characters
- closefd: Input file parameter type
- opener:
Import Excel and csv files
import pandas as pd df = pd.read_excel(r'Default path') df = pd.read_csv(r'Default path')
datetime module
datetime is the standard library for Python processing dates and times.
Get the current date and time
from datetime import datetime now = datetime.now() print(now)
- Notice that datetime is a module and that the datetime module also contains a datetime class, which is imported from datetime import datetime.
- If you import only import datetime, you must refer to the full name datetime.datetime.
Gets the specified time and date
from datetime import datetime tf = datetime(2018,8,8,18,30) print(tf) >>>2018-08-08 18:30:00
datetime to timestamp
from datetime import datetime tf = datetime(2018,8,8,18,30) tf.timestamp() >>>1533724200.0
Time stamp to datetime
from datetime import datetime tf = 1533724200.0 print(datetime.fromtimestamp(tf)) print(datetime.utcfromtimestamp(tf)) # Conversion to UTC Standard Time >>>2018-08-08 18:30:00 >>>2018-08-08 10:30:00
str to datetime
from datetime import datetime tday = datetime.strptime('2008-8-8 20:8:8','%Y-%m-%d %H:%M:%S') print(tday) >>>2008-08-08 20:08:08
datetime to str
from datetime import datetime now = datetime.now() print(now.strftime('%a, %b %d %H:%M')) >>>Sun, Jun 30 18:50