First NumPy Program
Write your first NumPy program, create numerical arrays, perform calculations, and understand how Python displays the results of array operations.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Import NumPy into a Python program.
- Create a NumPy array using
np.array(). - Display array values using
print(). - Perform basic arithmetic on numerical arrays.
- Calculate totals and averages using NumPy functions.
- Understand common errors in beginner NumPy programs.
- Write and execute a complete NumPy practice program.
2. Preparing Your First Program
Before writing your first NumPy program, confirm that NumPy
is installed in the Python environment selected by your IDE.
Create a Python file named main.py in your project.
Step 1: Import NumPy
import numpy as np
This statement imports the NumPy library and assigns it
the commonly used alias np.
Step 2: Create an Array
numbers = np.array([10, 20, 30, 40, 50])
The np.array() function converts the supplied
sequence of values into a NumPy array.
Step 3: Display the Array
print(numbers)
Output:
[10 20 30 40 50]
3. Understanding the Program Structure
| Statement | Purpose |
|---|---|
import numpy as np |
Makes NumPy available through the alias np. |
np.array([...]) |
Creates an array from the supplied values. |
np.sum(array) |
Calculates the sum of the array elements. |
np.mean(array) |
Calculates the arithmetic mean of the array elements. |
print() |
Displays values in the program output. |
4. Program Example: Student Marks Analysis
At CIIT TRANING INSTITUTE, Samadhan wants to calculate the total and average marks of five students. NumPy can perform these calculations directly on an array.
Complete Program
import numpy as np
marks = np.array([78, 85, 92, 67, 88])
total_marks = np.sum(marks)
average_marks = np.mean(marks)
highest_marks = np.max(marks)
lowest_marks = np.min(marks)
print("Student Marks:", marks)
print("Total Marks:", total_marks)
print("Average Marks:", average_marks)
print("Highest Marks:", highest_marks)
print("Lowest Marks:", lowest_marks)
Output:
Student Marks: [78 85 92 67 88] Total Marks: 410 Average Marks: 82.0 Highest Marks: 92 Lowest Marks: 67
Step-by-Step Explanation
marksstores the five marks in a NumPy array.np.sum(marks)adds all the marks.np.mean(marks)calculates the average.np.max(marks)returns the highest value.np.min(marks)returns the lowest value.- The
print()statements display the calculated results.
5. Performing Arithmetic Operations
NumPy supports element-wise arithmetic. When an arithmetic operation is applied to an array and a scalar, the operation is applied to every element.
Example: Basic Calculations
import numpy as np
numbers = np.array([10, 20, 30])
print("Original:", numbers)
print("Addition:", numbers + 5)
print("Subtraction:", numbers - 5)
print("Multiplication:", numbers * 2)
print("Division:", numbers / 10)
Output:
Original: [10 20 30] Addition: [15 25 35] Subtraction: [ 5 15 25] Multiplication: [20 40 60] Division: [1. 2. 3.]
| Operator | Operation | Example Result |
|---|---|---|
+ |
Adds a value to each element. | [15, 25, 35] |
- |
Subtracts a value from each element. | [5, 15, 25] |
* |
Multiplies each element by a value. | [20, 40, 60] |
/ |
Divides each element by a value. | [1.0, 2.0, 3.0] |
6. Program Example: Sales Calculation
Samiksha is analyzing daily sales at a practice store. She wants to calculate total sales, average sales, and the highest daily sales value.
Complete Program
import numpy as np
sales = np.array([1200, 1500, 1800, 1350, 2150])
total_sales = np.sum(sales)
average_sales = np.mean(sales)
highest_sales = np.max(sales)
print("Daily Sales:", sales)
print("Total Sales:", total_sales)
print("Average Sales:", average_sales)
print("Highest Sales:", highest_sales)
Output:
Daily Sales: [1200 1500 1800 1350 2150] Total Sales: 8000 Average Sales: 1600.0 Highest Sales: 2150
This program illustrates how one array can represent a set of daily sales values and how NumPy functions can summarize those values.
7. Understanding Array Attributes
NumPy arrays provide attributes that describe their structure. These attributes are useful when inspecting data before performing more complex operations.
import numpy as np
numbers = np.array([10, 20, 30, 40])
print("Array:", numbers)
print("Number of dimensions:", numbers.ndim)
print("Shape:", numbers.shape)
print("Number of elements:", numbers.size)
print("Data type:", numbers.dtype)
Example output:
Array: [10 20 30 40] Number of dimensions: 1 Shape: (4,) Number of elements: 4 Data type: int64
The exact integer data type can vary by platform and how the array is created. Read the value displayed by your own program rather than assuming a particular type.
| Attribute | Meaning |
|---|---|
ndim |
Number of dimensions in the array. |
shape |
Length along each dimension. |
size |
Total number of elements. |
dtype |
Data type used to represent array elements. |
8. Common Beginner Mistakes
Mistake 1: Forgetting to Import NumPy
Calling np.array() before importing NumPy
causes a name-related error.
Mistake 2: Misspelling a Function
NumPy function names must be spelled correctly.
For example, use np.mean() to calculate
an average.
Mistake 3: Using an Incorrect Variable Name
Python variable names are case-sensitive.
marks and Marks are different names.
Mistake 4: Running the Wrong Interpreter
If the IDE selects an environment without NumPy, the import statement may fail. Check the active interpreter and package installation.
Mistake 5: Miscalculating Expected Results
Always verify that the expected output matches the supplied input values. A correct program cannot produce a total that does not match the sum of its elements.
9. Classroom Practical Activity
Activity: Analyze Student Performance
Samadhan, Pradnya, and Samiksha are learning how to analyze numerical data. Complete the following activity using a NumPy array.
- Create an array containing the marks 76, 89, 94, 68, and 83.
- Display the complete array.
- Calculate the total marks.
- Calculate the average marks.
- Find the highest and lowest marks.
- Add five bonus marks to each array element.
- Display the updated array.
Starter Program
import numpy as np
marks = np.array([76, 89, 94, 68, 83])
print("Original Marks:", marks)
print("Total:", np.sum(marks))
print("Average:", np.mean(marks))
print("Highest:", np.max(marks))
print("Lowest:", np.min(marks))
updated_marks = marks + 5
print("Updated Marks:", updated_marks)
Run the program and compare the output with your own calculations. In a real assessment, apply any bonus marks according to the instructor's stated rules.
Practice Questions
- Which statement imports NumPy using the alias
np? - What does
np.array()do? - Which function calculates the sum of an array?
- Which function calculates the average of an array?
- How can you multiply every array element by two?
- What information does the
shapeattribute provide? - Why should you verify the selected Python interpreter?
Summary
In this lesson, you wrote your first NumPy program, imported the library, created numerical arrays, and displayed their contents.
You also practiced arithmetic operations, calculated totals and averages, inspected array attributes, and explored student marks and sales analysis examples.