Python Topic 1: Basic knowledge of functions and basic knowledge of python
I recently started to learn the Python language, but I have discovered many advantages (such as concise language and deep understanding of web crawlers ). I learned through "Python basic tutorial" and "python video of zhipu education at 51CTO College". When I watched the video, the teacher told me about the function, and I thought it was very good, so I wrote the first article on Python learning to share with you. main content:
1. Python installation and basic input and output, simple usage of the print () function and raw_input () function.
2. Based on the knowledge learned in the video, I will explain the basic knowledge of functions:
(1) The system provides internal functions: String function library, mathematical function library, network programming function library, and OS function library.
(2) third-party function libraries: explains how to install httplib2 third-party function libraries and provides a simple web crawler example.
(3). User-Defined Functions: Explains user-defined functions such as no return type, tangible parameters, and preset value parameters.
3. At the same time, I made a simple comparison with what I learned in C # in network programming. I found that python has many advantages and is very convenient and powerful.
PS: The article references a lot of knowledge in the video, books and their own knowledge. Thanks to the authors and teachers, I hope the article will help you to learn python knowledge, if there are any errors or deficiencies in the article, please ask Hai Han and I hope you will share your comments with me. do not spray ~
I. Python installation and input/output functions
Python interpreter in Linux can be installed with built-in, windows need to go to www.python.org downloads page download (such as python-2.7.8.amd64.msi), install Python Integrated Development Environment (Python Integrated Development Environment, IDLE) can be. run the program input "> print 'Hello world'", the python interpreter prints the "hello world" string. as follows:
The basic framework of the Python program is "input-processing-output", and the input and output functions are as follows:
1. print () function
Function is used to output or print integer, floating point, string data to the screen, such as print (3), print (12.5), print ('H '). it outputs the variable format "print (x) or print x", and can output multiple variables "print x, y, z ". you can also format the output data and call the format () function. The format is as follows:
Print (format (val, format_modifier) where val represents the value, and format_modifier represents the format word.
# Simple output> print (12.5) 12.5> print ("eastmount") eastmount # output "123.46", 6.2 indicates that the output is 6 bits, and the decimal point is accurate to 2 bits, output the result that the last digit 6 is rounded in. >>> print (format (123.45678, '6. 2f ') 123.46 # output "mouth 123", with a right-aligned fill space to output a total of 6> print (format (123.45678, '6. 0f') 123 # output "123.456780000" 9 digits after the decimal point. If the number exceeds the range, 0> print (format (123.45678, '6. 9f') 123.456780000 # output "34.56%" indicates the print percentage> print (format (0.3456 ,'. 2% ') 34.56%
2. raw_input () function
The built-in function accepts input from sys. stdin, reads the input statement, and returns a string. The input ends with a line break. You can use help (raw_input) to find help. The common format is:
S = raw_input ([prompt]) parameter [prompt] (optional) is used to prompt the user input.
# Input Function >>> str1 = raw_input ("please input a string:") please input a string: I love you >>> print (str1) I love you # view str1 data types >>> type (str1) <type 'str'>
Note the difference between raw_input () and input ().(1 ). input supports valid python table format "abc". strings must be enclosed in quotation marks. Otherwise, an error "NameError: name 'abc' is not defined" is reported, while raw_input () all types of input are acceptable; (2 ). raw_input () takes all input as a string and returns a string. When input () is a pure number, it has its own characteristics and returns the int or float of the input number type. examples:
# SyntaxError syntax error >>> str1 = input ("input:") input: abc Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'abc' is not defined # correct input and output >>> str1 = input ("input:") input: "I love you" >>> print str1 I love you # input pure digital data type >>> weight = input ("weight:") weight: 12.5 >>> type (weight) <type 'float' ># raw_input data types are str >>> age = raw_input ("age:") age: 20 >>> type (age) <type 'str'>
2. Internal functions provided by the function system
The internal library function provided by python mainly describes four types of functions: (videos are introduced in brief)
1. String function library
You can use help (str) to query the string function library. During the Query Process, enter "-More-" and press enter to implement the scrolling information. Then, output "q" to exit the help (Quit ). you are familiar with string functions. C \ C ++ \ C # \ Java has learned a lot and is basically the same. for example:
The islower () function is used to determine whether the string is case-sensitive. If one string is capitalized, False is returned. the previously used format () function and evaluate the string length len () function all belong to the string function library, help (str. replace) can be used to query specific function usage. This function is used to replace the old string with the new string.
# Determine whether the string is in lowercase >>> str1 = "Eastmount" >>> str1.islower () False # string replacement >>>> str2 = 'adfababdfab '>>> str2.replace (' AB ', 'AB') 'adfababdfab '# String Length >>> print (len (str2) 11 >>>
2. mathematical function library
When using the mathematical function library, you must note that import math is imported into the database. We are also very familiar with the functions in this library. For example, sin () is used to calculate the sine, cos () is used to calculate the cosine, pow (x, y) is used to calculate the y Power of x. For example, pow (3, 4) = 3*3*3*3. It can also be represented by 3 ** 4 in python. you can view the details in help (math), and the database defines two constants:
E = 2. 718281... pi = 3. 14159265...
# Import the math Library >>> import math >>>> print math. pi 3.14159265359 # Calculate sin30 degree> val = math. sin (math. pi/6) >>> print val 0.5 # pow function >>> math. pow (81.0) >>> 3 ** 4 81 >>> help (math. pow) Help on built-in function pow in module math: pow (...) pow (x, y) Return x ** y (x to the power of y). >>>
3. network programming library
The system provides the network programming library in the internal library function. Here is just a simple example. socket (socket network programming) is a very common application to obtain the Host IP address, I will make a simple comparison with C # network programming. the following blog will detail python network programming.
>>> import socket >>> baiduip = socket.gethostbyname('www.baidu.com') >>> print baiduip 61.135.169.125
Specifically, socket programming is very common. gethostbyname () returns the specified host ip address, while the code for getting the ip address of Baidu website in C # is as follows. "Warning: Dns. the GetHostByName () function is out of date. You can replace it with IPHostEntry myHost = Dns. getHostEntry (Www.baidu.com). Output:
61.135.169.121
61.134.169.125
// Reference the new namespace using System. net; namespace GetIp {class Program {static void Main (string [] args) {// obtain the DNS information of the DNS host name IPHostEntry myHost = Dns. getHostByName ("www.baidu.com"); IPAddress [] address = myHost. addressList; for (int index = 0; index <address. length; index ++) {Console. writeLine (address [index]);} Console. readKey ();}}}
4. Operating System (OS) function library
The function of the operating system library references "import OS". For example, you can obtain the files and directories in the current working path and the current path first. use OS. system ("cls") can be used to clear the screen. the Lib folder in the python installation directory contains many py library files for use.
>>> Import OS # Get the current job path >>> current = OS. getcwd () >>> print current G: \ software \ Program software \ Python \ python insert # Get files and directories in the current path >>> dir = OS. listdir (current) >>> print dir ['dls', 'Doc', 'h2.txt ', 'include', 'lib', 'libs', 'LICENSE.txt ', 'NEWS.txt ', 'python.exe ', 'pythonw.exe', 'README.txt ', 'tcl', 'tool']>
3. Third-party functions provide function libraries and install the httplib2 Module
(1) install the third-party function library httplib2
Third-party open-source projects in Python provide function libraries for our use, such as httplib2 library functions. in Linux, use "easy_install httplib2" to search for automatic installation. In Windows, use the python development tool IDLE to install the httplib2 module as follows (similar to other modules ).
1. Download httplib2 module"Https://code.google.com/p/httplib2/"To the specified directory, decompress the compressed package" httplib2_0.8.zip "to a directory. If google fails to access the URL, download it here:
2. Configure the python Runtime Environment
Right-click "computer"-> "properties"-> choose "Advanced System settings" in "System"-> choose "advanced" from "System Properties" and select "environment variable"
Add the python installation directory "G: \ software \ Program software \ Python \ python insert" after the system environment variable Path"
3. Install httpLib2 in dos
Run the script by the Administrator. Use the CD command to enter the httplib2_0.8.zip decompression directory and enter "python settup. py install", as shown in. The installation is successful.
4. Use httplib2
If the httplib2 library function is not successfully installed, "import httplib2" will prompt the error "ImportError: No module named httplib2". Otherwise, the installation is successful, for example.
Import httplib2 # obtain the HTTP object h = httplib2.Http () # Send a synchronous request and obtain the content resp, content = h. request ("http://www.csdn.net/") # display returned header information print resp # display webpage-related content print content
Output header information:
{'status': '200', 'content-length': '108963', 'content-location': 'http://www.csdn.net/', .... 'Fri, 05 Sep 2014 20:07:24 GMT', 'content-type': 'text/html; charset=utf-8'}
(2). Simple Web Crawler example
When using third-party function libraries, the specific format is module_name.method (parametes) third-party function name. Method (parameter ).
This article describes an example of referencing a web library. The urllib library accesses the Internet webpage. The webbrowser library calls a browser to download the content on the official website of csdn and displays it through the browser.
import urllib import webbrowser as web url = "http://www.soso.com" content = urllib.urlopen(url).read() open("soso.html","w").write(content) web.open_new_tab("soso.html")
It will output True and open the downloaded static webpage in the browser. Reference import webbrowser as web, or you can directly reference it. "module_name.method" is used.
Content = urllib. urlopen (url). read () indicates opening the url and reading the value assignment.
Open ("soso.html", "w" ).write(content##write the static soso.html file in the pythoninstallation directory
Web. open_new_tab ("soso.html") indicates opening the new tag of the static file.
You can also use web. open_new_tab ('HTTP: // www.soso.com ') to directly open a dynamic web page in the browser. The effect is shown in:
Iv. udfs
1. udfs without return values
The basic syntax format is as follows:
Def function_name ([parameters]):Function Name ([parameter]), where the parameter is optional(TAB) statement1 (TAB) statement2 ...
Note:
(1). the colon (:) after the User-Defined Function name cannot be omitted; otherwise, "invalid syntax" is reported, and {} does not need to be added like the C language {};
(2 ). the TAB is indented before each statement in the function. Otherwise, an error "There's an error in your programs: expected an indented block" is reported ", its function is equivalent to distinguishing between statements in a function and those outside a function.
For example, open the IDLE tool-> click "File"-> New File-> name it the test. py File. Add the following code to the test File.
def fun1(): print 'Hello world' print 'by eastmount csdn' print 'output' fun1() def fun2(val1,val2): print val1 print val2 fun2(8,15)
Save in test. in The py file, click Run-> Run Module. the output result is shown in. The fun1 () function is an invisible parameter user-defined function. fun2 (val1, val2) is a user-defined function with the form parameter. fun2 () is a function call, real parameters 8 and 15.
2. User-Defined Functions with return values
The basic syntax format is as follows:
def funtion_name([para1,para2...paraN]) statement1 statement2 .... return value1,value2...valueN
The return value supports one or more responses. Note that a user-defined function has a return value, and the main function must accept the value (accept the returned result ). at the same time, when defining variables, sum may be keywords (pay attention to color). It is best to use variables that are not keywords. example:
def fun3(n1,n2): print n1,n2 n = n1 + n2 m = n1 - n2 p = n1 * n2 q = n1 / n2 e = n1 ** n2 return n,m,p,q,e a,b,c,d,e = fun3(2,10) print 'the result are ',a,b,c,d,e re = fun3(2,10) print re
The output result is as follows. Note that the parameters correspond one by one. In division, 2/10 = 0, and ** power 2 is 10 to 1024. when re = fun3 () is used to directly output the result as a tuples, The re[ 0] storage 12 in the (12,-,) tuples will be detailed later, re [1] storage-8, in sequence ~
2 10 the result are 12 -8 20 0 1024 2 10 (12, -8, 20, 0, 1024)
3. Custom function parameters include predefined
The basic format of the default value is as follows:
def function_name(para1,para2...parai=default1...paran=defaultn) statement1 statement2 ... return value1,value2...valuen
Note that the pre-defined value parameter cannot be prior to the parameter without pre-defined value. For example.
def fun4(n1,n2,n3=10): print n1,n2,n3 n = n1 + n2 + n3 return n re1 = fun4(2,3) print 'result1 = ',re1 re2 = fun4(2,3,5) print 'result2 = ',re2
Shows the output result. When calling a predefined parameter, the real parameter can be omitted or the predefined value can be replaced.
2 3 10 result1 = 15 2 3 5 result2 = 10
If the function is defined as def fun4 (n3 = 10, n2, n1) the error "non-default argument follows default argument" will be reported. (unspecified parameters are following the predefined parameters.
At the same time, you need to pay attention to the assignment order during function calling. It is best to use one-to-one replication. You can also assign values to specific parameters in function calling, however, during a function call (when using a function), parameters with predefined values cannot be assigned values before those without predefined values.
In this example, the UDF def fun4 (n1, n2, n3 = 10) can be called:
(1). s = fun4 (2, 3) omitting the pre-defined parameter. It is a one-to-one value. The n1 value is 2, n2 value is 3, and n3 value is 10 (pre-defined)
(2). s = fun4 (4, n2 = 1, n3 = 12) It is also a one-to-one assignment, and the predefined value n3 is replaced with 12
(3). s = fun4 (n2 = 1, n1 = 4, n3 = 15) its order does not correspond to the defined function, but the specific response is also given during the call.
The following error occurs:
(1 ). s = fun4 (n3 = 12, n2 =) at this time, the error "non-keyword arg after keyword arg" is reported. It cannot specify n1 = 4, that is, if you do not specify the predetermined value n1 = 4 with a predetermined value n3 = 12, n2 = 1, if you change it to s = fun4 (4, n2 = 1, n3 = 12) or s = fun4 (4, n3 = 12, n2 = 1.
(2 ). s = fun4 (4, n1 = 2) the following error occurs: "TypeError: fun4 () got multiple values for keyword argument 'n1 '", it cannot specify n1 = 2 & n2 = 4, but n1 will assign multiple values.
Therefore, it is best to call functions one by one. at ordinary times, writing programs does not make it difficult for you.
Summary: This article describes the internal functions provided by the system, functions libraries provided by third parties, simple code crawling, the process of installing the httplib2 module, and user-defined functions. haihan ~ Finally, I would like to thank the video teacher and the above-mentioned bloggers, book teachers and me.
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!