This article describes the basics of a python conditional statement and a looping statement, as described in " topic I. Basics of Functions " . The main contents include:
1. Conditional statement: Includes single, dual, and multi-branch statements, If-elif-else
2. Loop statement: While use and simple network brush spider crawler
3. Looping statements: Use of for and traversal of lists, tuples, files, and strings
Preface: statement block
Before you can tell a conditional statement, a loop statement, and other statements, you should supplement the knowledge of the statement block. (The function has been used before)
A statement block is not a statement, it is a set of statements that executes or executes multiple times (a loop statement) when the condition is true (a conditional statement). You can create a statement block by placing a space or tab character before the code to indent a statement. Many language special words or characters (such as begin or {) represent the beginning of a block of statements. Use a different word or character (such as End or}) to indicate the end of a block of statements.
in Python, you use a colon (:) to identify the beginning of a statement block in which each statement is indented (with the same indentation). When you fall back to the same amount of indentation as the closed block, it means that the current block has ended.
I. Conditional statements IF
The basic types of IF branch statement expressions are common in three ways:
1. Single Branch statement
Its basic format is:
If condition:
Statement
Statement
It is important to note that the IF condition statement condition in Ptthon does not require parentheses (), and the condition is followed by a colon, which does not have curly braces {} but is distinguished by the tab implementation. Where condition conditional judgments usually have Boolean expressions (true| False 0-False |1-true 0 is true), the relational expression (>= <= = = =), and the logical operation expression (and or not).
2. Dual-Branch statements
Its basic format is:
If condition:
Statement
Statement
Else
Statement
Statement
3. Multi-Branch statements
If multiple branches are composed of If-elif-else, where elif is equivalent to the else if, and it can use multiple if nesting. The code is as follows:
#双分支if-elsecount = input ("Please input:") print ' count= ', countif count>80: print ' lager than ' else: print ' Lower than ' print ' End if-else ' #多分支if-elif-elsenumber = input ("Please input:") print ' number= ', Numberif number>=90: print ' A ' elif number>=80: print ' B ' elif number>=70: print ' C ' elif number>=60: print ' D ' else : print ' No pass ' print ' End if-elif-else ' #条件判断sex = raw_input ("plz input your sex:") if sex== ' male ' or sex== ' m ' or sex= = ' man ': print ' mans ' else: print ' Woman '
two. Loop statement while
the basic format of the While loop statement is as follows:
While condition:
Statement
Statement
Else
Statement
Statement
where the conditional statement condition can be a Boolean expression, a relational expression, and a logical expression, else can be omitted (listed here to be different from C language). For example:
#循环while计数1 +2+. +100i = 1s = 0while I <=: s = s+i i = i+1else: print ' exit while ' print ' sum = ', s ' ' Output is: Exit While
sum = 5050 ""
it outputs a result of 5050, when I was added to 101, because I>100 would execute the ELSE statement.
Note that the use of the pound sign (#) in Python represents a line comment, and the use of a three-line quotation mark ("...") represents a multiline comment.//Line comments and/**/comments that differ from C/s +/-lines.
The following is a code to brush the Spider Crawler, the first code to explain:
Import WebBrowser as Webimport timeimport osi=0while i<5: web.open_new_tab (' http://andy111.blog.sohu.com/ 46684846.html ') i=i+1 Time.sleep (0.8) Else: os.system (' taskkill/f/im iexplore.exe ') print ' Close IE '
In the Sohu blog or Sina Blog as long as the new window opens will increase the number of browsing visits, so the above code is mainly by calling WebBrowser browser Open_new_tab open a new window, and csdn not (estimated bound user or IP).
The function of the windoes command Taskkill in the above code is to kill the application IE browser, enter "taskkill/f/im iexplore.exe" in DOS to forcibly close the application (Chrome.exe or Qq.exe), where/ F means that the program is forcibly terminated, and/im represents the image. The main function in this program is to clear the memory, prevent the memory consumption is too big to appear the freezing phenomenon, but need to call the import OS's system () function to open, and Linux under the Kill command (Kill-pid or killall) Terminates the process.
The code in Time.sleep (seconds) means "Delay execution for a given number of seconds.", from open to loaded for a certain time.
When you need to greatly increase the amount of browsing can use two layers of loop nesting, each time you open 5 Web pages in the execution 100 times, so that your memory will not be too expensive to panic phenomenon, you can also use import random Count=random.randint (20,40) Generates 20 to 40 random numbers to perform the outer loop. The code is simple, mainly to introduce some basic knowledge of Python. But the first time you open IE browser, there will be an inconsistent open number of errors. Why?
three. Circular Statement for
The underlying format of the loop statement is:
for Target in sequences:
statements
target represents the variable name, Sequences represents a sequence, common types are list (lists), tuple (tuple), strings (string), and files (file).
Python's for does not reflect the number of loops, unlike the I loop count in the C language for i=0;i<10;i++, Python's for means each time the data item from the sequence sequences is placed in the target, the end is finished, How many times the loop is taken. Where in is the membership operator, check whether a value is in the sequence. You can also use break and continue to jump out of the loop.
1. String Loops
S1 = ' Eastmount of CSDN ' for C in S1: print C,
Note: If you add a comma at the end of print, the next statement will be printed on the same line as the previous statement. So the above output shows one line.
2. List Loops
List1 = [1,3,4,5, ' x ', 12.5]i = 0for val in list1: print format (i, ' 2d '), val i = i+1else: print ' out for '
Note: The list of lists is separated by commas, square brackets, and can be of the same type or different types. Format (i, ' 2d ') is equivalent to the output of two bits, insufficient fill spaces. When output 0-9 displays "Port 0" and output 10-99 displays "10" Implement the function on it. The output is as follows:
1 3 2 4 3 5 4 x 5 12.5out for
Because iterations (the other way round) a range of numbers is very common, there is a built-in range function range for use. The For n in [1,2,3,4,5,6,7,8] is equivalent to Listnum=range (1,9) in the list. Its format "range" (Start, stop[, step]), list of integers, which works like a shard, contains a lower bound (1 in this example range), but does not contain an upper limit (in this case 9), and if you want a lower limit of 0, you can provide only the upper limit such as range (4) =[ 0,1,2,3].
Generates a number range of 1 to 100 (1,101), output 1 to 100 odd range (1,101,2), and an even range of 1 to 100 (2,101,2).
3. Tuple loops
Tup = (1,2,3,4,5) for n in tup: print Nelse: print ' End for '
Tuple tuples Each data item cannot be modified, only readable, and sequence list[1,2,3,4] can be modified.
4. File cycle
Help (File.read) returns a string. " Read ([size]), read at most size bytes, returned as a string. "
Help (File.readlines) returns a list. " ReadLines ([size]), List of strings, each a line from the file. " The equivalent of reading n rows, consisting of N-times ReadLine, reads the list of string components.
Help (File.readline) reads a line from a file. " ReadLine ([size]), next line from the file, as a string. "
#文件循环遍历三种对比for N in open (' for.py ', ' R '). Read (): print n,print ' End ' for n in open (' for.py ', ' R '). ReadLines (): Print N,print ' End ' for N in open (' for.py ', ' R '). ReadLine (): print n,print ' End '
Output display:
#第一个read () Output: There is a space between each character s 1 = ' E a s t m o u n T o f C s D n ' F o r C i n s 1: .... end# second readlines () output: reads a line S1 = ' Eastmount of CSDN ' for C in S1: .... end# third ReadLine () output: reads the first line of the for.py file and outputs s 1 = ' E a s t m o u n t o f C s D N ' End
If you need to file output can also be implemented by the following code, using W will overwrite and A + is an append function, the file is described in detail later.
for R in open (' Test.txt ', ' R '). ReadLines ():
open (' test.txt ', ' A + '). Write (c)
PS: I am mainly through the "Basic Python Tutorial" and "51CTO College Zhipu Education python Video" learning. So the article cited a lot of video in the knowledge, book knowledge and their knowledge, thanks to those authors and teachers, hope that the article is helpful to everyone, and began to learn Python knowledge, If there are errors or shortcomings in the article, also please Haihan, also hope that you put forward suggestions and June mutual encouragement. Do not spray ~
(By:eastmount 2014-9-22 Night 7-point original CSDN http://blog.csdn.net/eastmount/)
[Python learning] topic two. Basics of conditional and cyclic statements