1. 程式人生 > >python語法(三)— 迴圈

python語法(三)— 迴圈

上一篇,學習了python的判斷語句,瞭解了python中如何直線分支語句,本文來學習迴圈語句。python中有兩種迴圈while迴圈和for迴圈,當我們不知道迴圈次數時使用while迴圈,讓我們知道迴圈次數時使用for迴圈,下面來介紹具體使用方式。

while 迴圈

  • 語法
while expression :
    whileSuite

當expression 條件等於0或者為False時,退出迴圈。從語法可以看出,while語句其實和java的while語句是差不多的,唯一的區別就是這裡的條件是可以為0的。
下面我們看一個簡單的例項:
將1-100累加:

# -*- coding: utf-8 -*-
''' Created on 2018年12月19日 將1-100累加: @author: Herrt灬凌夜 ''' sum = 0; i = 1; while i <= 100 : sum = sum + i; i = i + 1; print("1-100的和為:%d" % sum);
  • break 語句
    break語句為迴圈語句中的結束語句,和java中的break語句一樣,可以直接結束迴圈語句,而去直接執行迴圈語句後面的其他語句。
# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
break語句

@author: Herrt灬凌夜
''' while True : n = input("退出(y/n):"); if n == "y" : break; print("退出");

上面語句,當用戶輸入y的時候直接退出while迴圈輸出退出,否則會一直讓使用者進行輸入。

  • continue 語句
    continue語句也是迴圈結束語句,但是它與break的不同之處在於它只結束當次迴圈,會繼續執行後面的迴圈語句,當然與java中的continue語句作用也是一致的。
    我們來看一個例子:
# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
continue語句:列印100以內的偶數

@author: Herrt灬凌夜
''' num = 0; while num <= 100 : if num % 2 != 0 : num = num + 1; continue print(num) num = num + 1

上面語句當num等於奇數時會執行continue,語句,跳出本次迴圈,所以這裡只輸出偶數。當然我們可以不使用其中的if語句而是將num = num + 1 直接改為 num = num + 2,但是我在這裡這麼寫只是為了說明continue的作用而已,所以請忽略我智障的寫法。

  • else 語句
    這裡的else語句是while的else語句,他在正常的while語句執行結束之後才會去執行,如果是break強制結束while迴圈,else中的語句也不會執行。
    我們可以將第一個例子改造為:
# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
將1-100累加:

@author: Herrt灬凌夜
'''
sum = 0;
i = 1;
while i <= 100 :
    sum = sum + i;
    i = i + 1;
else :
    print("1-100的和為:%d" % sum);

最後我們將昨天的那個猜拳遊戲進行改造,當人或者機器誰先達到10分誰贏,並且輸入quit可以退出遊戲。

# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
猜拳遊戲,當人或者機器誰先達到10分誰贏,並且輸入quit可以退出遊戲。

@author: Herrt灬凌夜
'''
import random;
computerScore = 0
personScore = 0;
personList = ["石頭", "剪刀", "", "quit"];
computer = random.choice(["石頭", "剪刀", ""]);
personTriumph = [["石頭", "剪刀"], ["", "石頭"], ["剪刀", ""]];
introduce = """
請出拳:
0.石頭
1.剪刀
2.布
3.退出遊戲    
""";

while computerScore < 10 and personScore < 10 :
    index = int(input(introduce));

    if index not in [0, 1, 2, 3] :
        print("輸入有誤,請重新輸入!");
        continue;

    if personList[index] == "quit" :
        print("您退出了遊戲!");
        break;

    print("你出了%s, 電腦出了%s" % (personList[index], computer));

    if personList[index] == computer :
        print ("平局");
    elif [personList[index], computer] in personTriumph :
        print ("你贏了");
        personScore += 1;
    else :
        print ("電腦贏了");
        computerScore += 1;
