Python Tutorial #7 - Calculator

in #programming7 years ago

Welcome back to the Python Tutorial! Today we're gonna write our own little calculator to test our skills.
At first, we need to think of what our calculator should do. In this Tutorial, the main functions should be add, subtract, multiply and divide.
Now we need to define those as functions. For the experienced Python Programmers among you: I know it can be done easier, but in this Tutorial I will use functions for the sake employing the things we've learned.

def add(value1, value2):
    result = value1 + value2
    return result

def subtract(value1, value2):
    result = value1 - value2
    return result

def multiply(value1, value2):
    result = value1 * value2
    return result

def divide(value1, value2):
    result = value1 / value2
    return result



After that, we need to program the "Interface" which asks our user for the operation and the values the program should handle.

while True:
    print("Hello! Type add, subtract, multiply or divide. Type exit to exit.")
    choice = input("Your choice: ")

    if choice == "exit":
        break

    input1 = input("First Value: ")
    input2 = input("Second Value: ")



At this point, the program asks about your values and stores them in variables.

The input() statement in used to get user input. In the brackets you can define the prompt which is some text shown at the start of the line in which the user will type.

The break() statement cancels a loop. It is the only way to end infinite loops.

In the next step, we need to check whether the user really entered numbers as input values. If he didn't, the program would crash.

if not input1.isdigit():
        print("Please enter a valid value.")
        continue

if not input2.isdigit():
        print("Please enter a valid value.")
        continue



Here we call the isdigit() function on our string to ensure that there are no characters in it. We will talk about that special type of functions soon.

If a function only returns True or False, we can write if function() or if not function() instead of if function() == True or if function() == False.

The continue statement is related to the break statement, but it only cancels the current walkthrough of the loop, jumping effectively to it's beginning.

Now, we need to program the part that handles the inputs and relates them to the functions.

if choice == "add":
        res = add(int(input1), int(input2))
        print(res)

elif choice == "subtract":
        res = subtract(int(input1), int(input2))
        print(res)

elif choice == "multiply":
        res = multiply(int(input1), int(input2))
        print(res)

elif choice == "divide":
        if int(input2) == 0:
            print("Do not divide through Zero!")
            continue
        res = divide(float(input1), float(input2))
        print(res)

else:
        print("Invalid Choice.")



You might ask yourself now why we need to do things like int(input1). This is because of the input() returning our input as a string (Sequence of characters). Sadly, our operators can only handle integers (numbers).
So we need to convert our string to an integer, which is done with the int() function. In the division function, we need to use a float, which is a number with an inifinite amount of commas behind it (we will look at how that works soon).
The conversion to float is done with the float() function.
We also need to check wether the second number is zero, since you dividing through zero is forbidden and would raise an error.

If we put all those parts together, we get our program:

def add(value1, value2):
    result = value1 + value2
    return result

def subtract(value1, value2):
    result = value1 - value2
    return result

def multiply(value1, value2):
    result = value1 * value2
    return result

def divide(value1, value2):
    result = value1 / value2
    return result


while True:
    print("Hello! Type add, subtract, multiply or divide. Type exit to exit.")
    choice = input("Your choice: ")

    if choice == "exit":
        break

    input1 = input("First Value: ")
    input2 = input("Second Value: ")

    if not input1.isdigit():
        print("Please enter a valid value.")
        continue

    if not input2.isdigit():
        print("Please enter a valid value.")
        continue

    if choice == "add":
        res = add(int(input1), int(input2))
        print(res)

    elif choice == "subtract":
        res = subtract(int(input1), int(input2))
        print(res)

    elif choice == "multiply":
        res = multiply(int(input1), int(input2))
        print(res)

    elif choice == "divide":
        if int(input2) == 0:
            print("Do not divide through Zero!")
            continue
        res = divide(float(input1), float(input2))
        print(res)

    else:
        print("Invalid Choice.")



Pretty complicated for such a "little" program, isn't it? Well, you need to think about a lot of things if you're programming.
With that said, we've finished for today. Soon, we will look at the more advanced features of Python. If you have any Questions, write them in the commentaries! If you liked this part of the tutorial, you can do three things to support me: Upvote, Follow, Resteem. Have a nice day!

Coin Marketplace

STEEM 0.25
TRX 0.19
JST 0.036
BTC 91660.56
ETH 3295.97
USDT 1.00
SBD 3.83