Python Exercise: Generate and print a list where the values are square of numbers between two numbers
16. Create and Print a List of Squares for Numbers 1 to 30
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:
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python function that uses list comprehension to generate a list of squares for numbers 1 to 30 and prints the list.
- Write a Python program to implement a loop that calculates the square of each number from 1 to 30 and appends it to a list.
- Write a Python program to use the map() function to compute squares for numbers in a given range and convert the result to a list.
- Write a Python function that returns a list of squares for numbers in a specified range provided as input parameters.
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics