Giter VIP home page Giter VIP logo

decorator's Introduction

Python - Decorator練習

練習題目

假設已經存在一個func叫divide(也就是除法)

def divide(n,  d):
       return n  / d

n, d分別代表分子、分母,若我們傳0進去分母,程式會出錯當掉。

請寫一個decorator 來修正這個問題,把它變成傳0進去分母的時候,會return 0,而不是當掉。

解決方式

input傳回來的值為字串,先用intfloat轉為數字

x = int(input('請輸入分子'))
y = int(input('請輸入分母'))

Decorator中新增if、else判斷,分母為時0回傳0

if d == 0 :
    return 0
else:
    return n  / d

function上打上名為@zero的Decorator並print出結果

@zero
def divide(n,  d):
       return int(n  / d)

print(divide(x,y))

執行結果

decorator's People

Contributors

westleft avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.