1. 程式人生 > >python - 引數檢測isinstance

python - 引數檢測isinstance

引數檢測isinstance:

def add(x, y):
    if isinstance(x, (int, float)) and isinstance(y, (int, float)):
    # x,y只能是int或float
        return x + y
    else:
        print('Error:')

res = add(2.5,2)
print(res)

輸出:

4.5

將輸入引數變為字串型

在這裡插入圖片描述

練習
編寫函式,計算字串匹配的準確率(字母相同的個數佔第一句的多少百分比)
1.只能是字串型
2.第一句不能比第二句短

def Rate(orgin,userInput):
    if not (isinstance(orgin,str) and isinstance(userInput,str)):
        print('The tow parameters must be string')
        return
    	# 返回空
    if len(orgin) < len(userInput):
        print('Sorry.')
        return
    right = 0
    for orgin_char,user_char in zip(orgin,userInput):
        if orgin_char == user_char:
            right += 1
    return right/len(orgin)

a = 'have a nice day'
b = 'Have b aaaa DAy'
print(Rate(a,b))