VOOZH about

URL: https://thenewstack.io/so-much-more-python-for-beginners-functions/

⇱ So Much More Python for Beginners: Functions - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.

What’s next?

Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.

Follow TNS on your favorite social media networks.

Become a TNS follower on LinkedIn.

Check out the latest featured and trending stories while you wait for your first TNS newsletter.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2022-01-13 08:48:40
So Much More Python for Beginners: Functions
tutorial,
Data / Python / Software Development

So Much More Python for Beginners: Functions

This tutorial for programmers teaches you how to build functions in Python.
Jan 13th, 2022 8:48am by Jack Wallen
👁 Featued image for: So Much More Python for Beginners: Functions

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:

num = 3

if (num >= 0):
     print("The number is zero or positive")
else:
     print("The number is negative")

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:

def add(x, y):

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:

return x + y

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

def add(x, y):
      return x + y

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

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y

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:

print("Select A Type of Calculation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

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:

while True:
    choice = input("Make your choice(1/2/3/4): ")

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:

else:
print("Invalid Input")

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:

if choice in ('1', '2', '3', '4'):
     num1 = float(input("Enter first number: "))
     num2 = float(input("Enter second number: "))

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:

if choice == '1':
     print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':
     print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':
     print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':
     print(num1, "/", num2, "=", divide(num1, num2))

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:

# check if user wants another calculation
# break the while loop if the answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break

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

So our full Python script looks like this:

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x / y

print("Select A Type of Calculation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:

    # Accept input from user
    choice = input("Make your choice(1/2/3/4): ")

    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))

        # check if user wants another calculation
        # break the while loop if the answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
          break

    else:
        print("Invalid Input")

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

python3 calculator.py

Enjoy the fresh smell of simple math.

TRENDING STORIES
Jack Wallen is what happens when a Gen Xer mind-melds with present-day snark. Jack is a seeker of truth and a writer of words with a quantum mechanical pencil and a disjointed beat of sound and soul. Although he resides...
Read more from Jack Wallen
SHARE THIS STORY
TRENDING STORIES
TNS owner Insight Partners is an investor in: Simply, Statement.
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.