第3課,python使用for循環


前言:

  學習了python的while循環后感覺循環是挺強大的。下面學習一個更智能,更強大的循環-- for循環。

課程內容:

  1、由while循環,到for循環,格式和注意項

  2、for循環來報數

  3、for循環的智能操作

 

一圖

 

格式和注意項

  while循環的格式,  

  1. 條件

  2. 冒號

  3.tab縮進 (冒號和縮進是搭配使用的)

1 while 條件:
2     pass
3 
4 如,
5 a = 1
6 while a < 3:
7     print("hi")
8     a = a + 1

  for 循環的格式,

  1. for 變量 in 可迭代對象

  2. 冒號

  3. tab縮進

1 for 變量 in 可迭代對象:
2     pass
3 
4 如輸出三次,“帥鍋”,
5 
6 for a in range(3):
7     print("甩鍋")

  其中,range() 是python的一個內置函數,用於生成一系列連續的整數, 是一個可迭代對象。

  語法

  range(start, stop[, step])

  參數

  start--->>從某數開始計數,默認0

  stop--->>從某數結束,顧頭不顧尾

  step--->>步長

  要求,用循環及turtle庫畫三個圓或者三個同心圓

 1 #example 1
 2 import turtle as t
 3 a = 1 
 4 while a < 4:
 5     t.circle(30+a*10)
 6     a = a+1
 7 
 8 #example 2
 9 import turtle as t
10 for a range(1,4):
11     t.circle(30+a*10)
12 
13 #example 3
14 import turtle as t
15 for a range(40,60+1, 10):
16     t.circle(a)

  

 

 

 

報數

  請輸出0-10的數字  

 1 #example 1
 2 for i in range(11):
 3     print(i)
 4 
 5 #example 2
 6 for i in range(0,11):
 7     print(i)
 8 
 9 #example 3
10 for i in range(0,11, 1):
11     print(i)

  請輸出0-10的偶數

1 for i in range(0,11, 2):
2      print(i)

開啟for循環的智能操作

  我想用for循環輸出幾個心意的數字,66,88,99,68,6,0,1,8,888,686

 1 #智能的必然是簡單的
 2 #example 1
 3 for i in [66,88,99,68,6,0,1,8,888,686]:
 4     print(i)
 5 
 6 #example 2
 7 a = [66,88,99,68,6,0,1,8,888,686]
 8 for i in a:
 9     print(i)
10 
11 #example 3
12 a = [66,88,99,68,6,0,1,8,888,686]
13 for i in range(10):
14     print(a[i])

其中,[66,88,99,68,6,0,1,8,888,686]叫做列表,可以用下標引用,如上面 #example 3 ,  a[0]就是66,a[9]就是686.

 

寫在最后

  for循環在做,有明確次數的循環時,配合range是很方便的,不用定義變量,不用手動改變數據就能實現。

       for配合列表等可迭代對象就能輕松的遍歷里面的數據,智能的很

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM