Reputation: 3
Here is my code:
start=int(input('enter the starting range:'))
end=int(input('enter the ending range:'))
for d in range(start,end):
if d%2!=0:
print('The odd numbers between',start,'&',end,'is:',d)
Current output is:
enter the starting range:20
enter the ending range:30
The odd numbers between 20 & 30 is: 21
The odd numbers between 20 & 30 is: 23
The odd numbers between 20 & 30 is: 25
The odd numbers between 20 & 30 is: 27
The odd numbers between 20 & 30 is: 29
Wanted output is:
'The odd numbers between 20 & 30 is: 21,23,25,27,29'
What change do I need to make?
Upvotes: 0
Views: 1764
Reputation: 367
Simple and very neat solution: (added my comments so you can understand what I did)
start = int(input('enter the starting range: '))
end = int(input('enter the ending range: '))
#create an empty list
numbers = []
for d in range(start,end):
if d % 2 != 0:
#if number is odd, add it to the list
numbers.append(d)
#we use end=" " to make sure there is no new line after first print
print('The odd numbers between',start,'&',end,'are:',end=" ")
#* symbol is used to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively
print(*numbers,sep = ",")
Upvotes: 0
Reputation: 492
Using list comprehension you could make it more shorter
start=int(input('enter the starting range:'))
end=int(input('enter the ending range:'))
# New lines
numbers = ", ".join([str(i) for i in range(start, end) if i % 2 != 0])
print(f"The odds numbers between {start} and {end} are:", numbers)
Upvotes: 1
Reputation: 41
start=int(input('enter the starting range:'))
end=int(input('enter the ending range:'))
s = ""
for d in range(start,end):
if d%2!=0:
s += str(d) + ", ";
print('The odd numbers between',start,'&',end,'is:',s)
You should probably put it in a function but that's just a preference.
Upvotes: 0
Reputation: 35560
Print the message before the loop then the numbers during the loop:
start = int(input('enter the starting range:'))
end = int(input('enter the ending range:'))
# use end='' to avoid printing a newline at the end
print(f'The odd numbers between {start} & {end} is: ', end='')
should_print_comma = False
for d in range(start,end):
if d%2!=0:
# only start printing commas after the first element
if should_print_comma:
print(',', end='')
print(d, end='')
should_print_comma = True
Upvotes: 0