Python/Basic/chick_python_exam/Unit1_basic/program/inputSplitNum.py
2024-06-27 15:41:10 +08:00

17 lines
840 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#程式接受單列多筆輸入把輸入0之前的數值加總忽略非數字的輸入內容
inputList = input("*** 將加總輸入的數字,但忽略非數字的資料 ****\n\n請輸入多筆資料再按<Enter> => ").split()
i, inputSum = 0, 0
while i < len(inputList):
print("\n輸入值為",inputList[i])
j = 1 if inputList[i][0]=='-' else 0
if inputList[i][j:].isnumeric(): #.isnumeric()判斷字串是否全由數字組成若是回傳True否則回傳False注意負號不視為數字
#isnumeric()的用法可參見 https://www.w3schools.com/python/ref_string_isnumeric.asp
#字串轉數字的他種寫法可用try-except架構(即將教到)
inputSum += eval(inputList[i])
if inputList[i]=="0": i += len(inputList)
i += 1
print("\n您剛剛輸入0囉有效輸入總和 =",inputSum,"Bye ")