Python, with its concise syntax and vast library support, enables developers to create functional and robust programs with minimal code. In this blog post, we’ll explore how to create a simple yet powerful program using only 30 lines of Python 3 code.
Let’s assume we want to create a program that prompts the user to enter a list of numbers, calculates the sum and average of those numbers, and then displays the results. Here’s how we can accomplish this task in 30 lines of Python code:
python# Prompt the user to enter a list of numbers
numbers = input("Enter a list of numbers separated by spaces: ").split()
# Convert the input string to a list of integers
numbers = [int(num) for num in numbers]
# Calculate the sum of the numbers
total_sum = sum(numbers)
# Calculate the average of the numbers
total_count = len(numbers)
if total_count > 0:
average = total_sum / total_count
else:
average = 0
# Display the results
print("Sum:", total_sum)
print("Average:", average)
This program accomplishes the following tasks in 14 lines of code (excluding comments and blank lines):
- It prompts the user to enter a list of numbers separated by spaces.
- It splits the input string into a list of strings.
- It converts each string in the list to an integer using a list comprehension.
- It calculates the sum of the numbers using the
sum()
function.
- It calculates the average of the numbers by dividing the sum by the number of elements in the list.
- It displays the sum and average to the user.
Although this program is simple, it demonstrates the power and efficiency of Python. With just a few lines of code, we were able to create a functional program that handles user input, performs calculations, and displays results.
The key to writing concise and effective Python code is to leverage the language’s built-in functions, libraries, and syntax. By understanding and utilizing these features, you can create powerful programs with minimal effort.
Remember, the number of lines of code isn’t always the most important metric. What’s more important is the functionality, maintainability, and efficiency of your code. However, being able to accomplish complex tasks with a small amount of code is a testament to the power and elegance of Python.