Python Topic 2: Basic knowledge of conditional and cyclic statements, and basic knowledge of python

Source: Internet
Author: User
Tags print format

Python Topic 2: Basic knowledge of conditional and cyclic statements, and basic knowledge of python

Previously, I talked about "Topic 1. Basic knowledge of functions". This article describes the basic knowledge of Python conditional statements and cyclic statements. The main content includes:

1. conditional statements: including single branch, dual branch, and multi-branch statements, if-elif-else

2. Loop statement: Use of while and Web Crawler

3. Loop statement: Use and traverse the list, tuples, files, and strings of

Statement Block

Before talking about conditional statements, cyclic statements, and other statements, we should first add the knowledge of statement blocks. (We have used these functions before)

A statement block is a group of statements that are executed or executed multiple times when the condition is true (Condition Statement. place spaces or tab characters before the code to indent the statement to create a statement block. many special words or characters (such as begin or {) are used to indicate the start of a statement block. Other words or characters (such as end or}) are used to indicate the end of the statement block.

In Python, the colon (:) is used to mark the beginning of the statement block. Each statement in the block is indented (with the same indentation ). when it is rolled back to the same indentation as the closed block, it indicates that the current block has ended.

I. conditional statement if

There are three common types of if branch statement expressions:

1. Single Branch statement

The basic format is:

   if condition:   statement   statement

Note that the if Condition Statement condition in Ptthon does not require parentheses (), and a colon must be added after the condition. It does not have curly braces {}, but uses TAB to differentiate. the condition usually has a Boolean expression (True | False 0-False | 1-True or not 0 is True), a relational expression (>===! =) And logical operation expressions (and or not ).

2. Dual-branch statements

The basic format is:

   if condition:   statement   statement   else:   statement   statement

3. multi-branch statements

If multi-branch is composed of if-elif-else, where elif is equivalent to else if, and it can use the nesting of multiple if. The Code is as follows:

# Dual branch if-else count = input ("please input:") print 'count = ', count if count> 80: print 'lager than 80' else: print 'lower than 80' print 'end if-else' # multi-branch if-elif-else number = input ("please input:") print 'Number = ', number if 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' # conditional judgment sex = raw_input ("plz input your sex :") if sex = 'male' or sex = 'M' or sex = 'man ': print 'man' else: print 'Woman'

Ii. Loop statement while

The basic format of the while LOOP statement is as follows:

    while condition:     statement     statement    else:     statement     statement

The condition statement can be a Boolean, relational, and logical expression. else can be omitted (the difference is listed here). For example:

# Loop while counting 1 + 2 + .. + 100 I = 1 s = 0 while I <= 100: s = s + I = I + 1 else: print 'exit while 'print 'sum = ', s ''' output: exit while sum = 5050 '''

The output result is 5050. When I is added to 101, Because I> 100 will execute the else statement.

Note that in Python, a line comment is indicated by a pound sign (#), and three quotation marks ('''... ''') indicates multi-line comments. different from C/C ++'s/line comment and/**/multi-line comment.

The following describes a code refresh bot crawler. The Code will be explained first:

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 Sohu blog or Sina Blog, as long as the browser is opened in a new window, the number of browsing visits is increased. Therefore, the above Code mainly opens a new window by calling open_new_tab of webbrowser, CSDN does not work (it is estimated that the user or ip address is bound ).

In the code above, taskkill is used to kill the IE browser of the application. In DOS, enter "taskkill/F/IM iexplore.exe" to forcibly close the application (chrome.exeor qq.exe), where/F indicates that the program is forcibly terminated, /IM indicates the image. in this program, the main function is to clear the memory to prevent the memory consumption from getting too large. However, you need to call the system () function of the import OS to open it, in Linux, kill-pid or killall is used to terminate the process.

In the code, time. sleep (seconds) indicates "Delay execution for a given number of seconds.", which takes some time from opening to loading.

When you need to increase the page views in large quantities, you can use two layers of nested loops. Each time you open five webpages, you can close them for 100 times. In this way, your memory will not crash because of the high consumption, you can also use import random count = random. randint (20, 40) generates a random number of 20 to 40 to execute an outer loop. the code is relatively simple, mainly to introduce some basic Python knowledge through it. however, when you open ie for the first time, the number of opened requests is inconsistent. why?

Iii. Loop statement

The basic format of the loop statement is:

    for target in sequences:    statements

Target indicates the variable name, and sequences indicates the sequence. Common types include list, tuple, strings, and files ).

The for of Python does not reflect the number of loops. Unlike the for (I = 0; I <10; I ++) in C, in Python, for refers to the number of times the data items in the sequences are stored in the target. the in operator checks whether a value is in the sequence. you can also use break and continue to exit the loop.

1. String Loop

s1 = 'Eastmount of CSDN' for c in s1:  print c, 

Note: If a comma is added to the end of print, the next statement is printed in the same line as the previous statement. Therefore, the output shows a line.

2. List Loop

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: A List is separated by commas (,). It can be of the same type or of different types. format (I, '2d ') is equivalent to two output fields with spaces filled in. "port 0" is displayed when 0-9 is output, and "10" is displayed when 10-99 is output. the output result is as follows:

1 3 2 4 3 5 4 x 5 12.5 ut for 

Because iterations (loop another statement) numbers in a certain range are very common, there is a built-in range function range for use. in the list, for n in [,] is equivalent to listNum = range ). the format is "range (start, stop [, step])-> list of integers", which works in a similar way as a shard and contains the lower limit (range () in this example) (1), but does not include the upper limit (9 in this example). If you want the lower limit to 0, you can only provide the upper limit, for example, range (4) = [,].

Generate a number range (100) from 1 to 1,101, output an odd range (100, 2) from 1 to 1,101, and output an even range (100, 2) from 1 to 2,101 ).

3. tuples Loop

tup = (1,2,3,4,5) for n in tup:  print n else:  print 'End for' 

Each data item in the tuple cannot be modified and can only be read. The sequence list [1, 2, 3, 4] can be modified.

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. "It is equivalent to reading n rows, consisting of n readlines and a list of read strings.

Help (file. readline) reads a row from a file. "readline ([size])-> next line from the file, as a string ."

# Comparison of Three Types of file traversal: for n in open ('. py', 'R '). read (): print n, print 'end' for n in open ('. py', 'R '). readlines (): print n, print 'end' for n in open ('. py', 'R '). readline (): print n, print 'end'

Output:

# First 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: Read a row s1 = 'astmount of CSDN 'for c in s1 :.... end # Third readline () Output: Read. the first line of the py file and output s 1 = 'e a s t m o u n t o f c s d n' End

If file output is required, you can use the following code. w will overwrite and a + will be used as the append function, which will be described in detail later.

 for r in open('test.txt','r').readlines(): open('test.txt','a+').write(c)

PS: I mainly learned through "Python basics" and "python video of zhipu education at 51CTO College. therefore, the article cited 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 ~

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!

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.