# Python Programming – Basic Operations

In this Page, We are Providing Python Programming – Basic Operations. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

## Python Programming – Basic Operations

Basic Operations

Arithmetic operations when applied on NumPy arrays, they are implemented element-wise.

>>> a=np . array ( [ 20 , 30 , 40 , 50 ] )
>>> b=np . arange ( 4 )
>>> c=a - b
>>> c
array ( [ 20 , 29 , 38 , 47 ] )
>>> b**2
array ( [ 0 , 1 , 4 , 9 ] )
>>> a<39
array ( [ True , True , False , False ] , dtype=bool )

The product operator * operates element-wise in NumPy arrays. The matrix product can be performed using the dot ( ) function or creating matrix objects (refer section 7.8).

>>> a=np . array ( [ [ 1 , 1 ] ,
. . . [ 0 , 1 ] ] )
>>> b=np . array ( [ [ 2 , 0 ] ,
. . . [ 3 , 4 ] ] )
>>> a*b
array ( [ [ 2 , 0 ] ,
[ 0 , 4 ] ] )
>>> np . dot ( a , b )
array ( [ [ 5 , 4 ] ,
[ 3 , 4 ] ] )

Some operations, such as +=, *=, etc., modifies an existing array, rather than creating a new array.

>>> a=np . array ( [ [ 1 , 2 ] ,                        # a is integer type
. . . [ 3 , 4 ] ] )
>>> b=np . array ( [ [ 1 . , 2 . ] ,                   # b is float type
. . . [ 3 . , 4 . ] ] )
>>> a*=2
>>> a
array ( [ [ 2 , 4 ] ,
[ 6 , 8 ] ] )
>>> b+=a
>>> b
array ( [ [ 3 . , 6 . ] ,
[ 9 . , 12 . ] ] )
>>> a+=b                                                  # b is converted to integer type
>>> a
array ( [ [ 5 , 10 ] ,
[ 15 , 20 ] ] )

When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as “upcasting”).

>>> a=np . array ( [ 1 . 1 , 2 . 2 , 3 . 3 ] )
>>> a . dtype . name
' float64 '
>>> b=np . array ( [ 4 , 5 , 6 ] )
>>> b . dtype . name ' int32 '
>>> c=a+b
>>> c
array 0( [ 5 . 1 , 7 . 2 , 9 . 3 ] )
>>> c . dtype . name ' float64 '

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class .

>>> a=np . array ( [ [5 , 8 ] ,
. . . [ 3 , 6 ] ] )
>>> a . sum ( )
22
>>> a . min ( )
3
>>> a . max ( )
8

By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

>>> a=np . arange ( 12 ) . reshape ( 3 , 4 )
>>> a
array ( [ [ 0 , 1 , 2 , 3 ] ,
[ 4 , 5 , 6 , 7 ] ,
[ 8 , 9 , 10 , 11 ] ] )
>>> a.sum(axis=0)                                             # Sum of each column
array ( [12, 15, 18, 21] )
>>> a.min(axis=1)                                             # Minimum of each now
array ( [ 0 , 4 , 8 ] )
>>> a . cumsum ( axis=1 )                                  # Cumulative sum along each now
array ( [ [ 0 , 1 , 3 , 6 ] ,
[ 4 , 9 , 15 , 22 ] ,
[ 8 , 17 , 27 , 38 ] ] )