Write a Python program: a.Prompt the user to enter starting number, increment, a
ID: 3556798 • Letter: W
Question
Write a Python program:
a.Prompt the user to enter starting number, increment, and the ending number (all integers).
b.Sum up the number from starting number through the ending number with increment entered. For example, (1,10,1) will imply starting number of 1 and ending number of 10, and increment of 1. (i.e. 1,2,3,4,5,6,7,8,9,10).
c.Program should check for validity of numbers entered. If user enters invalid combination such as (1,10, -1), re-prompt the user to enter proper set of numbers.
d.Display the sum of the numbers.
e.Display the average of the numbers.
f.Display the total number of items added.
g.For example, if user entered (1,10,1). The sum should be 55. The average should be 5.5, and, the number of items = 10.
h.Prompt the user
Explanation / Answer
def check(start, inc, end):
if inc <= 0: return False
if start > end: return False
return True
def work():
start = int(raw_input('Enter starting number: '))
inc = int(raw_input('Enter increment: '))
end = int(raw_input('Enter ending number: '))
sum = 0
added = 0
average = 0.0
if(check(start, inc, end)): # check if values are valid
for i in range(start, end+1, inc):
sum += i
added += 1
average = float(sum) / float(added)
print "Sum: %d" % sum
print "Average: %f" % average
print "Number of items: %d" % added
else:
print "Invalid values! Enter again ";
work() # If invalid then recursively call this function again
if __name__ == '__main__':
again = True # Used for re-running the program
while again:
work()
ans = raw_input('Dou you want to continue (yes/no): ')
if(ans[0].lower() == 'y'): # taking the first character of the ans
again = True
else:
again = False
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.