Python Functions 1

Python Functions 1 Introduction; Why Do We Need Functions

Python Functions are ready-to-use blocks of code that you can call in your main program. These functions eliminate the task of writing the code that is already embedded in the functions.

The Problem Definition

  1. Generally, there is a need to do the same computation on a different set of data at several different places in the program.  It is tedious to write the same code to do this computation at sevaral places in the program.
  2. In most programs, there is a need for a functionality that is too complex to write yourself. These complex functionalities may consist of hundreds of lines of code. It would be very time-consuming to develop this complex code yourself.

The Solution: Python Functions 1 (A Subset of Python Functions)

What if this complex functionality code is available to you as a ready-to-use block of code that you can call in your main program? That would be neat! This block of code is called a function. Each function has a unique name you specify to use the function in your program.

Python has a large collection of built-in functions that provide programmers with these functionalities. Python Functions 1 discussed on this page help the programmer avoid the tedious task of coding this functionality yourself.

An additional subset of Functions is discussed Python Functions 2 page.

Python Built-in Functions Introductions

Python’s collection of built-in functions is very useful since they eliminate the task of writing the code that is already embedded in these functions. As an example, you may need to print the output of your program in dozens of places in your program. Imagine if you had to write the very complex code that resides inside the built-in print() function. That would be very tedious and very complex code. Python’s built-in functions make your programming task easier and result in a smaller, more modular, and easier to read and understand the program.

User-Defined Functions Introductions

Sometimes, you run into a situation where you would need a functionality very specific to your needs. And if you need this functionality at many places in your program, you may write your own functions that have the functionality that you need.  These are called User Defined Functions discussed in Python Functions 2 Chapter.

Python Functions Introduction

A Function is a block of reusable code that does a particular function (that is, provides a certain functionality). Some examples are:

  • Finding the square root of a number,
  • Calculating factorial of a number.

Functions are ready-to-use code that can be called by their unique name and used in your main programs, wherever you need the functionality that the function provides. 

Python provides a large collection of built-in functions to help programmers speed up their code-writing by eliminating unnecessary typing and code development.  Functions make the programs short, concise, and modular, and structure the code for improved readability.

We have already been using the print() function extensively. The print() function is one example of the many functions available in Python.

A list of Python Built-in Functions is available at the link below:

<a href=”https://docs.python.org/3/library/functions.html#functions“>

Arguments – How Are they Used In Programs

How does a function find the data to do the computations on?

To make a function do its work, parameters are typed and enclosed in parentheses in the function statement. The general syntax of the function statement is:

functionName (parameter1, parameter2, …. )

Let us take the example of the print() function since we are familiar with it. The text within the parenthesis is called an argument. A list of the comma-separated list of arguments that you want to print is passed to the print() function.

Going back to the example on the Printing in Python page, we printed a string variable ‘Rex’ in the example reproduced below.

>>> Rex = "Tyrannosaurs Rex was 40 feet long!!" #1)
>>> print(Rex)                                  #2)
Tyrannosaurs Rex was 40 feet long!!             #3)
>>>

In the above program, the text “Rex” within the parenthesis of the print() statement is the argument. The argument “Rex” is passed to the print function.

Line-by-line Explanation of the Program:

  1. Statement 1) defines a variable “Rex” and assigns it a value “Tyrannosaurs Rex was 40 feet long!!”
  2. Line 2) print(Rex) statement asks the Python interpreter to print the value contained in the argument “Rex”.
  3. Line 3) is the output of the print(Rex) statement.

The statement print(Rex) passes the argument “Rex” to the print() function. The argument “Rex” contains the string “Tyrannosaurs Rex was 40 feet long!!”. The print() function outputs the string stored in the variable “Rex”.

Below Are a Few Python Built-in Functions

As mentioned above, Python has many built-in functions. On this page, we will introduce a few of the built-in functions. These functions are necessary to understand the topics of loops discussed on the “Loops in Python” page.  We will reserve the other functions for a later chapter.

On this Python Functions 1 page, we will discuss only four Python Functions:

  • print()
  • range()
  • len()
  • input()

We use the print() function to display the program’s output.

print() syntax is:

print(expression)

For example, assume that the variables x and y have the following values.

x = 3

y = 5

The following statement

>>>print(“The sum of”, x, “plus”, y, “is”, x+y)

will output the following:

The sum of x plus y is 5.

Here in the expression

“The sum of”, x, “plus”, y, “s”, x+y

x and y are the arguments, whose value is passed to the print() function.

