Ibrahim
Ibrahim

Reputation: 11

How to user input while defining function?

I want to calculate area of cuboid. I had tried this function:

def area(l, b, h):
    return l*b*h

But I want prompt to ask user to input values like

lx = float(input("Enter Length"))

How to define this function?

Upvotes: 0

Views: 2597

Answers (1)

user5903421
user5903421

Reputation:

You already have 2/3 of the answer. The first thing you did is called "defining" the function. Now you just need to "call" it with the value the user inputs. I assume you also want the user to define base and height variables.

# Define function
def area(l, b, h):
    return l*b*h

# Take user input
lx = float(input("Enter Length"))
bx = float(input("Enter Base"))
hx = float(input("Enter Height"))

# Call function with user input
a = area(lx, bx, hx)

# Display results to user
print(a)

You could also ask for input inside the function itself, and call the function from within the print statement:

# Define function
def area():
    # Take user input
    lx = float(input("Enter Length"))
    bx = float(input("Enter Base"))
    hx = float(input("Enter Height"))
    return lx*bx*hx

# Call function and display results to user
print(area())

For extra credit, you may want to check that the user input is valid (that they are not entering letters instead of numbers, for example).

Upvotes: 3

Related Questions