目錄
零基礎 Python 學習路線推薦 : Python 學習目錄 >> Python 基礎入門
一.Python 計算總分數和平均分源碼
有位小粉絲后台公眾號后台留言,需求是使用 Python 從鍵盤上輸入學生的姓名,語文數學英語成績,計算平均分和總分,然后輸出這個學生的姓名,平均分和總分,源碼如下:
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:猿說編程
@Blog(個人博客地址): www.codersrc.com
@File:Python 計算總分數和平均分.py
@Time:2021/05/18 07:37
@Motto:不積跬步無以至千里,不積小流無以成江海,程序人生的精彩需要堅持不懈地積累!
"""
def main():
# 數學成績
maths_score = 0
# 英語成績
english_score = 0
# 姓名
name = input("請輸出姓名:")
while True:
# 增加異常處理,當輸入不是純數字的時候,提醒輸入錯誤
try:
# input 的默認返回值是 str字符串類型,需要通過float強制轉換一下
maths_score = float(input("請輸入數學成績:"))
english_score = float(input("請輸入英語成績:"))
break
except:
print("輸入錯誤,分數請用數字表示....")
print("你輸入的姓名是:%s 總分:%d 平均分:%f "%(name,maths_score+english_score,(maths_score+english_score)/2.0))
if __name__ == "__main__":
main()
'''
測試結果:
請輸出姓名:熊孩子
請輸入數學成績:DF
輸入錯誤,分數請用數字表示....
請輸入數學成績:45
請輸入英語成績:FDF
輸入錯誤,分數請用數字表示....
請輸入數學成績:45
請輸入英語成績:78
你輸入的姓名是:熊孩子 總分:123 平均分:61.500000
'''
程序中加了 try except 異常處理,避免用戶在輸入錯誤的時候程序異常崩潰退出,這樣可以增加程序的健壯性;源碼沒幾行,比較簡單,小鮮肉加油~~
二.猜你喜歡
- Python 條件推導式
- Python 列表推導式
- Python 字典推導式
- Python 不定長參數 *argc/**kargcs
- Python 匿名函數 lambda
- Python return 邏輯判斷表達式
- Python is 和 == 區別
- Python 可變數據類型和不可變數據類型
- Python 淺拷貝和深拷貝
- Python 異常處理
- Python 線程創建和傳參
- Python 線程互斥鎖 Lock
- Python 線程時間 Event
- Python 線程條件變量 Condition
- Python 線程定時器 Timer
- Python 線程信號量 Semaphore
- Python 線程障礙對象 Barrier
- Python 線程隊列 Queue – FIFO
- Python 線程隊列 LifoQueue – LIFO
- Python 線程優先隊列 PriorityQueue
- Python 線程池 ThreadPoolExecutor(一)
- Python 線程池 ThreadPoolExecutor(二)
- Python 進程 Process 模塊
- Python 進程 Process 與線程 threading 區別
- Python 進程間通信 Queue / Pipe
未經允許不得轉載:猿說編程 » Python 計算總分數和平均分
本文由博客 - 猿說編程 猿說編程 發布!
