This article mainly introduces the basic knowledge of Python conditional statements and loop statements. The main content includes: 1. Conditional statements: including single branch, double branch and multi-branch statements, if-elif-else; 2. Loop statements: the use of while and simple web browser crawlers; 3. Loop statements: the use of for and iterate over lists, tuples, files, and strings.
This article talks about the basic knowledge of Python's conditional statements and loop statements. The main content includes:
1. Conditional statements: including single branch, double branch and multi-branch statements ,if-elif-else
2. Loop statement: use of while and simple web browser crawler
3. Loop statement: The use of for and traversing lists, tuples, files and strings
Preface: Statement block
talks about conditional statements, loop statements and other statements Before that, let’s supplement the knowledge of statement blocks. (We have already used it when talking about functions earlier)
Statement blocks are not a kind of statement. They are executed or executed multiple times (loops) when the condition is true (conditional statement). statement). A statement block can be created by placing a space or tab character before the code to indent the statement. Many language special words or characters (such as begin or {) represent the beginning of a statement block, and use another word or Characters (such as end or }) to indicate the end of a statement block.
In Python, a colon (:) is used to identify the beginning of a statement block. Each statement in the block is abbreviated. (the indentation amount is the same). When the indentation amount is the same as that of the closed block, it means that the current block has ended.
1. Condition Statement if
There are three common basic types of if branch statement expressions:
1. Single branch statement
Its basic format is:
if condition: statement statement
##It should be noted that the if conditional statement in Ptthon does not require parentheses () , a colon needs to be added after the condition. It does not have curly braces {} but uses TAB to realize the distinction. Among them, the condition condition judgment usually includes Boolean expressions (True|False 0-False|1-True, either 0 or true), relational expressions ( >= <= == !=) and logical operation expression (and or not).
2. Double branch statement
Its basic format is:if condition: statement statement else: statement statement
##3. Multi-branch statementIf multi-branch consists of if-elif-else, where elif is equivalent to else if, and it can use the nesting of multiple ifs. The specific code is as follows:
#双分支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' #多分支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' #条件判断 sex = raw_input("plz input your sex:") if sex=='male' or sex=='m' or sex=='man': print 'Man' else: print 'Woman'
The basic format of the while loop statement is as follows:
while condition: statement statement else: statement statement
The judgment condition statement condition can be a Boolean expression, a relational expression and a logical expression, and else can be omitted (listed here to distinguish it from C language). For example:
#循环while计数1+2+..+100 i = 1 s = 0 while i <= 100: s = s+i i = i+1 else: print 'exit while' print 'sum = ',s ''''' 输出结果为:exit while sum = 5050 '''
The output result is 5050. When i is added to 101, the else statement will be executed because i>100.
Things to note In Python, pound signs (#) are used to indicate line comments, and triple quotes ('''...''') are used to indicate multi-line comments. They are different from // line comments and /**/ multi-line comments in C/C++ .The following is a piece of code to brush the blog crawler. The code is given first and then explained:
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 As long as the blog or Sina blog is opened in a new window, the number of browsing visits will increase, so the above code mainly opens a new window by calling open_new_tab of the webbrowser browser, but CSDN does not work (it is estimated to be related to binding the 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 forcefully close the application (chrome.exe or qq.exe), where /F means forcibly terminating the program, and /IM means image. The main function of this program is to clear the memory and prevent it from crashing if the memory consumption is too large; however, you need to call the system() function of import os to open it. , and use the kill command (kill -pid or killall) to terminate the process under Linux.
time.sleep(seconds) in the code means "Delay execution for a given number of seconds.", there will be a certain amount of time from opening to loading.
When you need to increase the number of views a lot, you can use two levels of loop nesting. Each time you open 5 web pages, close them and execute 100 times, so that your memory will not crash due to excessive memory consumption. You can also use import random count=random.randint(20,40) to generate 20 to 40 random numbers to execute the outer loop. The code is relatively simple, mainly I want to introduce some basic knowledge of Python through it. However, when opening IE browser for the first time, an error of inconsistent opening times will appear. Why?
3. Loop statement forThe The basic format of the loop statement is:
for target in sequences: statements
target表示变量名,sequences表示序列,常见类型有list(列表)、tuple(元组)、strings(字符串)和files(文件).
Python的for没有体现出循环的次数,不像C语言的for(i=0;i<10;i++)中i循环计数,Python的for指每次从序列sequences里面的数据项取值放到target里,取完即结束,取多少次循环多少次.其中in为成员资格运算符,检查一个值是否在序列中.同样可以使用break和continue跳出循环.
1.字符串循环
s1 = 'Eastmount of CSDN' for c in s1: print c,
注意:如果在print结尾加上逗号,那么接下来语句会与前一条语句在同一行打印.故上面输出显示一行.
2.列表循环
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'
注意:列表List由一堆数据用逗号间隔,方括号括起,可以是同类型也可以是不同类型.format(i,'2d')相当于输出两位,不足的补空格.当输出0-9时显示"口0",而输出10-99时显示"10"实现对其功能.输出结果如下:
1 3 2 4 3 5 4 x 5 12.5 ut for
因为迭代(循环另一种说法)某范围的数字是很常用的,所以有个内建的范围函数range供使用.列表中for n in [1,2,3,4,5,6,7,8]相当于listNum=range(1,9).其格式"range(start, stop[, step]) -> list of integers",它的工作方式类似于分片,它包含下限(本例range(1,9)中为1),但不包含上限(本例中9),如果希望下限为0,可以只提供上限如range(4)=[0,1,2,3].
产生1到100的数字range(1,101),输出1到100的奇数range(1,101,2),输出1到100的偶数range(2,101,2).
3.元组循环
tup = (1,2,3,4,5) for n in tup: print n else: print 'End for'
元组tuple每个数据项不可修改,只可读,而序列list[1,2,3,4]可以修改.
4.文件循环
help(file.read)返回一个字符串."read([size]) -> read at most size bytes, returned as a string."
help(file.readlines)返回一个列表."readlines([size]) -> list of strings, each a line from the file."相当于读n行,由n次readline组成,读出的字符串构成列表.
help(file.readline)从某个文件读一行."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'
输出显示:
#第一个read()输出:每个字符间有个空格 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()输出:读取的是一行 s1 = 'Eastmount of CSDN' for c in s1: .... End #第三个readline()输出:读取for.py文件第一行并输出 s 1 = ' E a s t m o u n t o f C S D N ' End
如果需要文件输出也可以通过下面代码实现,使用w会覆盖而a+是追加功能,后面讲文件详细叙述.
for r in open('test.txt','r').readlines(): open('test.txt','a+').write(c)
The above is the detailed content of Introduction to the basic knowledge of Python conditional statements and loop statements. For more information, please follow other related articles on the PHP Chinese website!