w3resource

Python Exercise: Generate and print a list where the values are square of numbers between two numbers

Python Functions: Exercise - 16 with Solution

Write a Python function to create and print a list where the values are the squares of numbers between 1 and 30 (both included).

Sample Solution:

Python Code:

# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
def printValues():
    # Create an empty list 'l'
    l = list()
    
    # Iterate through numbers from 1 to 20 (inclusive)
    for i in range(1, 21):
        # Calculate the square of 'i' and append it to the list 'l'
        l.append(i**2)
    
    # Print the list containing squares of numbers from 1 to 20
    print(l)

# Call the 'printValues' function to generate and print the list of squares
printValues() 

Sample Output:

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

Explanation:

In the exercise above the code defines a function named "printValues()" that generates a list of squares of numbers from 1 to 20. It iterates through a range of numbers from 1 to 20, calculates the square of each number, and appends it to an initially empty list l. Finally, it prints the list containing squares of numbers from 1 to 20 by calling the "printValues()" function.

Pictorial presentation:

Python exercises: Generate and print a list where the values are square of numbers between two numbers.

Flowchart:

Flowchart: Python exercises: Generate and print a list where the values are square of numbers between two numbers.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.
Next: Write a Python program to make a chain of function decorators (bold, italic, underline etc.).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/python-functions-exercise-16.php