Introduction to the basics of Python conditional statements and looping statements

Source: Internet
Author: User
Tags print format
This article mainly introduces the basic knowledge of Python conditional statements and circular statements. The main contents include: 1. Conditional statements: Includes single, dual, and multi-branch statements, if-elif-else;2. Loop statement: While using and simple network brush spider crawler; 3. Loop statement: Use for and traverse lists, tuples, files, and strings.

This article describes the basics of Python's conditional statements and looping statements. 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-else count = input ("Please input:") print ' count= ', Count if count>80:  print ' lager than ' else:  print ' Lower than ' print ' End if-else '  #多分支if-elif-else number = input ("Please input:") print ' number= ', number if number& GT;=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+. +100 i = 1 s = 0 while I <=:  s = s+i  i = i+1 else:  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 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 (' 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 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 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 = 0 for Val in list1:  print format (i, ' 2d '), val  i = i+1 else:  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.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 an even range of 1 to 100 (2,101,2).

3. Tuple loops

Tup = (1,2,3,4,5) for n in tup:  print n else:  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 ():  pri NT 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 s1='eastmountofcsdn'forcins1:.... 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

If you need 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)

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.