TNS
VOXPOP
How has the recent turmoil within the OpenAI offices changed your plans to use GPT in a business process or product in 2024?
Increased uncertainty means we are more likely to evaluate alternative AI chatbots and LLMs.
0%
No change in plans, though we will keep an eye on the situation.
0%
With Sam Altman back in charge, we are more likely to go all-in with GPT and LLMs.
0%
What recent turmoil?
0%
ARCHITECTURE
ENGINEERING
OPERATIONS
CHANNELS
THE NEW STACK

# So Much More Python for Beginners: Functions

How to build function in Python.
Jan 13th, 2022 8:48am by

And we’re back with our series on Python goodness for beginners that you might not be able to handle it all. Okay, that’s not exactly true, because you’re ready for the next step in the process.

This time around we’re going to create an application that can actually do something useful. What is this magical application? A calculator. That’s right, a handy little tool that will help you add, subtract, multiply, and divide numbers. After spending a decade or so out of school, you might need such an application.

Ignore your smartphone for a minute. Remember, this is all in the name of education.

Anyway, this little application is a great way to learn about two very important programming features… the function and the `if else` statement.

## What Is a Function?

Simply put, a function is a group of related statements put together to perform a single, specific task. The syntax of a function looks like this:

def FUNCTION(PARAMETERS):
STATEMENTS(S)

Where:

• FUNCTION is the name for the function.
• PARAMETERS are arguments that pass values to the function.
• STATEMENTS are the bits that make up the functioning aspect of the function.

It’s important to understand that all statements must have the same indentation, or the code will error out. So a function with multiple statements might look like this:

def FUNCTION(PARAMETERS):
STATEMENT1
STATEMENT2
STATEMENT3

The indentation can be either tabs or spaces, but you can’t mix the two in a block of code.

## What Is an if else Statement?

If else is a conditional statement that runs one set of statements if an expression is true and another if the expression is false.

Think of it like this:

We’ve set num to 3 so it’s greater than 0, which means it will print out the first statement. However, if we set num to -5, it will print out the second statement.

So we can write out the if else statement like:

if number is greater than or equal to 0 it’s positive, else it’s negative.

Now, let’s use these two cool features for our calculator.

## Create the Function

The first thing we must do is write our functions. Create the new file with:

`nano calculator.py`

We’re going to create four functions, one each for add, subtract, multiply, and divide.

we start each function with def (for define). So our first function will be for addition and looks like this:

So we tell Python we’re defining a function, that function’s name is add, and our variables will be x and y. We end with :, because that tells Python there’s more to come with this function. The final line for the function is:

That tells Python to add x and y together. So our full function looks like this:

That’s it. Now we create the rest of our functions and they look like this:

Next, we’ll use something you’ve already learned, the print() statement. What we’re going to do here is ask the user to make a selection between Add, Subtract, Multiply, or Divide. What the user doesn’t know is they are selecting between the functions we’ve created. This section looks like this:

I’m going to throw a curveball at you with the while loop. What this does is execute a set of statements, so long as a condition is true. Why do we need this? In our case, the user only can only select 1, 2, 3, or 4. What if they type 5? In that event, our program needs to know how to handle it. So if the user types 5 it means the while condition is not met and it will inform them their input is invalid and ask them to make another selection. So our while loop has two statements. The first begins the loop with:

We’re setting the choice variable with input from the user and they can only select from four valid options. If the user enters a valid number, the while loop will allow the program to continue to the next phase. If the user inputs an invalid number, the while loop will jump down to its else statement, which is:

The else statement will then kick it back up to the beginning of the while loop and give the user another chance.

Okay, so our user types a valid number and the while loop allows the program to continue. The next phase uses the `elif` keyword which means if the previous conditions were not true, then try this condition.

What we’re going to do now is ask the user to input numbers to be acted upon. The first thing we must do is pass the user’s first choice (1.Add, 2.Subtract, 3.Multiply, 4.Divide) to the next section of statements. This is done with:

We also are defining variables for num1 and num2 (which the user will type) with `float(input())`. The float function converts a number stored in a string or an integer into a floating-point number (a number with a decimal point). So 2 would convert to 2.0.

Next, we have our if else statement which will take the variable choice and pass it to the statements such that if choice equal 1 it will add the numbers, if choice equals 2 it will subtract the numbers if choice = 3 it will multiply the numbers, and if choice equals 4 it will divide the numbers. That section looks like this:

Notice the double “==”. That actually means equals.

Each statement will print the value for the num1 variable, followed by the operator (+, -, *, /) according to the user selection. It will then print out the proper operator and follow it with the value for the num2 variable. The last piece of each statement then acts upon num1 and num2, according to the user’s selection.

Our final portion of the application asks if the user wants to run another calculation and looks like this:

If the user types yes, the program will start over, otherwise it will end.

So our full Python script looks like this:

Save and close the file. You can then run your calculator with:

`python3 calculator.py`

Enjoy the fresh smell of simple math.

TNS owner Insight Partners is an investor in: Simply.
THE NEW STACK UPDATE A newsletter digest of the week’s most important stories & analyses.