python入門—認識while迴圈及運用

來源:互聯網
上載者:User

標籤:==   嵌套   inpu   運用   class   判斷   +=   put   end   

本節內容

1、認識while迴圈
2、while迴圈的運用
3、嵌套迴圈:迴圈套迴圈

 

1、認識while迴圈

break # 終止當前迴圈

continue #跳出當次迴圈

1 while 判斷條件:   #當while滿足條件時,程式會一直迴圈2     執行語句...3 else:   #當while正常迴圈完成後,,程式才會進行else 註:break會終止while迴圈,所以程式不會進行else;而continue是跳過當次迴圈,所以程式會進行else4     執行語句...

 

2、while迴圈的運用

使用者輸入一個值,猜出正確的年齡

 1 age = 60 2 while True: 3     guess_age = int(input("年齡:")) 4     if guess_age == age: 5         print("恭喜你!猜對了!") 6         break 7     elif guess_age > age: 8         print("猜大了!") 9     else:10         print("猜小了!")11 else:12     print("End")

 

3、嵌套迴圈:迴圈套迴圈

(1)使用 # 號輸出一個長方形,使用者可以指定寬和高。列如:長為3,高為4,就輸出一個橫著有3個#號,豎著有4個#號的長方形

 1 height = int(input("高度:")) 2 width = int(input("寬度:")) 3 num1 = 1 4 while num1 <= height: 5     num2 = 1 6     while num2 <= width: 7         print("#",end="") 8         num2 += 1 9     num1 += 110     print()11 else:12     print("End")

(2)用while迴圈輸入“九九乘法表”

 1 num1 = 1 2 while num1 <= 9: 3     num2 = 1 4     while num2 <= num1: 5         num3 = num2 * num1 6         print(num1, "*", num2, "=", num3, end="   ") 7         num2 += 1 8     print() 9     num1 += 110 else:11     print("九九乘法表")

 

python入門—認識while迴圈及運用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.