5 Best Ways to Convert Height from Centimeters to Feet and Inches in Python

Convert Height from Centimeters to Feet and Inches in Python

πŸ’‘ Problem Formulation: This article addresses the challenge of reading a height value in centimeters and converting it into feet and inches format. For instance, an input of 170 cm should yield an output comprising 5 feet and 6.93 inches. This conversion is essential for applications that require height measurements in non-metric units.

Method 1: Using Floor Division and Modulo Operation

This method employs the floor division and modulo operators to differentiate between feet and inches after converting the total height from centimeters to inches. It is a straightforward and efficient mathematical approach to the conversion problem.

Here’s an example:

height_cm = 170

# Constants for conversion
cm_to_inches = 0.393701
inches_to_feet = 12

# Convert centimeters to inches
height_inches = height_cm * cm_to_inches

# Calculate feet and inches
feet = height_inches // inches_to_feet
inches = height_inches % inches_to_feet

print(f"{height_cm} cm is equal to {int(feet)} feet and {inches:.2f} inches.")

Output: 170 cm is equal to 5 feet and 6.93 inches.

This code snippet first sets up a conversion factor from centimeters to inches. It then uses this factor to convert the given height in centimeters to inches. Afterward, it uses floor division to find the number of feet and the modulo operator to find the remaining inches. This method output rounds the number of inches to two decimal places for precision.

Method 2: Using the divmod() Function

The divmod() function provides an alternative way to perform division and modulus in a single step, returning both the quotient and the remainder. This reduces the number of lines of code and makes it an elegant solution.

Here’s an example:

height_cm = 170

# Convert centimeters to inches and then divmod by inches_to_feet
feet, inches = divmod(height_cm * 0.393701, 12)

print(f"{height_cm} cm is equal to {int(feet)} feet and {inches:.2f} inches.")

Output: 170 cm is equal to 5 feet and 6.93 inches.

In this snippet, we convert height in centimeters to inches and then use the divmod() function to obtain both feet and inches in a single step. This code is concise and avoids the need for explicitly using floor division and the modulo operation.

Method 3: Using a Custom Conversion Function

Encapsulating the conversion logic in a function separates concerns, providing a reusable and testable piece of code. This practice adheres to the DRY (Don’t Repeat Yourself) principle and enhances readability.

Here’s an example:

def cm_to_feet_inches(height_cm):
    inches = height_cm * 0.393701
    feet = inches // 12
    inches %= 12
    return int(feet), inches

height_cm = 170
feet, inches = cm_to_feet_inches(height_cm)
print(f"{height_cm} cm is equal to {feet} feet and {inches:.2f} inches.")

Output: 170 cm is equal to 5 feet and 6.93 inches.

This approach defines a function cm_to_feet_inches() that takes height in centimeters as its argument and returns a tuple of feet and inches after performing the needed conversions and calculations. Such modular code is easier to maintain and understand.

Method 4: Using Object-Oriented Programming

Creating a class for handling conversions encapsulates the functionality and allows for extensibility, such as adding methods for other types of conversions or validations.

Here’s an example:

class HeightConverter:
    cm_to_inches = 0.393701

    def __init__(self, height_cm):
        self.height_cm = height_cm

    def to_feet_inches(self):
        inches = self.height_cm * self.cm_to_inches
        feet = inches // 12
        inches %= 12
        return int(feet), inches

height_cm = 170
converter = HeightConverter(height_cm)
feet, inches = converter.to_feet_inches()
print(f"{height_cm} cm is equal to {feet} feet and {inches:.2f} inches.")

Output: 170 cm is equal to 5 feet and 6.93 inches.

Here, we’ve created a `HeightConverter` class, which is instantiated with the height in centimeters. The method `to_feet_inches` does the conversion. This pattern benefits from the clarity of object-oriented programming and can be extended or modified without affecting other parts of the codebase.

Bonus One-Liner Method 5: List Comprehension with Rounds

List comprehension combined with the round() function can provide a quick one-liner solution for this conversion, especially handy for scripting and data processing tasks.

Here’s an example:

height_cm = 170
feet, inches = [func(height_cm * 0.393701) for func in (lambda x: x // 12, lambda y: round(y % 12, 2))]
print(f"{height_cm} cm is equal to {feet} feet and {inches} inches.")

Output: 170 cm is equal to 5 feet and 6.93 inches.

The one-liner uses list comprehension to apply two anonymous functions (or lambda functions) that perform the feet and inches conversion, respectively. The use of round() for inches ensures correct formatting. This method is compact and elegant, but less readable for beginners.

Summary/Discussion

  • Method 1: Floor Division and Modulo Operation. Straightforward. Requires manual use of two separate operations.
  • Method 2: divmod() Function. Compact. Less intuitive for those unfamiliar with divmod().
  • Method 3: Custom Conversion Function. Highly readable and reusable. Might be overkill for simple scripts.
  • Method 4: Object-Oriented Programming. Encapsulates behavior in a class. Can be too heavy for small projects.
  • Method 5: One-Liner with List Comprehension. Quick and script-friendly. Potentially confusing for those not adept with lambda functions.