迴圈結構

yoyy3發表於2024-08-15

程式碼:

 # -*- coding:utf-8 -*-

#while語句
i=1;sum=0
while i<=100:
    if i%2!=0:
        sum=sum+i
    i=i+1
print "sum",sum
#不確定迴圈次數設定標誌
flag='y'
sum=0.0
count=0
while flag=='y':
    x=input("輸入數字:")
    sum=sum+x
    count=count+1
    flag=raw_input("y/n?")
print"平均成績是",sum/count
#訊號值迴圈控制法

sum1=0.0
count1=0
x = input("輸入數字:")
while x>0:
    sum=sum+x
    count=count+1
    x = input("輸入數字:")
print"平均成績是",sum/count


#無限迴圈
running=True
number=1

while running:
   guess = input("輸入數字:")
   if guess==number:
       print "猜對了"
       running=False
   elif  guess>number:
       print "猜大了"

'''for用於列表序列'''


fruits=['apple','pear','banana']
for fruit in fruits:
     print 'fruits have:',fruit

#else 與continue 語句


執行結果:


相關文章