else :
    if personScore > computerScore :
        print("您當前得分為%s分,電腦得分為%s分,您獲勝了!" % (personScore, computerScore));
    else:
        print("您當前得分為%s分,電腦得分為%s分,電腦獲勝了!" % (personScore, computerScore));
 

for 迴圈

  • for 迴圈語法
for i in itrtable
    suiteToRepeat

for迴圈需要一個變數i和一個元素,其中i每次迴圈為itrtable的一個,並且for迴圈也支援while中的break,continue和else語句。
看個簡單的例子:

# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
for迴圈

@author: Herrt灬凌夜
'''
for i in "hello" :
    print(i)

上面就會依次輸出沒有個字母,但是會換行輸出,如果不想讓其換行可以在最後加一個print (i, end = "");

for i in "hello" :
    print (i, end = "");
  • range 函式
    range函式一般與for迴圈連用,range為迴圈提供迴圈條件。在之前的python2.0的時候還有一個xrange的函式,他不會立刻生成一個列表,而是使用了懶載入的方式,這樣可以更節省記憶體,執行效率也更高,但是在python3.0以後將xrange取消了,而是由range直接取代,但是作用其實是range的作用。
    range函式語法:
range(start,end,step)

其中startt為起始,end為結束,step為步長。我們看下面幾個例子:

# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
range函式

@author: Herrt灬凌夜
'''
for i in range(10) :
    print(i, end = " ");
else :
    print();

for i in range(5, 10) :
    print(i, end = " ");
else :
    print();   

for i in range(1, 10, 2) :
    print(i, end = " ");
else :
    print();
  • 列表解析
    列表解析是一種非常實用,非常簡單,也非常靈活的動態建立列表的方式。
    列表解析語法:
[expr for iterVar in iterable]

上述的語法中 expr 表示列表中的每一個成員,也可以是某種公式,而後面的則是一個迴圈,其實相當於迴圈去建立一個列表。
我們看下面的例子:

# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
列表解析

@author: Herrt灬凌夜
'''
print(["hello" for i in range(5)]);
print([i for i in range(5)]);
print([i * i for i in range(5)]);
print([i + (i + 1) for i in range(5)]);
print([i * i for i in range(5, 10)]);
print([i for i in range(0, 10, 2)]);

這樣,我們可以生成很多有規律的列表。

  • for 迴圈的幾個練習
    再簡單的語言都離不開練習,沒有練習,估計一個星期就會忘乾淨了,下面就來看幾個例子:
    1.使用者輸入一個數字,生成對應長度的斐波那契數列。
# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
使用者輸入一個數字,生成對應長度的斐波那契數列。

@author: Herrt灬凌夜
'''
fid = [0, 1];
while True :
    num = int(input("請輸入斐波那契數列的長度:")) - 2;
    if num < 0 :
        print("請輸入大於2的數字:");
    else :
        break;
for i in range(num) :
    fid.append(fid[-1] + fid[-2]);
else :
    print(fid);

2.根據使用者輸入,顯示乘法口訣表。

# -*- coding: utf-8 -*-
'''
Created on 2018年12月19日
2.根據使用者輸入,顯示乘法口訣表。

@author: Herrt灬凌夜
'''
while True :
    num = int(input("請輸入一個數字:"));
    if num < 1 :
        print("請輸入大於2的數字:");
    else :
        break;
for i in range(1, num + 1):
    for j in range(1, i+1):
        print("%sX%s=%s" % (i, j, i * j), end = " ")
    print();

今天主要學習了python的迴圈語句,while迴圈和for迴圈,可以在某些場景重複的執行某些程式碼。在後面還會繼續學習python的其他語法。

 

 

-------------------- END ---------------------

 

 

 

最後附上作者的微信公眾號地址和部落格地址 

 

 

 

公眾號:wuyouxin_gzh

 

 

 

 

 

 

 

 

 

 

Herrt灬凌夜:https://www.cnblogs.com/wuyx/