Brother Lian Learning Python-------conditional statements and loop statements

Source: Internet
Author: User

The basics of Python's conditional statements and looping statements: 1. Conditional statements: Includes single, dual, and multi-branch statements, If-elif-else 2. Loop statement: Use of while and simple network brush crawler 3. Loop statement: Use and traversal of for Lists, tuples, files, and strings complement the knowledge of a block of statements before they can be sued for conditional statements, loop statements, and other statements. The statement block (already used before the function) 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 the statement. Many languages special words or characters (such as begin or {)       To represent the beginning of a block of statements, using another word or character (such as End or}) to represent 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 (the indentation is the same). When you fall back to the same indent as the closed block, it means that the current block has ended. I. Conditional statement If the branch statement expression basic type There are three kinds of common:                                           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 (), after which a colon is added, which does not have curly braces {} but is distinguished by tab implementation. where C Ondition 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. Two-branch statement its basic format is: if Condition:statement                                 Statement Else:statement Statement 3. Multi-Branch language The If multi-branch is composed of If-elif-else, where elif is equivalent to the else if, and it can be nested using multiple if. The code is as follows: [Python] View plain copy #双分支if-else count = input ("Please input:") print ' count= ', Count if Count>80:print ' lager than ' Else:print ' lower than ' pri NT ' End if-else ' #多分支if-elif-else number = input ("Please input:") print ' number= ', number if Number>=90:prin      T ' 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 ': The print ' Man ' else:print ' Woman ' two. The basic format of a loop statement while the 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 as a difference from the C language). For example: [Python] view plain copy #循环whil E-Count 1+2+.  +100 i = 1 s = 0 while I <= 100:s = s+i i = i+1 else:print ' exit while ' print ' sum = ', s '        The output is: Exit while sum = 5050 "' It outputs a result of 5050, when I was added to 101, because I&GT;100 will 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 to explain the code: [Python] View plain copy import WebBrowser as Web import time import os i=0 while i<5: Web.open_new_tab (' http://andy111.blog.sohu.com/46684846.html ') i=i+1 time.sleep (0.8) Else:os.system (' Task kill/f/im iexplore.exe ') print ' Close IE ' in Sohu blog or Sina blog just open in new window willIncrease 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 of the basics of Python. But the first time you open IE browser there will be an inconsistent open number of errors. Why? three. The underlying format of the loop statement for the Loop statement is: For Target in Sequences:statemen        TS Target represents a variable name, sequences represents a sequence, and a common type is a list (list), 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 jump out of the loop. 1. String loop [Python] View plain copy 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 match the previous A statement is printed on the same line. The above output shows a row. 2. List loop [Python] view plain copy list1 = [1,3,4,5, ' X ', 12.5] i = 0 for Val in List1:prin T format (i, ' 2d '), val i = i+1 else:print ' out for ' note: The list of lists is separated by a comma of data, surrounded by square brackets, and can be of the same type or different types. Format (i, '          2d ') equivalent to output two bits, insufficient fill space. When output 0-9 displays "Port 0", and output 10-99 displays "10" to achieve its function. The output is as follows: [Python] View plain copy 1 3 2 4 3 5 4 x 5 12.5 ut 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 outputs 1 to 100 even range (2,101,2). 3. Tuple loop [Python] view plain copy tup = (1,2,3,4,5) for n in tup:print N else:print ' End for ' tuple per The number of items cannot be modified, only readable, and sequence list[1,2,3,4] canModify. 4. File loop 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. " [Python] View plain copy #文件循环遍历三种对比 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: [Python] View plain copy #第一个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 #第二个readlines () output: reads a line S1 = ' Eastmount of CSDN ' for C in S1: ....            End #第三个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

  

Brother Lian Learning Python-------conditional statements and loop statements

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.