python習題庫57-65

習題57、 用戶輸入不同的數據,當輸入的數據達到3個數字的時候,求和結束程序。(數字可以是整數)

提示:判斷是否整數的方法,isdigit()
遍歷所有的輸入數據,判斷是否在0-9的字符串範圍內
方法1:

#coding=utf-8
result=0
count=0
while True:
    s=input("please input the number:")
    for v in s:
        if v not in "0123456789":#如果不是數字跳出當前循環
            break
    else:
        count+=1
        result +=int(s)
    if count==3:
        break
print(result)

在這裏插入圖片描述
方法2:**利用isdigit()函數
知識點:isdigit() 函數的作用:檢測字符串是否只由數字組成。

result=0
count=0
while  True:
    s=input("please input the number:")
    if s.isdigit():
        count+=1
        result+=int(s)
    if count==3:
        break
print(result)

在這裏插入圖片描述

習題58:用嵌套列表的方式,遍歷輸出一個矩陣

方法1:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章