Python, being a highly concise and expressive language, allows us to create powerful programs in a remarkably small number of lines. In this article, we’ll explore the creation of a simple yet practical 100-line Python program. This program will demonstrate several core Python features and concepts within a concise framework.
Program Description
Our program will be a basic command-line tool that performs a few tasks:
- Prompts the user for a list of numbers.
- Calculates the sum, average, minimum, and maximum of the entered numbers.
- Allows the user to save the results to a text file.
Here’s a step-by-step breakdown of the program:
- Getting User Input
We’ll use a while
loop to continuously prompt the user for numbers until they enter “done”. The numbers will be stored in a list.
pythonnumbers = []
while True:
num_input = input("Enter a number (or 'done' to finish): ")
if num_input.lower() == 'done':
break
try:
numbers.append(float(num_input))
except ValueError:
print("Invalid input. Please enter a number.")
- Calculating Sum, Average, Minimum, and Maximum
Next, we’ll calculate the sum, average, minimum, and maximum of the numbers in the list.
pythonif numbers:
total = sum(numbers)
average = total / len(numbers)
min_value = min(numbers)
max_value = max(numbers)
print(f"Sum: {total}")
print(f"Average: {average}")
print(f"Minimum: {min_value}")
print(f"Maximum: {max_value}")
else:
print("No numbers entered.")
- Saving Results to a File
We’ll give the user an option to save the results to a text file. If they choose to do so, we’ll write the results to a file named results.txt
.
pythonsave_to_file = input("Save results to a file? (yes/no): ")
if save_to_file.lower() == 'yes':
with open('results.txt', 'w') as file:
file.write(f"Sum: {total}\n")
file.write(f"Average: {average}\n")
file.write(f"Minimum: {min_value}\n")
file.write(f"Maximum: {max_value}\n")
print("Results saved to results.txt.")
The Complete Program
When you combine the above code snippets, you’ll have a complete 100-line (or less, depending on formatting) Python program that performs the desired tasks.
Why This Program?
This program is a great example of several key Python concepts, including:
- User input and validation
- List manipulation
- Basic arithmetic operations
- File I/O
- Conditional statements
By writing a program like this, you’ll gain practical experience with these concepts while staying within a manageable code size.
Conclusion
In this article, we explored the creation of a simple yet powerful 100-line Python program. This program demonstrates several core Python concepts within a concise framework, allowing you to gain practical experience while staying focused. Remember, the beauty of Python lies in its simplicity and expressiveness, and this program serves as a great example of that.