Python Flask Basics Welcome to Flask The Adder

chun chang
chun chang
Pro Student 1,390 Points

Is there a way to accept either one of different types for a argument?

as title

3 Answers

I would simply not specify what data type I wanted in the route. This would therefore give me string values, from there simply use a try except to accept both ints and floats.


@app.route("/add/<num1>/<num2>") # NOTE: This gets the values as strings
def add(num1, num2):
    num1 = getValue(num1) # Get int or float values for both
    num2 = getValue(num2)
    return "{} + {} = {}".format(num1, num2, num1 + num2)

def getValue(string):
        return int(string) # Attempt to return int value of string
    except ValueError: # If getting int value failed, then get float value
        return float(string)


The getValue() function was created to demonstrate the logic separately but it could have been added within

def add(num1, num2): 
It is however cleaner and more importantly, reusable.
chun chang
chun chang
Pro Student 1,390 Points

I wonder if there is any way that we can use to specify num1 can be either int or float in a single route instead of repeat for several routes

Andreas cormack
.a{fill-rule:evenodd;}techdegree seal-36
Andreas cormack
Python Web Development Techdegree Graduate 31,267 Points

do you mean pass different datatypes as arguments?

def add(num1,num2):
    return "{} + {} = {}".format(num1,num2,num1+num2)