Home > Backend Development > Python Tutorial > Introduction to the basic knowledge of Python conditional statements and loop statements

Introduction to the basic knowledge of Python conditional statements and loop statements

高洛峰
Release: 2017-03-20 09:17:22
Original
1830 people have browsed it

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
Copy after login

##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
Copy after login

##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 &#39;count=&#39;,count 
if count>80: 
 print &#39;lager than 80&#39; 
else: 
 print &#39;lower than 80&#39; 
print &#39;End if-else&#39; 
 
#多分支if-elif-else 
number = input("please input:") 
print &#39;number=&#39;,number 
if number>=90: 
 print &#39;A&#39; 
elif number>=80: 
 print &#39;B&#39; 
elif number>=70: 
 print &#39;C&#39; 
elif number>=60: 
 print &#39;D&#39; 
else: 
 print &#39;No pass&#39; 
print &#39;End if-elif-else&#39; 
 
#条件判断 
sex = raw_input("plz input your sex:") 
if sex==&#39;male&#39; or sex==&#39;m&#39; or sex==&#39;man&#39;: 
 print &#39;Man&#39; 
else: 
 print &#39;Woman&#39;
Copy after login

2. Loop statement while

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

    while condition:
     statement
     statement
    else:
     statement
     statement
Copy after login

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 &#39;exit while&#39; 
print &#39;sum = &#39;,s 
 
&#39;&#39;&#39;&#39;&#39; 
输出结果为:exit while 
 sum = 5050 
&#39;&#39;&#39;
Copy after login

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(&#39;http://andy111.blog.sohu.com/46684846.html&#39;) 
 i=i+1 
 time.sleep(0.8) 
else: 
 os.system(&#39;taskkill /F /IM iexplore.exe&#39;) 
print &#39;close IE&#39;
Copy after login

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.

Introduction to the basic knowledge of Python conditional statements and loop statementstime.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 for

The The basic format of the loop statement is:

    for target in sequences:
    statements
Copy after login

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 = &#39;Eastmount of CSDN&#39; 
for c in s1: 
 print c,
Copy after login

注意:如果在print结尾加上逗号,那么接下来语句会与前一条语句在同一行打印.故上面输出显示一行.

2.列表循环

list1 = [1,3,4,5,&#39;x&#39;,12.5] 
i = 0 
for val in list1: 
 print format(i,&#39;2d&#39;),val 
 i = i+1 
else: 
 print &#39;out for&#39;
Copy after login

注意:列表List由一堆数据用逗号间隔,方括号括起,可以是同类型也可以是不同类型.format(i,'2d')相当于输出两位,不足的补空格.当输出0-9时显示"口0",而输出10-99时显示"10"实现对其功能.输出结果如下:

1 3 
2 4 
3 5 
4 x 
5 12.5 
ut for
Copy after login

因为迭代(循环另一种说法)某范围的数字是很常用的,所以有个内建的范围函数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 &#39;End for&#39;
Copy after login

元组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(&#39;for.py&#39;,&#39;r&#39;).read(): 
 print n, 
print &#39;End&#39; 
for n in open(&#39;for.py&#39;,&#39;r&#39;).readlines(): 
 print n, 
print &#39;End&#39; 
for n in open(&#39;for.py&#39;,&#39;r&#39;).readline(): 
 print n, 
print &#39;End&#39;
Copy after login

输出显示:

#第一个read()输出:每个字符间有个空格 
s 1 = &#39; E a s t m o u n t o f C S D N &#39; 
f o r c i n s 1 : 
.... 
End 
#第二个readlines()输出:读取的是一行 
s1 = &#39;Eastmount of CSDN&#39; 
for c in s1: 
.... 
End 
#第三个readline()输出:读取for.py文件第一行并输出 
s 1 = &#39; E a s t m o u n t o f C S D N &#39; 
End
Copy after login

如果需要文件输出也可以通过下面代码实现,使用w会覆盖而a+是追加功能,后面讲文件详细叙述.

 for r in open(&#39;test.txt&#39;,&#39;r&#39;).readlines():
 open(&#39;test.txt&#39;,&#39;a+&#39;).write(c)
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template