1. 程式人生 > >學習python課程第四天

學習python課程第四天

循環嵌套 循環 ron 麻煩 else 工作 計算 () while

一.流程控制之 if else:

既然我們編程的目的是為了控制計算機能夠像人腦一樣工作,那麽人腦能做什麽,就需要程序中有相應的機制去模擬。

人腦無非是數學運算和邏輯運算,對於數學運算在上一節我們已經說過了。對於邏輯運算,即人根據外部條件的變化而做出不同的反映,比如:

1.如果:女人的年齡>30歲,那麽:叫阿姨

age_of_girl=31
if age_of_girl > 30:
    print(‘阿姨好‘)
2 如果:女人的年齡>30歲,那麽:叫阿姨,否則:叫小姐
age_of_girl=18
if age_of_girl > 30:
    print(‘阿姨好‘)
else:
    print(‘小姐好‘)
3 如果:女人的年齡>=18並且<22歲並且身高>170並且體重<100並且是漂亮的,那麽:表白,否則:叫阿姨
age_of_girl=18
height=171
weight=99
is_pretty=True
if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    print(‘表白...‘)else:
    print(‘阿姨好‘)
4.if 套 if
在表白的基礎上繼續:
如果表白成功,那麽:在一起
否則:打印。。。

age_of_girl=18
height=171
weight=99
is_pretty=True

success=False

if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    if success:
        print(‘表白成功,在一起‘)
    else:
        print(‘什麽愛情不愛情的,愛nmlgb的愛情,愛nmlg啊...‘)
else:
    print(‘阿姨好‘)

5.如果:成績>=90,那麽:優秀

如果成績>=80且<90,那麽:良好

如果成績>=70且<80,那麽:普通

其他情況:很差

score=input(‘>>: ‘)
score=int(score)

if score >= 90:
    print(‘優秀‘)
elif score >= 80:
    print(‘良好‘)
elif score >= 70:
    print(‘普通‘)
else:
    print(‘很差‘)



二.流程控制之while:
1 為何要用循環
程序員對於重復使用一段代碼是不恥的, 而且如果以後修改程序會很麻煩.
while條件循環, 語法如下:
while 條件:    
     循環體
 
     如果條件為真,那麽循環體則執行,執行完畢後再次循環,重新判斷條件。。。
     如果條件為假,那麽循環體不執行,循環終止.
打印0-10
count=0
while count <= 10:
    print(count)
    count+=1
打印0-10之間的偶數
count=0
while count <= 10:
    if count%2 == 0:
        print(count)
    count+=1
打印0-10之間的奇數
count=0
while count <= 10:
    if count%2 == 1:
        print(count)
    count+=1
2.死循環:
import time
num=0
while True:
    print(‘count‘,num)
    time.sleep(1)
    num+=1 
4 循環嵌套與tag
tag=True 

  while tag:

    ......

    while tag:

      ........

      while tag:

        tag=False
5.break 與 continue
break可以把while的代碼塊循環強制停止,
continue可以把while代碼塊循環的本次停止.

三.流程控制之for循環:

1 叠代式循環:for,語法如下

  for i in range(10):

    縮進的代碼塊

2.循環嵌套:

for i in range(1,10):
    for j in range(1,i+1):
        print(‘%s*%s=%s‘ %(i,j,i*j),end=‘ ‘)
    print()

學習python課程第四天