1. 程式人生 > >3.2Python while循環實例

3.2Python while循環實例

print pri utf-8 乘法表 空行 date 乘法 end int()

實例1:輸出100以內的奇數

# -*-coding:utf-8 -*-
__date__ = ‘2018/2/5 17:10‘
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘while1‘
n=1
while n <=100:
    print(n)
    n+=2

//打印奇數

實例2:while……else……語句
Python中的特殊結構:
While 條件:
……
else:
……
Else只有在循環正常結束的時候才能執行,break的時候不能執行,其余時候都能執行。

m=1
while m<10:
    print(m)
    m+=1
else:
    print("finish!")

實例三:結尾自定義
python默認以空格結尾

print("hello world!",end="____")     //\n   \r    \t
print("hello world!",end="____")
print("hello world!",end="____")

hello world!hello world!hello world!____

print()
空行

實例4:輸出九九乘法表

# -*-coding:utf-8 -*-
__date__ = ‘2018/2/5 17:33‘
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘九九乘法表‘

i=1
j=1
while i <10:
    j=1
    while j<=i:
        print("%d * %d=%d"%(i,j,(i*j)),end="      ")
        j+=1
    print( )
    i+=1

3.2Python while循環實例