-1

How to write a code in Python which can print from 0.0 to 4.0, excluding 1.0 and 2.0, incrementing by 0.1?

Kichu
  • 1
  • 2

3 Answers3

1

You could try:

 def print_hi():
        for i in range(0, 41, 1):
            if i == 10 or i == 20:
                continue
            print(i / 10.0)

Because Python's range() can only do integers, so we did a trick.

navylover
  • 12,383
  • 5
  • 28
  • 41
0

If you don't mind using libraries like numpy, one way would be to first create the array you want using np.arange(start, stop, interval) and then use np.where(condition) to select the values.

Here's an example:

import numpy as np
x = np.arange(0, 4, 0.1)

array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9])

x = x[np.where((x!=1) & (x!=2))]

array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9])

np.where() returns an array of indexes. These indexes are then used to select only required elements from x. Note the use of & instead of and. Read more about the difference here.

Bread
  • 3
  • 8
  • If you use this method, note that its vulnerable to the floating point error. This is shown in this answer: https://stackoverflow.com/a/477635/2895835 – Bread Jan 25 '22 at 05:09
-1

You should read anwsers under this question: How to use a decimal range() step value?

After you create an array or list or whatever you want you can always remove some positions. Or if you only want to print it you can also use if statement.

MariAd
  • 26
  • 5