Python Basic Learning 4-functions, built-in functions, OS modules, time modules

Source: Internet
Author: User
Tags local time

1 Function 1.1 Method of string formatting

Several ways to format the output of a string in Python:

Https://www.cnblogs.com/hongzejun/p/7670923.html

String formatting Another way of format mode

#字符串format () method
#
First type
import datetime
msg = ' Welcome {Name} , today's date is {today} '
msg = Msg.format (name = ' Zhangsan ' , today= datetime.datetime.today ())
Print (msg)

# second type
sql = ' INSERT into My_user_value ({Id},{name},{sex },{ADDR}) '
tmp = Sql.format (id=11,name= ' Lisi ' , sex= ' male ' , addr= ' DFDSD ' )
Print (TMP)

# third type
sqla= ' insert into {} value {} ' . Format ( ' AAA ' , ' BBB ' )
Print (SQLA)


#format_map is to format the dictionary string
D = {' name ':' little black ',' sex ':' man '}
Words = ' name : {name}, gender : {sex} '. Format_map (d)
print (words)

The default character set encoding for Python2 is ASCII and is reported in Python2 if any of the following errors occur:

You can add a comment in front of Python2-*-coding:utf-8-*-can solve the problem of Chinese error;

Python3 default is Utf-8 (Utf-8 is a subset of Unicode encoding), adding Chinese does not error.

Name = ' little black '
file_name = ' Goods.json ' # variable name if it is an uppercase representation of a constant , a constant indicates that the value of the variable generally does not change.

1.2 Global variables and local variables

Name = ' little black '
file_name = ' Goods.json ' # variable name if it is an uppercase representation of a constant, a constant indicates that the value of the variable generally does not change.

#局部变量: Variables defined inside a function are local variables and cannot be used except for functions.
#全局变量: The variable defined at the top of the file is the global variable
def HHH ():
Name = ' small white '
Print (name)
HHH ()

Global Name # in a function if you need to modify the value of a global variable, it is generally not recommended that you use Globals. Because global variables always consume memory

Dictionaries and lists such mutable variables, do not need to use Golbal to declare, you can directly modify the

1.3 Variable parameters

Variable parameters (also known as parameter groups): Is not required, there is no limit on the number of parameters, general parameters can be used when more than this method to achieve;

Add an * number before the parameter:
def Send_mail (*email):
Print (' email: ', email)
Send_mail (' [email protected] ')
Send_mail (' [email protected] ',' [email protected] ',' [email protected] ')
Send_mail ()

Example:

def Run (Name,*args):
Print (name)
Print (' args: ', args)
Run (' Zhangsan','a ', 'Beijing ',' Tian Tong Yuan ')

The Zhangsan is passed to name, and the other strings are passed to args.

When a function return multiple values, it is placed by default in a tuple, or you can receive a return value with multiple variables
def Nhy ():
Name = ' Niuhanyang '
sex = ' male '
age= 18
return Name,sex,age
res = Nhy () #默认存放在一个元组中
Print (RES)
A,b,c = Nhy () #也可以使用多个变量接收return的值
Print (A,B,C)

#positional parameters (required parameters), default parameters (not required), variable parameters (no need to fill, no limit on the number of parameters)
#
Position Parameters
defop_db (Ip,port,db,user,passwd,sql):
Print'ConnectionMySQLmanipulating Databases')
Pass
op_db (' 192.168.1.1 ', 3306,' AAA ',' Root ',' 123456 ',' SELECT ')
op_db (' 192.168.1.1 ',' 3306 ', user=' Root ', passwd=' 123456 ', db=' Jzx ', sql=' Insert ')

#keyword parameter: Add two in front of the parameter**number, do not need to fill, do not limit the number of parameters, passed the parameters in the dictionary
Print'------keyword Parameters1------')
defMy (**info):
Print (info)
My (name=' haha ', sex='male', age=18)
My ()
My (type=' car ', a=1,c=1)

Print'------Required Parameters+keyword Parameters2------')
defMy (Name,**info):
Print (name)
Print (info)
My' Xiaohei ', a=' AAAA ', b=' bbbbb ')#two x**number keyword parameter must specify who is equal to who, do not specify will error


Print'------Multiple Parameters1------')
#if more than one type of parameter is used together, it must be by positional parameter -Default Parameters -variable Parameters -the order of keyword parameters is filled in.
defMy (name,sex='male', *args,**kwargs):
Print (name)
Print (Sex)
Print (args)
Print (Kwargs)
My' Xiaohei ')
My' Xiaohei ',' HHH ',' args ',' Args2 ', k=' 1 ', k2=' 2 ')

1.4 Recursion

Recursion, the function calls itself, recursively loops up to 999 times. With recursion, you have to have a definite end condition, and a recursive implementation can also be implemented using a loop.

def my2 ():
num = input (' Enter a number:')
num = int (num)
if num%2!=0:
Print (' Please enter an even number ')
return my2 ()
My2 ()

2 Built-in functions

Python built-in functions:

Print

Input

Int

Dict

Set

List

Str

Len

Open

Tuple

Type

Max #取最大值

Dir #看这个对象里面有哪些方法

msg =' Hello '
Print (dir (msg))

Sorted #排序

Print (CHR) #打印数字对应的ascii

Print (ord (' B ')) #打印字符串对应的ascii

Round () #保留几位小数

Eval #python执行代码

EXEC #执行python代码

Enumerate #枚举方法

# methods for obtaining subscripts and elements at the same time:
#
Method One
Stus = [' Zhang San ',' John Doe ',' Harry ']
for I in range (len (stus)):
Print (I,stus[i])
# Method Two: Enumerate Enumeration methods:
for Index,s in Enumerate (stus):
Print (index,s)

