Python language basics 21: functions in Python

Introduction

In the previous post we took a break from going through the Python language features and looked at how to execute a Python source file from the Windows command prompt. We saw how easy it was to execute a file without having to go through any steps before such as code compilation like in Java with the “javac” tool.

In this post we’ll return to Python language constructs and see how functions are built.

Functions and methods

Functions are reusable code blocks that execute the code within the function body.

Consider the following code:

x = 5
y = 10
sum = x + y

x = 3
y = 4
sum = x + y

That’s extremely basic of course but we can see that “x + y” is repeated twice. It’s a good candidate to wrap the addition within a function so that it can be called from different parts of the code.

We’ve already seen some built-in functions like…

randomNumber = randint(int(lowerLimitInput), int(upperLimitInput))

…where randint is the name of the function and the two input values are the function arguments or parameters.

randint constructs a random integer. We say that it returns an integer, a random integer is its return value. We assign the return value from the function to a variable called randomNumber.

A function doesn’t necessarily have a return value or any parameters. A function that has no return value is said to be void.

You might also come across the term “method”. I don’t hear it as often as before but usually functions with no return value are called methods.

Building your own functions

There’s nothing stopping you from building your own functions. You’ll need to use the “def” keyword like here:

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

sum1 = addTwoNumbers(3,4)
sum2 = addTwoNumbers(5, 7)
print(sum1)
print(sum2)

“def” is followed by the name of the function and any arguments within parenthesis. The argument names can be anything, the below code is equivalent:

def addTwoNumbers(firstNumber, secondNumber):
    return firstNumber + secondNumber

The “return” keyword defines that the function will return a value. Any code after that will be ignored:

def addTwoNumbers(firstNumber, secondNumber):
    return firstNumber + secondNumber
    print(firstNumber)

The print function will never be called as the addTwoNumbers exits after the return statement.

Here comes a void method with no return value:

def printMe(whatToPrint):
    print(whatToPrint)

printMe("Hello void method")

Here comes one with no input parameters:

def printRandomNumber():
    randomNumber = randint(0, 10)
    print(randomNumber)

printRandomNumber()

A note on function naming conventions

Rules for naming functions can fill books especially as far as casing is concerned. Every language has some accepted standard. The standard that I followed in the code snippets in this post is called camel case where the first letter is a lower case character and the starting character of each subsequent word within the function name is capitalised. Camel case is common in Java.

Then we have something called Pascal case which is almost the same as camel case but even the first character is capitalised like here:

PrintRandomNumber()
AddTwoNumbers(x, y)

PascalCase is common in C#.

Python follows yet another rule: function names should be lower case. The individual words within the function names are connected with the underscore “_” character:

def add_two_numbers(firstNumber, secondNumber):
    return firstNumber + secondNumber

def print_me(whatToPrint):
    print(whatToPrint)

def print_random_number():
    randomNumber = randint(0, 10)
    print(randomNumber)

We’ll adhere to that convention from now on.

You can find the next part here.

Read all Python-related posts on this blog here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: