Home > Backend Development > Python Tutorial > Python中for循环和while循环的基本使用方法

Python中for循环和while循环的基本使用方法

WBOY
Release: 2016-06-10 15:07:58
Original
1727 people have browsed it

while循环:

while expression:
  suite_to_repeat
Copy after login

while 条件:
语句块

不需要括号哦!

>>> x 
1.2 
>>> while x < 2: 
 print(x) 
 x += 0.2 
 
  
1.2 
1.4 
1.5999999999999999 
1.7999999999999998 
1.9999999999999998 
>>> 

Copy after login

经常用 :

while True: 
 .... 
 if ... : 
  break 
 .... 
Copy after login

for循环:

for iter_var in iterable:
  suite_to_repeat
Copy after login

for循环访问可迭代对象iterable的所有元素,iter_var被设置为可迭代对象的当前元素。for循环可用于序列类型,包括字符串、列表及元组,也可用于迭代器类型,迭代器对象有一个next()方法,调用后返回下一个条目,所有条目迭代完成后,迭代器引发一个StopIteration异常告诉程序循环结束,for语句在内部调用next()并捕获异常。

for something in XXXX:
语句块

即表示对XXXX中的每一个元素,执行某些语句块,XXXX可以是列表,字典,元组,迭代器等等。

>>> for x in range(0,10): 
 print(x*x) 
 
  
0 
1 
4 
9 
16 
25 
36 
49 
64 
81 
Copy after login


这是 for..else...语句
仅在没有 break 的情况下执行,或者说,只要你没有 break,它就会执行

>>> for n in range(99,81,-1): 
 root = sqrt(n) 
 if root == int(root): 
  print (n) 
  break 
else: 
 print ("I didn't fint it") 
 
  
I didn't fint it 

Copy after login

但你应该尽可能使用列表推导式,因为它更方便,清晰

>>> [x*x for x in range(1,5)] 
[1, 4, 9, 16] 
>>> [x**2 for x in range(1,10) if x % 2 ==0] 
[4, 16, 36, 64] 
>>> [(x,y) for x in range(1,3) for y in range(4,6)] 
[(1, 4), (1, 5), (2, 4), (2, 5)] 

Copy after login

break、continue、pass:
break语句结束当前循环,跳转到下条语句。continue语句终止当前循环,尝试下一次迭代。pass语句表示不做任何事情。
循环中的else:
在循环中也可以有else,这与C/C++不同,else字句只在循环完成后执行,也就是说break语句会跳过else块。

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