Python循环

循环

 python中的循环控制语句有for语句和while语句,可用来遍历某一对象。其中for语句附带的else块,主要用于处理for语句中包含的break语句。

 

for循环

for语句的格式如下:

for <> in <对象集合>:

if <条件>:

       break

else   if <条件>:

       continue

   <其他语句>

else:

   <>

for looper in [1,2,3,4,5]:                 #循环输出单一语句
    print("I Love HaoHao!")
    
for looper in [1,2,3,4,5]:                 #循环输出循环次数
    print(looper)
    
for looper in [1,2,3,4,5]:                 #循环输出与数乘积
    print(looper,"Times 8=",looper*8)

for looper in range(1,5):                  #range()从第一个数据开始,到最后一个数字之前
    print (looper,"times 8=",looper*8)
    
for looper in range(5):                    #range()简写,只输入上界,默认从零开始
    print(looper)

for letter in "Hi,there":                  #逐个输出字母,print每一次输出完换行
        print (letter)

for i in range(1,10,2):                    #按步长为2循环输出1到10
    print(i)    

for i in range(10,0,-1):                   #按步长为-1,倒序输出10到1
    print(i)    

import time                                #按步长为-1,倒序输出10到1
for i in range(10,0,-1):
    print (i)
time.sleep(1)                              #等待一秒
print ("blast off!")

range()包含第一个数字到最后一个十字之前的整数,默认步长为1;只输入上界默认从0开始。

Python中要用到时间是要调用time模块,既要有语句“import time”。

例1:输出乘法表

print("Multiplication Table")
#Display the number title
print(" ",end=' ')
for j in range(1,10):
print(" ",j,end=' ')
print() #jump to the new line
print("_________________________________________________")

#Display table body
for i in range(1,10):
print(i,"|",end=' ')
for j in range(1,10):
#Display the product and align properly
print(format(i*j,"4d"),end=' ')
print() #Jump to the new line

break 在需要时终止for循环,如果for循环未被break终止,则执行else块中的语句。

continue 跳过位于其后的语句,开始下一轮循环。

例2:输出星星

numstars=int(input("How many stars do you want?"))              #输出输入数-1颗*
for i in range(1,numstars):
    print('*')

numstars=int(input("How many stars do you want?"))              #输出输入数颗*
for i in range(0,numstars):
    print('*')

numblocks=int(input  ("How many blocks of stars do you want?")) #输出输入数-1颗*
numlines=int(input  ("How many lines in each block?"))   
numstars=int(input  ("How many stars per line?"))   
for blocks in range(0,numblocks):
    for lines in range(0,numlines):
        for stars in range(0,numstars):
            print('*'),
        print
    print

注意:for循环的缩进量应该严格控制,否则会产生错误结果。

while循环

for语句的格式如下:

while  <对象集合>:

         <>

else: 

    <>

例3:求两个整数的最大公因子(Prompt the user to enter two integers)

n1=eval(input("Enter first integer:"))
n2=eval(input("Enter second integer:"))

gcd=1
k=2
while k<=n1 and k<=n2:
if n1%k==0 and n2%k==0:
gcd=k
k+=1

print("The greatest common divisor for",n1,"and",n2,"is",gcd)

在 python 中,while … else 在循环条件为 false 时执行 else 语句块。

判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

注意:无限循环(死循环)可以使用 CTRL+C 来中断循环。

posted @ 2017-09-28 23:42  【SmarT】  阅读(498)  评论(0编辑  收藏  举报