Comparing Modular and Input Handling in Python (With Code Examples)
Tags: python, programming, beginners
Published: 2024-07-10 14:02:49

I was working on a some problem sets in the [CS50 programming with python course](https://cs50.harvard.edu/python/2022/) and got stuck while trying to understand the expected solution of a problem presented. 

The prerequisite code was provided and the requirement was to add in functions that convert the input string to floating-point numbers representing the dollar amount.

Below are code snippets providing two different approaches to the problem. 

The first snippet shows the section added by instructors. I was supposed to fill in the blanks in the `dollar_to_float` and `percent_to_float` functions.

The second one outlines my way of approaching the problem. It involved modifying the prerequisite code to get the expected results. 

### Code 1 (Original Code with Separate Functions)

```python
def main():
    dollars = dollars_to_float(input("How much was the meal? "))
    percent = percent_to_float(input("What percentage would you like to tip? "))
    tip = dollars * percent
    print(f"Leave ${tip:.2f}")

def dollars_to_float(d):
    return float(d.replace("$", ""))

def percent_to_float(p):
    return float(p.replace("%", "")) / 100

main()
```

### Code 2 (Simplified Code Without Separate Functions)

```python
def main():
    dollars = float(input("How much was the meal? "))
    percent = float(input("What percentage would you like to tip? "))
    tip = dollars * percent / 100
    print(f"Leave ${tip:.2f}")

main()
```
What puzzled me is why the first approach was used, and whether it's a preferred coding practice among developers.

The results were the same, but the way of handling the solution was different based on the following differences:

### Differences

1. **Function Definitions**:
   - **Code 1**: Defines two separate functions, `dollars_to_float` and `percent_to_float`, to handle specific conversions.
   - **Code 2**: Performs the conversions directly within the `main` function without using separate functions.

2. **Input Handling**:
   - **Code 1**: Assumes the input may include currency (`$`) and percentage (`%`) symbols and handles their removal within the separate functions.
   - **Code 2**: Assumes the input is a plain number without any symbols, directly converting the input string to a float.

3. **Tip Calculation**:
   - **Code 1**: Multiplies the `dollars` by `percent`, where `percent` is already converted to a decimal.
   - **Code 2**: Multiplies `dollars` by `percent` and then divides by 100 to convert the percentage to a decimal inline.

### Pros & Cons: Which Method is Better and More Commonly Used?

#### Pros of Code 1:
1. **Modularity**: Breaking the conversion logic into separate functions (`dollars_to_float` and `percent_to_float`) makes the code more modular. Each function has a single responsibility, making it easier to test and maintain.

2. **Reusability**: The separate functions can be reused in other parts of the program if needed.

3. **Clarity**: The intent of the conversion is clearer. Each function name describes what it does, which can make the code easier to read and understand.

#### Pros of Code 2:
1. **Simplicity**: The code is simpler and shorter since it doesn't define extra functions. Everything is done inline within the `main` function.

2. **Directness**: The input and conversion logic are handled directly, which can be easier to follow for small scripts.

#### Common Practice:
- **Modularity and Clarity**: In larger projects or where input handling is complex, **Code 1**'s approach is preferred. It makes the codebase easier to manage and understand. Writing modular code with single-responsibility functions is a common best practice in programming.

- **Simplicity and Conciseness**: For small scripts or when the input is straightforward (e.g., guaranteed to be plain numbers), **Code 2**'s approach is often sufficient and commonly used due to its simplicity.

### Conclusion:
I did a little research and learned that for small and straightforward scripts, handling input and conversions directly within the main function is common due to its simplicity and conciseness (code 2). 
However, in larger or more complex applications, breaking the logic into separate functions enhances modularity, reusability, and clarity, making the codebase easier to manage and understand (code 1).