Python Functions 1

for – range() Function with Length Function

len() function can be used to find the number of items in a list or a tuple data type as well. In the case of the list or tuple data types, len() returns the number of items in the list or tuple.  

You can also use the len() function with the dictionary (dict) data type. In the case of dict data type, the len() function returns the number of key:value pairs in the dictionary. The example program below shows how to do it.

Use len() Function To Find The stop Parameter For range() Function

Now let us get back to the use of the len() function used along with the for-range() function.

You saw in the previous section that you need the start and stop arguments for the range() function.  What if your list is very long and you do not know the number of items in the list?  In such a case, you cannot specify the stop argument in the range() function. 

Let’s consider this example. You are helping the school administrator write a program that has a list of all students in the school. However, you do not know how many students are enrolled in the school.  To write the range (start, stop) statement, you need the second parameter to tell the range() function when to stop looping. In this program, we do not have the value of the stop parameter.

How do you solve this problem?

The problem is solved by using the len() function. The len() function will find the number of items in the list. You can then use this number as the stop parameter in the range() function.

The program below illustrates that in some situations it is necessary to find the length of a string before the range() function can be used.

Below is an example program that uses the len() function to find the number of items in the list. The program then uses this number as the stop parameter in the range() function.

To illustrate the use of the len() function along with the range() function, we write a simple program using a small list consisting of names of the solar system planets.

Let us define a variable named “planets” of the list data type. The list contains the names of all the planets in the solar system.

>>> planets = [‘mercury’,’venus’,’earth’,’mars’,’jupiter’,’saturn’,’uranus’,’neptune’]

Then, we define a variable “number” that represents the number of planets in the list.

The statement

number = len(planets)

returns the number of planets in the list “planets” and assigns this value to the variable “number”.

>>> number = len(planets)

The program then uses the variable “number” as the stop parameter in the range() function. 

This program prints out each of the planets in the list called ‘planets’ and numbers them from 0 to 7.

PROGRAM EXAMPLE: for-range() WITH (len) LENGTH FUNCTION FOR LIST DATA TYPE
>>> planets = ['mercury','venus','earth','mars','jupiter','saturn','uranus','neptune']
>>> number = len(planets)
>>> print(number)
8
>>> for x in range(0,number):
	print(x, planets[x])

	
0 mercury
1 venus
2 earth
3 mars
4 jupiter
5 saturn
6 uranus
7 neptune
>>>

For-range() for List Data Type With Indexing Using %s Placeholder

In an earlier chapter, you saw how you can use %s as a placeholder for embedded variables in string variables. Now you will see how we can use %s formatting for list variables. The following example explains the use of %s and % placeholders in print() statements.

First, we define a list variable as below.

>>> planets = [‘mercury’, ‘venus’, ‘earth’, ‘mars’]

Then, the program finds the length of the list using the len() function. The range() function uses this length as the stop parameter ‘list_length’.

The program below uses both range() function and len() function with indexing.

PROGRAM EXAMPLE: len() FUNCTION WITH for-range() FUNCTIONS USING %s PLACEHOLDER
>>> planets = ['mercury','venus','earth','mars']
>>> list_length = len(planets)  # find the length of the list.
>>> # There are four planets, so the length is 4.
>>> 
>>> # The ‘for’ statement loops index ‘x’ from 0 to 3.
>>> # print statement replaces %s by value of index at 
>>> # each loop and the planet name at that index.
>>> for x in range(0, list_length):
	print('The planet at index %s is %s' %(x, planets[x]))

	
The planet at index 0 is mercury
The planet at index 1 is venus
The planet at index 2 is earth
The planet at index 3 is mars
>>>

In the following section, we will review the input()function in detail.

Input() Function

We introduced the input() function on the Input and Output page. The input function is used for entering data from the keyboard. 

Let’s assume you want to enroll in the school basketball team. You are using the Internet web application program for this purpose.

The program will ask you to enter your name on the web application and wait (pause) until you have entered your name from the keyboard. Then, the program may ask for your address and wait until you have entered your address, and so on.

This type of program uses the Python input() function, which is used to get data directly from the user from the keyboard.

The input() function reads the input from the keyboard, converts it to a string, and stores the keyboard input in a variable.

Python input() function treats all inputs from the keyboard as string (str) data type, even if you enter a number.

The following is the syntax for the input() function:

>>> input([promptString ])

As described earlier, the input() function prints the promptString argument on the monitor screen. The program then waits until the user has entered the requested information on the keyboard, followed by the ENTER key press.

The program below is an example of code that request the user to enter the requested data.

PROGRAM EXAMPLE: input() FUNCTION USE CASES
>>> first = input('Enter your first name:  ')   #1)
Enter your first name:  Alicia                  #2)
>>> last = input('Enter your last name:  ')     #3)
Enter your last name:  Smith                    #4)
>>> print(first + last)                         #5)
Alicia  Smith                                   #6)
>>> print('Hello', first, last)                 #7)
Hello Alicia   Smith                            #8)

Explanation of the Program

The numbers in the explanation correspond to the line numbers in the program.

1) first = input(‘Enter your first name: ‘)

The input() function’s argument ‘Enter your first name: ‘ is the prompt string.

2) The program displays the prompt string ‘Enter your first name: ‘ on the monitor. The program waits for the user to enter the first name followed by the RETURN keypress.

In this program example, the user entered the text “Alicia”, followed by the ENTER key.

3) last = input(‘Enter your last name: ‘)

Line 3) asks the user to enter the last name.

4) The program displays the prompt string ‘Enter your last name: ‘.

The program then waits for the user to type the last name, followed by the ENTER key.

In this example, the user entered the text ‘Smith’.

The program saves the text entered by the user in the variable ‘last’.

5) print(first + last)

The print() function concatenates the values contained in the variables ‘first’ and ‘last’ to print the whole name’.

6). Line 6) is the output of the print() statement. It prints the name ‘Alicia Smith’.

Lines 7) print(‘Hello’, first, last)

Line 8) is the output of the print() statement in line 7). The program prints ‘Hello Alicia Smith’.

In the next chapter, we will introduce the concept of loops The loops are used to execute the same block of code several times. Loops combined with the functions and if-else condition tests make the programs very effective in solving control problems. We will see how such a combination of statements controls the logic of a home thermostat.

Copyright © 2019 – 2021 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights