Modularity Why it is important
In this project on a basic calculator in Python, you will learn how to break things down into functions and why you should do that.
Functions give you the power to implement things in smaller blocks of code, which you can test individually.
The main reason to use Python functions is Modularity.
Modularity Functions help to break down complex programs into smaller, more manageable pieces. This makes the code easier to read, understand, and maintain.
Modular programming is an important skill to master because it helps programmers to break down complex problems into smaller, more manageable pieces. By breaking down a program into smaller functions, it becomes easier to understand, test, and modify.
Modular programming promotes code reuse, which means that functions can be written once and used in multiple places throughout a program, or even in different programs altogether. This reduces the amount of code that needs to be written and maintained and also helps to ensure consistency across different parts of a program.
In addition, modular programming makes it easier to collaborate with other programmers. By breaking down a program into smaller functions, different programmers can work on different parts of the program without interfering with each other’s work. This can make it easier to develop large, complex programs in a team environment.
Finally, modular programming can help to improve the overall quality of a program. By breaking a program into smaller functions, it becomes easier to test each function individually, which can help to identify bugs and other issues more quickly. This can help to ensure that a program is reliable, efficient, and easy to maintain.
In summary, mastering modular programming is an important skill for any programmer to have. It helps to promote code reuse, collaboration, and program quality and can make it easier to develop large, complex programs in a team environment.
In this project, you will create a simple calculator.
The calculator will take input from the user and create the calculation.
It will only accept positive integer input with one operator.
Examples of valid input.
Examples of invalid input.
Step 1 Design Choices
When a developer gets a task, often there are things not specified.
- What happens if the user inputs data in the wrong format (invalid input)?
- How should it output the result data?
What to do?
- Sometimes you can clarify these issues with the user.
- Other times you can make choices based on your knowledge or best guesses.
When to do what?
- Who is the user or owner of the code you develop?
- How big an impact does the decision have?
Step 2 Breaking it down
A great way to break projects down is to divide them into the normal flow you would think of it.
- Input from the user and validation of input
- Calculate the result
- Output the result
Then each of the above 3 steps can be divided further down to make the code more simple.
Step 3 Input from the user
The first thing to realize is that the validation is difficult to implement and needs proper testing to make sure it is done correctly.
One thing you can do before that is to make sure the input functionality works independently of the validation.
def is_input_format_correct(input_str): return False # Input from user and validation of input def input_calculation(): """ Prompts the user for a calculation. Repeat until input from user is on format [num][op][num] Return the input from user. """ while True: input_str = input('Input calculation: ') if is_input_format_correct(input_str): return input_str print('Expected format: [number][operator][number]')
We first have the validation function, which returns False by default. This function will be implemented afterward. This enables you to test whether the input calculation function works as expected.
The input_calculation() uses an infinite while-loop and breaks out of it by using the return statement from a function.
Step 4 Breaking the validation down
is_input_format_correct(input_str) needs to validate 3 things.
input_stronly contains the following characters
input_stronly contains one operator (one of the following
input_stris on format
A great way to do that is to make 3 functions for that. This way you can test if they do what you expect.
We keep the functions simple and do not use any advanced Python. But it uses for-loops and conditional statements.
def valid_chars(input_str): """ Returns True if input_str only contains chars from '0123456789+-*/' """ for c in input_str: if c not in '0123456789+-*/': return False return True assert valid_chars('123+456') assert valid_chars('123-123') assert valid_chars('123*123') assert valid_chars('123/123') assert valid_chars('0123456789+-*/') assert valid_chars('123b123') == False
If you are unfamiliar with assert it evaluates the expression followed and raises an exception if it evaluates to anything else than True.
That is a great way to test if your function works as expected.
def one_operator(input_str): """ Given input_str only contains chars '0123456789+-*/' Return True if input_str only has one operator (+, -, *, or /) """ no_add = input_str.count('+') no_minus = input_str.count('-') no_mult = input_str.count('*') no_div = input_str.count('/') no_operators = no_add + no_minus + no_mult + no_div if no_operators == 1: return True else: return False assert one_operator('123+123') assert one_operator('123-123') assert one_operator('123*123') assert one_operator('123/123') assert one_operator('123123/') assert one_operator('123++123') == False assert one_operator('123+/123') == False assert one_operator('123+*123') == False assert one_operator('123--123') == False
The power of writing a doc string here, is, that you can give assumptions to the user. The function uses the string method count. This function will only work correctly if the input is of a certain format (a format passing the previously defined function).
Now that is powerful.
def correct_format(input_str): """ Given input_str only contains chars '0123456789+-*/' and input_str only has one operator (+, -, *, or /) Return True if input_str is on the format [num][op][num] """ if input_str in '+-*/': return False if input_str[-1] in '+-*/': return False return True assert correct_format('0+0') assert correct_format('1+1') assert correct_format('2+2') assert correct_format('3+3') assert correct_format('4+4') assert correct_format('5+5') assert correct_format('6+6') assert correct_format('7+7') assert correct_format('8+8') assert correct_format('9+9') assert correct_format('99+') == False assert correct_format('+99') == False assert correct_format('99-') == False assert correct_format('-99') == False assert correct_format('99*') == False assert correct_format('*99') == False assert correct_format('99/') == False assert correct_format('/99') == False
I think I “over”-asserted the above function.
Anyhow. We have now higher confidence that all 3 functions work as expected.
Now we can combine them.
def is_input_format_correct(input_str): """ Return True if input_str is on the format [num][op][num] """ if not valid_chars(input_str): return False if not one_operator(input_str): return False if not correct_format(input_str): return False return True assert is_input_format_correct('123+123') assert is_input_format_correct('123b123') == False assert is_input_format_correct('123++123') == False assert is_input_format_correct('123123+') == False
Now we have implemented the validation and we can use it together with the input_calculation().
Step 5 Calculate the result
Now the power of having the validation of the format before this step, is, that you now can assume the input to this function is of the correct format.
def convert_to_ints(numbers_str): """ Input is a list of numbers as str. Returns a list of the numbers as int. """ numbers =  for number_str in numbers_str: numbers.append(int(number_str)) return numbers assert convert_to_ints(['123', '123']) == [123, 123] def calculate_result(calc): """ If calc is on format [num][op][num] Returns the result of the calculation calc. """ if '+' in calc: numbers_str = calc.split('+') numbers = convert_to_ints(numbers_str) return numbers + numbers if '-' in calc: numbers_str = calc.split('-') numbers = convert_to_ints(numbers_str) return numbers - numbers if '*' in calc: numbers_str = calc.split('*') numbers = convert_to_ints(numbers_str) return numbers*numbers if '/' in calc: numbers_str = calc.split('/') numbers = convert_to_ints(numbers_str) return numbers/numbers assert calculate_result('123+1') == 124 assert calculate_result('123-1') == 122 assert calculate_result('123*1') == 123 assert calculate_result('1/2') == 0.5
The function only expects and should only calculate correctly if the calculation string is in the correct format.
Also, we created a simple helper function. I know it can be done simply with list comprehension (more here), but we are making the code easy to understand and easy for everybody to enjoy.
Step 6 Display the result
The last piece is pretty straightforward.
def display_result(calc, result): print('The calculation of', calc) print('is', result)
Feel free to make it nicer than I have the capability to do.
The power of breaking it down as we did, is, that it makes it easy to improve or change each piece isolated.
Step 7 Combining it all
Now, we need to combine it all.
# Combine it all calc = input_calculation() result = calculate_result(calc) display_result(calc, result)
I hope you see the power of that.
3 lines of code and you have it all there. If you know something is wrong with the way you calculate it, you know where to look.
Also, if you want to make a more advanced calculator you know how to proceed now.
Want more Python projects?
This is part of 19 Python Projects and you can create this awesome interactive board game and learn the importance of program design.
Python for Finance: Unlock Financial Freedom and Build Your Dream Life
Discover the key to financial freedom and secure your dream life with Python for Finance!
Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.
Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.
Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.
Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!
Python for Finance a 21 hours course that teaches investing with Python.
Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.
“Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.