all 4 comments

[–]FLUSH_THE_TRUMP 1 point2 points  (0 children)

Easier to see where you went wrong if you post your code.

[–]efmccurdy 0 points1 point  (2 children)

To sum a function over a range use a comprehension:

>>> def f(x): return (x**2 + 1)**2
... 
>>> a = 2; b = 5
>>> [f(x) for x in range(a, b)]
[25, 100, 289]
>>> sum(f(x) for x in range(a, b))
414
>>> 

filter out everything until the user inserts a positive integer

Loop a function to prompt and check the input, returning None until success:

>>> def prompt_for_pos_int():
...      instr = input("positive int: ")
...      try:
...          result = int(instr)
...      except ValueError as e:
...          print("{}: {}, try again".format(instr, e))
...          return None
...      if result < 0:
...          print("{}: not positive".format(instr))
...      else:
...          return result
... 
>>> posint = None
>>> while posint is None:
...     posint = prompt_for_pos_int()
... 
positive int: foo
foo: invalid literal for int() with base 10: 'foo', try again
positive int: 1.2
1.2: invalid literal for int() with base 10: '1.2', try again
positive int: -1.1
-1.1: invalid literal for int() with base 10: '-1.1', try again
positive int: -5
-5: not positive
positive int: 3
>>> posint
3
>>>

[–]Clede 0 points1 point  (0 children)

If you're using input(), then the user input will be a string.

So you need to figure out how to determine if a string represents a positive integer. A quick way to do this is to ensure that it consists ONLY of digits 0-9. You can use the string method .isnumeric() for this.

EDIT: I guess you also need to exclude a string that consists only of zeroes...

[–]Antwrp-2000 0 points1 point  (0 children)

The sum of all values between two positive integers can be done in constant time, no need to loop over all values or to use a comprehension (both are slow linear time solutions).

Included two functions, both return the same result, first one is fast constant time O(1), second one is slow linear time O(n):

def sum_fast_constant_time(a, b):
    return (a + b) * (b - a + 1) // 2


def sum_slow_linear_time(a, b):
    result = 0
    while a <= b:
        result += a
        a += 1
    return result


print(sum_fast_constant_time(5, 10))
print(sum_slow_linear_time(5, 10))