Study Guide

6.3.8 Area of a Square with Default Parameters CodeHS Answers

6.3.8 Area of a Square with Default Parameters CodeHS Answers

The most common answer is:

def calculate_area(side_length=10):
    area = side_length * side_length
    print(f"The area of a square with sides of length {side_length} is {area}.")

side_length = int(input("Enter side length: "))

if side_length > 0:
    calculate_area(side_length)
else:
    calculate_area()

This version of the program:

  • Defines a function calculate_area with a default parameter side_length=10, which calculates the area of a square and prints a formatted message.
  • Asks the user to input a side length, converting the input into an integer.
  • Checks if the inputted side length is greater than 0; if so, it calls calculate_area with the user-provided side length. If not (or if the input is invalid), it calls calculate_area without arguments, using the default side length of 10.