Python 2: Adding Integers In A For Loop
I am working on lab in class and came across this problem: Write a program using a for statement as a counting loop that adds up integers that the user enters. First the program as
Solution 1:
I think this is what you're asking:
Write, using a for loop, a program that will ask the user how many numbers they want to add up. Then it will ask them this amount of times for a number which will be added to a total. This will then be printed.
If this is the case, then I believe you just need to ask the user for this amount of numbers and write the for loop in a similar fashion to your's:
NumOfInt = int(input("How many numbers would you like to add up? : "))
total = 0for i inrange (NumOfInt):
newnum = int(input("Enter a number! : "))
total += newnum
print("Your total is: " + str(total))
This will add their input to the total until the amount of numbers they have input exceeds NumOfInt:
Howmanynumberswouldyouliketoaddup? : 4Enteranumber! : 1Enteranumber! : 2Enteranumber! : 3Enteranumber! : 4Yourtotalis: 10
I hope this helps :)
Solution 2:
number = int(raw_input("How many numbers?"))
tot = 0for x in range(number):
tot += int(raw_input("Enter next number:"))
print tot
Post a Comment for "Python 2: Adding Integers In A For Loop"