Python基礎知識(三)–基本的異常處理、算術運算子、輸入/輸出

來源:互聯網
上載者:User

異常處理

 
  1. try:
  2. try_suite
  3. except exception1 as variable1:
  4. exception_suite1
  5. ...
  6. except exceptionN as variableN:
  7. exception_suiteN
 
  1. s = input("enter an integer:")
  2. try:
  3. i = int(s)
  4. print("valid integer entered:", i)
  5. except ValueError as err:
  6. print(err)
  7. #invalid literal for int() with base 10: '3.5'

算術運算子

+ - * / += ...

 
  1. seeds = ['sesame', 'sunflower', 'pumpkin']
  2. seeds += ['poppy']
  3. print(seeds)
  4. #['sesame', 'sunflower', 'pumpkin', 'poppy']
  5. #這個時候的運算同seeds.append('poppy')等價
  6. seeds += 2
  7. #TypeError: 'int' object is not iterable
  8. #類型不符
  9. seeds += 'durian'
  10. print(seeds)
  11. #['sesame', 'sunflower', 'pumpkin', 'poppy', 'd', 'u', 'r', 'i', 'a', 'n']
  12. #不同類型的即便可以執行,也會出現比較奇怪的結果
  13. #這個時候用seeds.append('durian')可得到正確的結果

輸入/輸出

input()

print()

 
  1. #!user/bin/env python3
  2. print("Type integers, each followed by Enter; or just Enter to finish")
  3. total = 0
  4. count = 0
  5. while True:
  6. line = input("integer:") #輸入數字
  7. if line: #如果非空
  8. try:
  9. number = int(line) #轉換成整數
  10. except ValueError as err:
  11. print(err) #非整數
  12. continue
  13. total += number
  14. count += 1
  15. else:
  16. break
  17. if count:
  18. print("count = ", count, "total = ", total, "mean = ", total / count)

* 應該盡量將異常處理模組放在程式末尾,以保證主要流程儘可能清晰

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.