Python Forum
Is there a way i print odd and even numbers separately?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a way i print odd and even numbers separately?
#1
I don't want the following output, I want the odd numbers, even numbers separately. Can you please help.
'''odd and even numbers under 10'''
for i in range(1, 11):
    if i % 2 == 0:
        print(i, " is even")
    else:
        print(i, "is odd")
Output:
1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even
Reply
#2
You could print all the even numbers then print all the odds. If you want all the evens on the same line you can print without a newline or you could join the numbers together in a single string before printing. What you cannot do is jump back and forth between lines.
Reply
#3
There should be a better way than this
'''odd and even numbers under 10'''
print("even numbers")
for i in range(1, 11):
    if i % 2 == 0:
        print(i, end=" ")
print()
print("odd numbers")
for i in range(1, 11):
    if i % 2 !=0:
        print(i, end=" ")
Output:
even numbers 2 4 6 8 10 odd numbers 1 3 5 7 9
Reply
#4
There are better ways, but not a lot better. But what you are doing is kind of odd to start with. Slightly better way:
print('Even numbers ', [x for x in range(0, 11, 2)])
print('Odd numbers ', [x for x in range(1, 11, 2)])
Or if you don't like the brackets:
print('Even numbers ', ', '.join([str(x) for x in range(0, 11, 2)]))
print('Odd numbers ', ', '.join([str(x) for x in range(1, 11, 2)]))
Reply
#5
What's wrong with that? How do you want to print them?
Reply
#6
There is nothing wrong but does it look like a good programming way? I am learning python, I don't want to go the wrong path. Thank you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to customize each x-axis separately? Mark17 4 1,925 Mar-10-2022, 02:56 PM
Last Post: Mark17
  Print max numbers in a list jimmoriarty 1 2,116 Sep-25-2020, 07:29 AM
Last Post: DPaul
  Supposed to print out even numbers DallasPCMan 4 1,891 May-21-2020, 05:50 PM
Last Post: ndc85430
  first k non prime numbers print bsrohith 7 7,416 Jun-20-2019, 10:48 AM
Last Post: arycloud
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,661 May-09-2019, 12:19 PM
Last Post: Pleiades
  Why can't I print numbers in Python? skrivver99 2 2,732 Nov-04-2018, 09:47 PM
Last Post: snippsat
  Print list from splitted range of numbers prashant8530 1 2,766 Sep-04-2017, 08:03 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020