The program below shows how you would use print() function to format the results of a math problem.

PROGRAM EXAMPLE: print() FUNCTION USAGE

>>> a = 8
>>> b = 5
>>> print(‘The sum of’ ,a, ‘+’, b, ‘=’, a+b)
The sum of 8 + 5 = 13
>>>

Print Without Adding A New Line

The print() function inserts a new line at the end by default. So, after finishing printing all the variables in the print() statement, a newline character is appended. By default, Python sets the “end” argument as a newline character. This default newline character ensures that the output of each print statement is on a different line. The default newline character can be suppressed by inserting an argument “end” within the parenthesis of the print() function as below:

print("What is your name?", "end = " ")

In the above example, print() function will print the string “What is your name?” and will not insert a newline character. The “end” argument tells print() function to not put the next string or value on a new line.

It is possible to replace the default newline character with any character of your choice by using the “end” keyword. For example, you can replace the default newline with a space, a comma, or any character of your choice. In the example below, we replace the newline character with a space character.

PROGRAM EXAMPLE: print() FUNCTION WITH “end” ARGUMENT

Program Name: Python_print_end.py

print("Hello!" , end = " ") 
# Suppress newline and replace it by a space.
print("Good Morning") 
# These two print statements will be printed on one line.

The following is the program output.

Program Output:
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
=========== RESTART: C:/Users/username/Python_scripts/Python_print_end.py ==========
Hello! Good Morning
>>>

print() Function: Print A List Without Brackets and Quotes – “sep” Argument

When you print a list data type, Python will print the items in the list with quotes around the items and a bracket around the complete list.  In some cases, you would like Python to print the list without quotes and brackets. Python print() function has an argument “sep”. You can use the sep argument to achieve this. To explain this, let us make a list of your friends that you want to print without quotes and brackets.

>>> friends = ["Robert", "Tracy", "Lynn", "John", "Michael"]
>>> print(friends)
['Robert', 'Tracy', 'Lynn', 'John', 'Michael']
>>> # Now let us print the friends list without quotes and brackets.
>>> print(*friends, sep = ", ")
Robert, Tracy, Lynn, John, Michael
>>>

Python Functions 1 – Range Function

range() is another Python built-in function. It can be used to automatically generate regular arithmetic sequences. The range() function is used to loop through a section of code a specific number of times.

The range() function needs two parameters (actually 3, explained below) specified inside the parenthesis, separated by a comma.

  • The first parameter is the start of the range
  • The second parameter is the stop of the range. 

The resulting sequence starts at the first parameter and ends just before the second parameter. The range() function is normally used with for statement.  (for looping statement is discussed in the next few pages).

How to Use range() Function

The syntax of the range() function is:

for x in range (start, stop, [step]):

Where x is what is called a counting variable (or looping variable).

for and in are reserved words.

Start is the first parameter within the parenthesis and is the start of the range.

Stop is the second parameter within the parenthesis; the range loop stops just before this number.

Step is the third parameter. It is the step for the loop to step through.  For example, if start is 1 and step is 2, then the counting variable x will count through 1, 3, 5, …. and stop just before reaching the stop parameter. The Step parameter is optional.

If the step argument is omitted, it defaults to 1. If the start argument is omitted, it is assumed to be 0.  The start, stop, and end parameters are all integers.

How Does the range() Function Work

Suppose you would like Python to count from 0 to 10.  You will specify two parameters:

1) start =0

2) stop = 11

Note that the last number (11) in the range function is not used. The for loop will exit the loop after finishing count x = 10.

The following describes how the range() function works.

  1. It sets counting variable x = 0
  2. The program jumps to the code just after the colon (:) in the for-range statement and executes the block of code. In the program example below, the code is just one line, that is print(x).
  3. Since x starts at value 0, the program prints 0.
  4. The program then loops back to the top of the program (for-range statement) and increments the looping variable x by 1.  So, x is now 1.
  5. The program executes the code just after the colon and executes the code, which is print(x).  Since x is 1 now, it prints 1.

The program continues to loop until x reaches 10. It prints 10 and exits the loop just before reaching 11.

PROGRAM EXAMPLE: range() FUNCTION TO PRINT MUMBERS 0 THROUGH 10
>>> for x in range (0, 11):
	print(x)

	
0
1
2
3
4
5
6
7
8
9
10
>>>

Detailed Explanation of the Program

In the above program example, the program loops through the print(x) statement using the parameters specified in the range(0, 11) function.

In the first loop, x = 0, the print(x) function prints ‘0’.

