I. Python installation and input/output functions The Python interpreter can be built into Linux using the installation, Windows need to go to www.python.org official website downloads page download (such as Python-2.7.8.amd64.msi), Install the Python integrated development environment (Python Integrated Development environment,idle). Run the program input ">>>print ' Hello World '" The Python interpreter will print out the "Hello World" string. As follows: Then the basic framework of the Python program is "input-process-output", and the input-output function is as follows: the 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 variable format "print (x) or print X", and can output multiple variables "Print z/y". also supports formatting output data, calling the format () function, in the form: print (Val, Format_modifier)) where Val represents the value, Format_modifier represents the format word. [Python] View plain copy# simple output >>> print (12.5) 12.5 >>> print ("Eastmount") eastmount #输出 "123.46", 6.2 Indicates output 6 bits, 2 digits after the decimal point, output the last 6 is the result of rounding >>> print (format (123.45678, ' 6.2f ')) 123.46 #输出 "mouth Port 123", with right-aligned fill whitespace output total 6 bits >>> Print (Format (123.45678, ' 6.0f ')) 123 #输出 "123.456780000" after the decimal point 9 bits, out of range will automatically fill 0 >>> print (format (123. 45678, ' 6.9f ')) 123.456780000 #输出 "34.56%" for printing percent >>> print (Format (0.3456, '. 2% ')) 34.5The 6% 2.raw_input () function built-in function accepts input from Sys.stdin, reads input statements, and returns string strings. The input ends with a newline character and can be found with help (Raw_input), and the common format is: s = Raw_input ([prompt]) parameter [prompt] optional, used to prompt user input. [Python] View plain copy# input function >>> str1 = raw_input ("Please input a string:") Please input a string:i love you >>> print (STR1) I Love you #查看str1数据类型 >>> type (str1) <type ' str ' > Note raw_input () and Inpu The difference between T (): (1). Input supports the legitimate Python table format "abc", the string must be enclosed in quotation marks, otherwise an error "Nameerror:name ' abc ' is not defined", and raw_input () any type input is acceptable; (2). Raw_input () returns all input as a string, while input () enters a pure number with its own attribute, returning the input number type int or float. Examples are explained below: [Python] View plain copy# SyntaxError syntax error >>> str1 = input ("Input:") Input:abc Traceback (most recent call last): File "<stdin> ", line 1, <module> File" <string> ", line 1, in <module> nameerror:name ' abc ' are not defined #正 True Input Output >>> str1 = input ("Input:") Input: ' I love you ' >>> print str1 I love #input纯数字 data type >& Gt;> weight = input ("Weight:") weight:12.5 >>> type (weight) <type ' float ' > #raw_input data type is str >& Gt;> age = Raw_input ("Age:") age:20 >>> type (age) <type ' str ' > two. function system provides internal functions Python provides system internal library There are four main types: (from the video, just a brief introduction) 1. String function library through Help (STR) can query the String function library, where the query process "-more-" input enter to implement scrolling information, output "Q" Exit assistance (quit). String functions We all compare Familiar, regardless of C\c++\c#\java have learned a lot, and basically the same. For example, the Islower () function determines whether a string is case-sensitive, and a capitalization returns false. The format () function used earlier, the string length Len () function is all part of the String function library, Help (Str.replace) can query for a specific function usage that replaces the old string with the new string. [Python] View plain copy# determine if the string is lowercase >>> str1 = "Eastmount" >>> str1.islower () False #字符串替换 >>& Gt str2 = ' Adfababdfab ' >>> str2.replace (' ab ', ' ab ') ' Adfababdfab ' #字符串求长度 >>> print (len (str2)) ;>> 2. Mathematical libraries when using the mathematical library, it is important to note that the import library "import math", the library functions we are also very familiar with, such as sin () to find the sine, cos () cosine, pow (x, y) calculates the y power of x, such as POW (3,4) You can also use 3**4 in =3*3*3*3,python to see the details in. Help (math), and two constants are defined in the library data:e = 2.718281 ... Pi = 3.14159265... [Python] View plain copy# import Math library >>> import Math >>> print Math.PI 3.14159265359 #计算sin30度 >> > val = Math.sin (MATH.PI/6) >>> print val 0.5 #pow函数 >>> math.pow (3,4) 81.0 >>> 3**4 Bayi >>> Help (MATH.POW)-built-in function POW in module MATH:POW (...) Pow (x, y) Return x**y (x to the power of Y). >>> 3. Network Programming Library System provides internal library functions in the Network Programming library, I here just to give a simple example, socket (socket network programming) to obtain host IP address this is very common use, I will and C # network programming simple comparison. The post will be detailed Describe Python network programming in detail. [Python] View plain copy>>> import socket >>> baiduip = socket.gethostbyname (' www.baidu.com ') >> > Print Baiduip 61.135.169.125 where socket programming is common, gethostbyname () returns the specified host IP, and the IP address code for the Baidu URL in C # is shown below. "Warning: Dns may appear in the code. GetHostByName () function is obsolete ", can be replaced by iphostentry myHost = Dns.gethostentry (www.baidu.com). Output: 61.135.169.121 61.134.169 .125[csharp] View plain copy//referencing the new namespace using System.Net; Namespace GetIP {class Program { static void Main (string[] args) {//Get DNS information for DNS hostname iphostentry myHost = dns.ge Thostbyname ("www.baidu.com"); ipaddress[] address = myhost.addresslist; for (int index = 0; index < address. Length; index++) {Console.WriteLine (Address[index]); } console.readkey (); }}} 4. The operating system (OS) function library operating system library functions refer to "Import OS", for example, to obtain the current working path and the files and directories under the current path. You can use Os.system ("CLS") to achieve clear screen function. installation Pytho The N directory Lib folder contains many Py library files for use. [CSharp] View plain copy>>> import os #获取当前工作路径 >>> current = OS.GETCWD () >>> Print current G:\software\Program software\python\python Insert #获取当前路径下的文件和目录 >>> dir = os.listdir (current) >>> p Rint dir [' DLLs ', ' Doc ', ' h2.txt ', ' include ', ' Lib ', ' Libs ', ' LICENSE.txt ', ' NEWS.txt ', ' python.exe ', ' pythonw.exe ', ' R EADME.txt ', ' tcl ', ' Tools ' >>> three. Function of third party to provide function library and install HTTPLIB2 module process (i). Install third-party library HTTPLIB2 Process Python provides a library of functions for use in third-party open source projects, such as using HTTPLIB2 Library functions. Use the "Easy_install httplib2" search in Linux to automatically install The process of installing the HTTPLIB2 module in the Windows Python development tool in Idle is as follows (similar to other modules). 1. Download HTTPLIB2 module "https://code.google.com/p/httplib2/" to the specified directory, extract the compressed package "Httplib2_0.8.zip" to a directory, if Google access to the URL failed, you can download here: 2. Configure the Python run environment right-click Computer, properties, select Advanced system settings in System Properties, select environment variables in system attributes, add the Python installation directory after the system environment variable path G:\SO Ftware\program Software\python\python Insert "3. Under DOS, install HTTPLIB2 administrator mode to run CMD, use the CD command to enter Httplib2_0.8.zip extract directory, enter" p Ython settup.py Install ", as shown in successful installation. 4. Using HTTPLIB2 if the HTTPLIB2 library function is not successfully installed, "Import Httplib2" prompts the error "Importerror:no module named Httplib2". Otherwise the installation is successful, for example. See more "Py Thon-Familiar with httplib2 "[Python] View plain copyimport httplib2 #获取HTTP对象 h = httplib2. Http () #发出同步请求并获取内容 resp, content = H.request ("http://www.csdn.net/") #显示返回头信息 Print resp #显示网页相关内容 print content Output header information: {' status ': ' $ ', ' content-length ': ' 108963 ', ' content-location ': ' http://www.csdn.net/', .... ' Fri, SEP 20:07:24 GMT ', ' content-type ': ' text/html; Charset=utf-8 '} (ii). Simple Web crawler example when using a third-party library, the specific format is Module_name.method (parametes) third-party function name. Method (Parameter). Tell a reference Web library, Urllib Library to access the public Web page, WebBrowser library invoke browser operation, download CSDN website content and display the instance through the browser. [Python] View plain copyimport 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 Web page in the browser. Reference Import We The Bbrowser as Web uses the Web and can also be referenced directly, using "Module_name.method". Readers can compare my C # article "Simple download Implementation of the C # Network Programming Web page." Content = Urllib.urlopen (URL). Read () to open the URL and read the assignment open ("Soso.html", "W"). Write (content) indicates that a static soso.html file is written in the Python installation directory Web.open_new_tab ("soso.html") indicates that a new label for the static file is opened. You can also use Web.open_new_tab (' http://www.soso.com ') to open dynamic Web pages directly in your browser. The effect is as follows: four. function's custom Function 1. No return value Custom function its basic syntax format is as follows: def function_name ([parameters]): function name ([parameter]), where parameters are optional (TAB) statement1 (TAB) Statement2: . Note: (1). The colon after the custom function name (:) can not be omitted, otherwise the error "Invalid Syntax", and do not need to be like C language plus {}; (2). There is indentation tab before each statement in the function, otherwise it will error "There's an error in your programs:expected an indented block", which functions as a function of distinguishing between statements in functions and statements outside functions. Example: Open the Idle tool, click on the bar "file"->new file New files, named test.py file, add the code in the test file as follows. [Python] View plain copydef fun1 (): print ' Hello world ' print ' by Eastmount csdn ' print ' Output ' fun1 () d EF fun2 (val1,val2): Print val1 print val2 fun2 (8,15) Save, click test.py Module in the Run->run file. Output as shown, where Fu The N1 () function is an invisible parameter custom function, Fun2 (VAL1,VAL2) is a tangible parameter custom function, Fun2 (8,15) is a function call, argument 8 and 15. 2. There is a return value custom function whose basic syntax format is as follows: Def funtion_name ([Para1,para2...paran]) Statement1 Statement2 .... Return Value1,value2...valuen returns are supported by one or more of the return values, it is important to note that the custom function has a return value, and the keynote function needs to accept the value ( Accept the returned result). While defining a variable may sum these may be keywords (note color), preferably using variables that are not keywords. Example: [Python] View plain copydef 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 is ', the a,b,c,d,e re = FUN3 (2,10) print re output is as follows, where it is important to note that the parameter one by one corresponds to the 2/10=0,** power in the Division 2 of 10 times =102 4. The result of direct output using RE=FUN3 (2,10) becomes a tuple, which is described in detail later, (12,-8,20,0,1024) tuple re[0] storage 12,re[1] Storage-8, ~[python] View plain copy2 Result is 12-8 20 0 1024 2 10 (12,-8, 20, 0, 1024) 3. The basic format of a custom function parameter with a predefined preset value is as follows: def function_name (PARA1,PARA2...PARAI=DEFAULT1...PARAN=DEFAULTN) Statement1 Statement2 ... Return Value1,value2...valuen One thing to note is that the predefined values cannot be preceded by no pre-defined value parameters, as explained in an example. [Python] View plain copydef 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 output as shown, predefined parameters can be omitted when invoked, or they can be substituted by default defined predefined values. [Python] View plain copy2 3 RESULT1 = 2 3 5 result2 = 10 where the function is defined as Def fun4 (N3=10,N2,N1) the error "Non-defaul T argument follows default argument "(no predefined parameters are behind predefined parameters), so you need to be aware of that point when defining a function. At the same time, it is necessary to pay attention to the order of the function call, preferably one-to-one replication, or a function call to the issue of the parameter assignment, but it is important to note that during the function call (when using the function), the parameters with predefined values can not be assigned before the parameter is not pre-defined value. As an example, the Custom function Def fun4 (n1,n2,n3=10), when invoked, can be: (1). S=FUN4 (2,3) omits the predefined parameters, which are assignment to one to the other, where N1 assignment 2, N2 assignment 3, N3 assignment 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 by the number of (3). S=FUN4 (N2=1,N1=4,N3=15) Its order does not correspond to the defined function, but when the call gives the exact corresponding line, the following conditions will appear as described in the "predefined values parameter is assigned "error: (1). S=FUN4 (n3=12,n2=1,4)" Non-keyword arg after keyword arg ", which cannot specify n1=4, that is, no predetermined value is specified n1=4 after a predetermined value n3=12,n2=1, if changed to S=fun4 (4,n2=1,n3=12) or S=fun4 (4,n3=12,n2=1). (2). S=FUN4 (4,n1=2) will also error "TYPEERROR:FUN4 () got multiple values for keyword argument ' n1 '", it cannot specify n1=2&n2=4, but N1 will assign multiple . Therefore, the best is one by one corresponding to the calling function, usually write programs do not make it difficult for themselves, the corresponding can be [
Brother----Python (English) function