Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Flask Basics Welcome to Flask The Adder

chun chang
PLUS
chun chang
Courses Plus 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.

Example:

@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):
    try:
        return int(string) # Attempt to return int value of string
    except ValueError: # If getting int value failed, then get float value
        return float(string)

Note:

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
PLUS
chun chang
Courses Plus 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

do you mean pass different datatypes as arguments?

python
@app.route('/add/<int:num1>/<int:num2>')
@app.route('/add/<int:num1>/<float:num2>')
@app.route('/add/<float:num1>/<int:num2>')
@app.route('/add/<float:num1>/<float:num2>')
def add(num1,num2):
    return "{} + {} = {}".format(num1,num2,num1+num2)