Home > Mobile >  How to print even and odd integers using Numpy arange function
How to print even and odd integers using Numpy arange function

Time:11-08

I am learner , bit stuck not getting how to print odd integers and Even integers using arange function

For Even :

Print Even integers:
arr = np.arange(5,25,2) 

The above piece of line does not print even number

Output :

array([ 5,  7,  9, 11, 13, 15, 17, 19, 21, 23])

For Odd

arr = np.arange(5,25,1) 
arr

Output :

array([ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
       22, 23, 24])

Both of them are printing abnormal output

This traditional code gives me proper result

start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
  
# iterating each number in list
for num in range(start, end   1):
      
    # checking condition
    if num % 2 == 0:
        print(num, end = " ")

How to print even and odd integers using Numpy arange function

CodePudding user response:

You can actually assign them to variables and just use an if statement for your code to check if the user wants to print odd elements or even elements.

start = 5
end = 25   1

# For even
np.arange(start 1, end, 2)

# For odd
np.arange(start, end, 2)

CodePudding user response:

May be this could help you

To print even :

import numpy as np
arr = [i for i in np.arange(5,25) if (i%2) == 0] 
arr

Expected Output :

[6, 8, 10, 12, 14, 16, 18, 20, 22, 24]

To print odd :

import numpy as np
arr = [i for i in np.arange(5,25) if (i%2) != 0] 
arr

Expected Output :

[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]

Code is tested in Google Collab

Note : The Output will be store in List

If you want to the output in array format then store list in below format automatically it will become array

Code :

import numpy as np
arr = [i for i in np.arange(5,25) if (i%2) != 0]
arr_1 = np.array(arr)
arr_1
#type(arr_1)

Expected Output :

array([ 5,  7,  9, 11, 13, 15, 17, 19, 21, 23])

want to check the type of arr_1 just uncomment the type(arr_1) it will give you justification that it's an array : numpy.ndarray

  • Related