Specifies that the following table starts from the specified numeric value and does not specify a default starting from 0:

Zip #压缩

Stus = [' Zhang San ',' John Doe ',' Harry ']
sex = [' male ',' female ',' woman ']
Age = [30,20,22,21]
for Name,se,ag in Zip (stus,sex,age): #zip to compress multiple lists together
Print (NAME,SE,AG)

If the list element is not as many, the loop is minimal.

Map #循环帮你调用函数

Filter

3 modules

A python file is a module

3.1 Standard Modules

Standard modules: Python comes with modules that are standard modules, which are standard modules that can be directly import, such as:

Import JSON

Import Random

Import datetime

Import time

Import OS

3.2 Third-party modules

Third-party module: The module that someone else has written, you can use it after you install it.

3.2.1 PIP Installation

Third-party modules need to be installed on their own, using the PIP source method for installation

Pip install + third-party module name

Pip Install Pymysql

If the PIP command does not exist, add the PIP directly to the installation directory (D:\Miniconda3\Scripts) in Python to the environment variable;

If the PIP command has but still cannot be installed, use where PIP to see if there is more than one PIP, which will be resolved by renaming the PIP under non-Python;

If more than one version of Python is installed, the third-party library is downloaded as follows:

python2–m pip Install xxx

python3–m pip Install xxx

3.2.2 Manual Installation

Search for modules that need to be installed from the Python official website (https://pypi.org):

File installation method (installed using the absolute path method) at the end of the. WHL suffix:

Pip INSTALLD:\PYTHONBAO\REDIS-2.10.6-PY2.PY3-NONE-ANY.WHL

File installation method for. tar.gz Compressed Package:

Unzip the file, go to the extracted file directory, enter CMD on the address bar to enter the path (or press the SHIFT key under the Decompression folder, right-click "Open command Line window here") and execute the Python setup.py install under the open window.

Pycharm How to install third-party modules (this is not very useful):

3.3 Self-written modules

Write yourself: Python files that you write yourself

3.4 Common Modules 3.4.1 OS module

Import OS
Print (OS.GETCWD ()) # takes the current path
Os.mkdir (' SPz ') # Create a folder in the current directory
Os.mkdir (' d:\aaa ') # Create a folder under absolute path
Os.makedirs (' spz2 ') # creates a folder in the current directory ,
Os.makedirs (' stu\ \laowang ') # parent directory does not exist, will automatically help create the parent directory, and mkdir not;

Print (Os.listdir (' D:\ \pythonscript\day5 ')) # get all the files under a path

# for I in range (10):
# os.mkdir (' d:\\pythonscript\\day5\\test%s '%i)
#
put a folder with even numbers at the end to create aa.txtfile, write something inside .
#
ideas are as follows:
#1
, get to all the folders in this directory,Os.listdir (")
#2
, judging the name of the folder the last one is not even
#3
, if it's even, in this file .f = open (A.txt) f.write (' xxxx ')

forDirinchOs.listdir (' D:\\Pythonscript\\Day5 '):
ifDir[-1].isdigit ():
ifInt (dir[-1])%2==0:
Abs_path =R ' d:\\pythonscript\\day5\\%s\\a.txt '%dir
withOpen (Abs_path,' W ') asFw:
Fw.write (' Test ')

#stitching path, path delimiter is recognized automatically
Print (Os.path.join (' Day5 ',' Test0 ',' A.txt '))
Print (OS.SEP)#Displays the current system file path delimiter

Print (Os.path.dirname (' D:\ \pythonsript\day5\test0 \ \a.txt ') # Gets the path to the parent directory

Os.path.getsize () # Gets the file size of the

3.4.2 Time Module

ImportTime
#time stamp, fromUnixnumber of seconds since the beginning of the first time
#
time of the format number2018-07-01

Print (Time.time ())#gets the current time stamp

Print (Time.strftime ('%y-%m-%d%h:%m:%s '))#get a good time to format
Print (Time.strftime ('%y%m%d '))#%yand the%ya little different .

#
Timestamp and format time conversion
#
Time Tuple

Print (Time.gmtime ())#turn the timestamp into a time tuple, and if the timestamp is not passed, then the time of the standard time zone is taken.
Print (Time.localtime ())#time tuple to take local time zone
Print (Time.localtime (1530436244-864000))

Print (Time.asctime (Time.localtime (1530436244-864000)))
Print (Time.strftime ('%y%m%d%h%m%s ', Time.localtime (1530436244-864000)))

#time stamp to format good time
#1
, first turn the timestamp into a time tuple
#2
, and then turn the time tuple into a formatted time.
defTimestamptostr (timestamp=None, format='%y%m%d%h%m%s '):
ifTimestamp
Time_tuple =time.localtime (timestamp)#turn into a time tuple
returnTime.strftime (Format,time_tuple)
returnTime.strftime (format)
res = TIMESTAMPTOSTR (1530436244,'%y%m%d ')
Res2 = Timestamptostr ()
Print (Res,res2)

# well-formatted time-to-time stamping
#1
, turn the formatted time into a time tuple first
#2
, and then convert the time tuple into a timestamp

time1 = Time.strptime (' 20180701 ','%y%m%d ')
Print (Time.mktime (time1))

def strtotimestamp (format_time=None, format='%y%m%d%h%m%s '):
if format_time:
Time_tuple =time.strptime (Format_time,format)
return Int (time.mktime (time_tuple))
return Int (time.time ())
T1 = Strtotimestamp (' 20180702020202 ')
T2 = Strtotimestamp ()
Print (T1,T2)

Python Basic Learning 4-functions, built-in functions, OS modules, time modules

Related Article

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.