Reputation: 5
This script will accept two whole number inputs . first input will always be (-) than the second. script will display sum of every other whole number inputs.
script will not print any other text to the console other than the result of the operation.
here's the code i've written - so far i'm able to accept input but it produces an infinite loop and doesn't sum.
thanks
if __name__ == "__main__":
# user inputs digits
start = int(input())
stop = int(input())
# sum the range of above
while start < stop:
print(sum for i in range(start, stop, 2))
Upvotes: 0
Views: 789
Reputation: 358
Your start
is always smaller than stop
so of course the loop always runs.
If it was the other way around it would not even run once.
You have a for
loop inside a while
and that can be avoided as well:
# user inputs digits
start = int(input())
stop = int(input())
# sum the range of above
result = 0
for i in range(start, stop, 2):
result += i
Or, even better,
result = sum(range(start, stop, 2))
Upvotes: 0
Reputation: 35560
If you want to sum the range, then you don't even need a loop, as the range
basically acts as your loop:
# user inputs digits
start = int(input())
stop = int(input())
# sum the range of above
print(sum(range(start, stop, 2)))
Upvotes: 1
Reputation: 118021
In your problem start
will always be less than stop
, so the while
loop never exits. Instead you can keep a variable that starts at start
and increments by 2
until reaching stop
.
# user inputs digits
start = int(input())
stop = int(input())
i = start
total = 0
while i < stop:
total += i
i += 2
For conciseness, this can simply be done with
total = sum(range(start, stop, 2))
Upvotes: 1