In the second loop, the range function changes x = 1. The print(x) function, therefore, prints 1.

The program continues to loop through the print() statement for all values of x specified in the range() function until x reaches 10. It prints from 0 through 10 and then stops just before reaching 11.

Counting With start Parameter Other Than Zero and step Parameter Other Than 1

Suppose you do not want to count from 0.  Instead, you want to count from 53 to 65 skipping every alternate number. You will set the start argument = 53, stop argument = 65, and step argument = 2.  The for loop will count from 53 skipping every alternate number and stopping just before reaching the stop argument of 65 specified in the range function.

PROGRAM EXAMPLE: range() FUNCTION USING STEP PARAMETER
>>> for x in range (53, 65, 2):
	print(x)

	
53
55
57
59
61
63

Note that the for loop exits just before reaching the end count of 65.

Let Us Try Negative Step Value

The step parameter may be positive or negative. If you wish to count down, you can use a negative step value.

For example, the statement range(0, -50, -10) will count from 0 to -50 and skip numbers.

In the statement below

for x in range (0, -50, -10):

The program will count 0, -10, -20, -30, -40

Below is another program to illustrate the use of the range() function.  The program computes the squares, cubes, and the 4th power of integers from 1 through 10.

PROGRAM EXAMPLE: range() FUNCTION TO COMPUTE SQUARES. CUBES, AND 4th POWER
>>> # This program generates squares, cubes, and fourth power of numbers.
>>> # The programn uses range() function to loop from 1 to 10.
>>> for x in range(1,11):
	print('x = %s; x_square = %s; x_cube = %s; x_4th power = %s' %(x, x*x, x*x*x, x*x*x*x))

	
x = 1; x_square = 1; x_cube = 1; x_4th power = 1
x = 2; x_square = 4; x_cube = 8; x_4th power = 16
x = 3; x_square = 9; x_cube = 27; x_4th power = 81
x = 4; x_square = 16; x_cube = 64; x_4th power = 256
x = 5; x_square = 25; x_cube = 125; x_4th power = 625
x = 6; x_square = 36; x_cube = 216; x_4th power = 1296
x = 7; x_square = 49; x_cube = 343; x_4th power = 2401
x = 8; x_square = 64; x_cube = 512; x_4th power = 4096
x = 9; x_square = 81; x_cube = 729; x_4th power = 6561
x = 10; x_square = 100; x_cube = 1000; x_4th power = 10000
>>>

Explanation of the Program

The ‘for’ loop executes the code exactly ten times for ‘x’ from 1 through 10. The program exits before x reaches 11. 

The code executed for each value of “x” is:

print(‘x = %s x^2 = %s x*3 = %s’ %(x, x*x, x*x*x))

We will provide more details of the range() function in the Python Functions 2 chapter.

Length Function len()

Python has a function called the length function len(). The len() function returns the length of a string.

You might wonder about the uses of the length function. Why would one use it?

The paragraph below illustrates a case where the len() function is very useful.

How len() Function Is Used

Suppose you are given the assignment to write a paragraph regarding the Earth’s moon in your Science class. To ensure that your paragraph is long enough, the teacher requires that you count the number of characters in your paragraph and ensure the number of characters is more than 250. 

It is easy to write a paragraph about the moon. But it is sort of tedious to count the characters in the paragraph. The Python len() function will count the characters fairly quickly and easily. 

To get the len() function to count the characters in the paragraph, you will first define a string variable and call it “moon”.

Then you will assign the text in your paragraph to the variable “moon”.

Lastly, you will type the statement len(moon) which will count the number of characters for you.

The program below counts the number of characters in the string “moon”.

PROGRAM EXAMPLE; LENGTH len() FUNCTION USAGE
>>> moon = ('''Our Moon orbits around planet Earth
\nand is Earth's only natural satellite.
\nIt is the fifth-largest satellite in the Solar System.
\nIt takes moon 27 earth-days to complete one orbit around earth.
\nIt is 4.5 billion years old.
\nMoon's distance from earth is 238,000 miles.
\nMoon's radius is 1,079 miles.''')
>>> len(moon)
303
>>> print(moon)
Our Moon orbits around planet Earth

and is Earth's only natural satellite.

It is the fifth-largest satellite in the Solar System.

It takes moon 27 earth-days to complete one orbit around earth.

It is 4.5 billion years old.

Moon's distance from earth is 238,000 miles.

Moon's radius is 1,079 miles.
>>> 

Verified by MonsterInsights