Accumulator using For Loop in Python

My teacher wants a program to ask the user for a positive integer number value, which the program should loop to get the sum of all integers from 1 up to the numbered entered. In For Loop using Python.

Here's what I came up with for the For Loop but it is not's not looping when I type in a negative number and it won't display an answer when I input a positive number after inputting a negative number.

x=int(input("Please pick a positive integer"))
sum=0
for i in range(1,x): sum=sum+1 print(sum)
else: x=int(input("Please pick a positive integer"))

Help?

1

2 Answers

How about implementing something like the following. There are a few problems with your program, most notably:

1. The sum is being repeatedly printed for every value.

2. You are simply adding 1 to the sum instead of adding the integer i.

3. You are not returning on your function if your user does not enter a positive integer.

4. You have no if statement for if the integer is greater than 0.

def intpicker(): x=int(input("Please pick a positive integer")) sum=0 if x >= 0: for i in range(1,x): sum=sum+i print(sum) else: return intpicker()

This code could be further abbreviated, but for all intents and purposes you should probably just try and understand this implementation as a start.

1

There are a few fatal flaws in your program. See below:

x=int(input("Please pick a positive integer")) #what if the user inputs "a"
sum=0
for i in range(1,x): # this will not include the number that they typed in sum=sum+1 # you are adding 1, instead of the i print(sum)
else: x=int(input("Please pick a positive integer")) # your script ends here without ever using the above variable x

This is what I might do:

while True: # enters loop so it keeps asking for a new integer sum = 0 x = input("Please pick an integer (type q to exit) > ") if x == "q": # ends program if user enters q break else: # try/except loop to see if what they entered is an integer try: x = int(x) except: print "You entered {0}, that is not a positive integer.".format(x) continue for i in range(1, x+1): # if the user enters 2, this will add 1 and 2, instead of 1. sum += i print sum

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like