Hello, I am new to the forums and I am just starting to learn python. I have been writing the following program and have ran into a problem with getting it to work right. If anyone can offer some advice on what I am doing wrong I would be thankful. This program is suppose to get a starting value and an ending value and then print just the even numbers, including the starting and ending values if necessary. My problem is if I start with an even number and end with an even number it doesn't print the last even number.
Also any advice on things I can do better in writing the code would be great to hear I want to be good at coding.

Thanks again for anyone who reads this and helps.

def main():
  x = input('Enter a starting value: ')
  y = input('Enter an ending value: ')
  for i in range(x, y, 2):
      if(x%2!=0):
        i = i + 1
        print i
      else:
        print i

I would fix it like this:

def main():
  x = input('Enter a starting value: ')
  y = input('Enter an ending value: ')
  # add one to odd starting value and add one to end value to
  # also get y included
  for i in range(x + (x & 1), y + 1, 2):
        print i

main()

You can of course use also x % 2 for odd detection, but as division is heavy operation I usually prefer and.

commented: Thanks, worked perfectly +0

Thank you, for your help. That makes a lot of sense I wasn't thinking about having to get y in there too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.