How to print all numbers in range from two inputs which are divisible by 3 with while loop? If num_1 is smaller than num_2 then step should be increased and how to make it opposite??
num_1 = int(input("First number : "))
num_2 = int(input("Second number : "))
i = num_1
while i in range(num_1, num_2):
if i % 3 ==0 and num_1 < num_2:
print(i)
i = 1
else:
if i % 3 ==0 and num_1 > num_2:
print(i)
i -= 1
CodePudding user response:
You don't need to use a while loop for this. If you want all numbers divisible by three within a given range, you can do this in a single line of code (excluding the inputs):
a = 0
b = 100
l = [x for x in range(a, b) if x%3 == 0]
The result would be:
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
You could also make this a function for better reuse:
def get_divisible_numbers(a, b, divisor):
"""
Returns a list of all numbers between two numbers that are divisible by a given number.
"""
return [x for x in range(a, b) if x%divisor == 0]
CodePudding user response:
First of all i in range(num_1, num_2) returns type bool, so your while loop will either block or skip.
You can use for instead of while, it will traverse the range(num_1, num_2)
The range function can pass in the step parameter to control the step size, negative numbers are reverse
Use while:
num_1 = int(input("First number : "))
num_2 = int(input("Second number : "))
total = abs(num_1 - num_2)
if num_1 < num_2:
step = 1
else:
step = -1
r = range(num_1, num_2, step)
i = 0
while abs(i) < total:
if r[i] % 3 == 0:
print(f"i: {i}, v: {r[i]}")
i = step
else:
print('')
Demo:
First number : 1
Second number : 11
i: 2, v: 3
i: 5, v: 6
i: 8, v: 9
First number : 11
Second number : 1
i: -2, v: 3
i: -5, v: 6
i: -8, v: 9
Use for:
num_1 = int(input("First number : "))
num_2 = int(input("Second number : "))
if num_1 < num_2:
step = 1
else:
step = -1
for i in range(num_1, num_2, step):
if i % 3 == 0:
print(i)
print('')
Demo:
First number : 1
Second number : 11
3
6
9
First number : 11
Second number : 1
9
6
3
CodePudding user response:
There's a number of syntax issues (e.g. indentation). Fixing them up, the following should work:
num_1 = int(input("First number : "))
num_2 = int(input("Second number : "))
i = num_1
while i in range(num_1, num2):
if i % 3 ==0:
print(i)
i = 1
To handle changing the order of iteration depending on the values of num_1 and num_2 (as asked in a comment), you can do the following:
num_1 = int(input("First number : "))
num_2 = int(input("Second number : "))
if num_1 < num_2:
for i in range(num_1, num_2):
if i % 3 == 0:
print(i)
else:
for i in range(num_1, num_2 - 1, -1):
if i % 3 == 0:
print(i)
