與小卡特一起學python 第11章 巢狀與可變迴圈

yarking207發表於2016-04-04
#11-1巢狀迴圈 ,一次列印3個乘法表
multiplier = 5
for i in range(1,11):
    print(i,"x",multiplier,"=",i*multiplier)
for multiplier in range (5,8):
    for i in range (1,11):
        print(i,"x",multiplier,"=",i*multiplier)
    print()

#11.2 可變迴圈
numStars = int(input("How many stars do you want?\n"))
for i in range (1,numStars+1): #for in range(0,numStars)一樣
    print("*",end="")

#11-3 可變巢狀迴圈
numLines = int(input("How many lines of stars do you want?\n"))#多少行
numStars = int(input("How many stars per line?\n"))#每行多少個星星
for line in range(0,numLines):
    for star in range(0,numStars):
        print("*",end = "")
    print()

#11-4 更多可變巢狀迴圈 更復雜的星星模組
numBlocks = int(input("How many blocks of srars do you want"))
for block in range(1,numBlocks + 1):
    for line in range(1,block * 2):
        for star in range(1,(block + line) * 2):
            print("*",end="")
        print()
    print()

#11-5 在巢狀迴圈中列印迴圈變數
numBlocks = int(input("How many blocks of stars do you want?"))
for block in range(1,numBlocks +1):
    for line in range(1,block * 2):
        for star in range(1,(block + line) *2):
            print("*",end = "")
        print("line=",line,"star=",star)
    print()
#11-6 熱狗組合
print("\tDOG \tBun \tKetchup\tMustard\tOnions")#z注意空格,因為有的單詞比較長
count = 1
for dog in [0,1]:
    for bun in [0,1]:
        for ketchup in [0,1]:
            for mustard in [0,1]:
                for onion in [0,1]:
                    print("#",count,"\t",end = "")#不換行符號
                    print (dog,"\t",bun,"\t",ketchup,"\t",mustard,"\t",onion,"\t")
                    count = count +1

#11-7 程式碼清單,計算卡路里的熱狗程式
#列出熱狗各個部分的卡路里
dog_cal = 140
bun_cal = 120
ket_cal = 80
mus_cal = 20
onion_cal = 40
print("\tDog \tBun \tKetchup\tMustard\tOnions\tCalories")
count = 1
for dog in [0,1]:#熱狗程式是外迴圈
    for bun in [0,1]:
        for ketchup in [0,1]:
            for mustard in [0,1]:
                for onion in [0,1]:
                    total_cal = (bun*bun_cal)+(dog*dog_cal)+ \
                                (ketchup * ket_cal) + (mustard * mus_cal) +\
                                (onion * onion_cal)
                    print("#",count,"\t",end="")
                    print(dog,"\t",bun,"\t",ketchup,"\t",mustard,"\t",onion,"\t",total_cal)
                    count= count + 1
        

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220205/viewspace-2074842/,如需轉載,請註明出處,否則將追究法律責任。

相關文章