-4

I'm using JES. The function below will work for what I want it to do, but it doesn't include x and y in the answer. For example, if the first number I enter is 2 and the second number is 8, it prints only 4 and 6. I want it to print 2, 4, 6, 8. Please help! Thanks!

def main():
  x=input("Enter the first number:")
  y=input("Enter the second number:")
  i=0
  for i in range (x,y):
    if i%2==0:
      print i
David Robinson
  • 77,383
  • 16
  • 167
  • 187
Emily Jordan
  • 29
  • 2
  • 3

2 Answers2

2

Quite simply, the problem is that, in Python (and, by extension, JES), range(x, y) steps from x to y-1, inclusive. This allows it to naturally mimic the slicing syntax of the [] list operator, i.e. [l[a] for a in range(x, y)] is the same list as l[x:y]. (As for why both slicing and range do this, see Why does range(start, end) not include end?).

So, if you want x to y inclusive, you just need to bump the last parameter up by one:

for i in range(x, y+1):

and it should print out the numbers you want.

P.S. the i=0 before the loop is unnecessary. The for loop will initialize (and create if necessary) the variable i.

Community
  • 1
  • 1
nneonneo
  • 171,345
  • 36
  • 312
  • 383
1
print ",".join([str(i) for i in range(int(raw_input("Enter #1:")),\
                                      int(raw_input("Enter #2:"))+1) if not i%2])

I think I got those parens right

alternatively,Using input is shorter but a huge security hole and should usually be avoided

print ",".join([str(i) for i in range(input("Enter #1:"),\
                                      input("Enter #2:")+1) if not i%2])

and the shortest (thanks nneonneo)

print str([x for x in range(input('1'), input('2')+1) if not x%2])[1:-1] 
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Someone had to do and add the one-liner...you should replace `int(raw_input)` with `input` for brevity (security here is not a concern!) – nneonneo Sep 08 '12 at 01:33
  • `input` is horrible.... but yes that would be shorter :P – Joran Beasley Sep 08 '12 at 01:33
  • 1
    It's horrible, unless it does what you want it to do and you understand the ramifications. I submit that `print str([x for x in range(input('1'), input('2')) if not x%2])[1:-1]` is a shorter, though somewhat less readable one-liner :) – nneonneo Sep 08 '12 at 01:35
  • "Security here is not a concern!" Maybe, but it's a good idea to get into the habit of writing secure code, even for frivolous example/toy code. – Agi Hammerthief Jan 16 '15 at 07:07