Functions are a way of compartmentalizing code such that it makes it both easier to read and easier to manage. In this case, there are a few concepts you must understand before implementing functions to solve your problem.
Functions follow the format:
def functionName(): #this defines the function
print("This is inside the function.") #this is code inside the function
functionName() #this calls the function
A few things to note:
- code that belongs to the function is indented
- in order for the function to execute, it first has to be invoked (i.e. called)
So your function aims to calculate the area of a rectangle using width and height variables. In order for your function to work you would first need to invoke the function itself and then remove the unneeded parameters as you are asking for them as input anyway. This would give you:
def area_rectangle():
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print (area)
area_rectangle()
Another way to go about this would be to make use of parameters. Parameters are values passed to a function by the line of code that invokes them, and they are given within the parentheses:
def functionName (my_param):
print (my_param)
fucntionName (my_param)
Using parameters to solve your problem would look something like this:
def area_rectangle(width, height):
area=width*height
print (area)
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area_rectangle(width, height)
Another side note is on return values. Rather than printing the result of a function within the function itself, you can return it to the line that invoked it and then make use of it outside the function:
def area_rectangle(width, height):
area=width*height
return area
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area = area_rectangle(width, height)
print ("The area is {}".format(area))
Functions are an essential part of Python, and I suggest reading some tutorials on them, as there is many more things you can do with them. Some good ones...
learnpython.org - Functions
tutorialspoint.com - Python Functions
passinside the function or indent your code to be inside of the function.widthand aheightparameter in that function.