Example HTML page

A Python program to print the squares and cubes of the numbers in a list.

In this post i am defining a function which create and print a list where the values are square of numbers between a given range.

To create and print a list where the values are Squares of numbers between a given range.

Program

def Values( ):
	L = list( )
	for x in range(1,21):
		L.append(x**2)
	print(L)
Values( )

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

Explanation:

In the above program we defined a function as “Values”. Later we initialize a built-in function of list ‘list( )’ to convert an iterable (if it is tuple,string,set or a dictionary) and is stored in a variable called ‘L’. The range (1,21) prints the squares of the numbers from 1 to 20(since range(1,21) is 20). L.append( ) method appends the resultant square number to ‘L’. When the loop terminates it prints the list of squares of the numbers.

To create and print a list where the values are cubes of numbers between a given range.

def Values( ):
	L = list( )
	for x in range(1,21):
		L.append(x**3)
	print(L)
Values( )

Output

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000]

 

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest