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 = 0
for i in range (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:
How many numbers would you like to add up? : 4
Enter a number! : 1
Enter a number! : 2
Enter a number! : 3
Enter a number! : 4
Your total is: 10
I hope this helps :)
Solution 2:
number = int(raw_input("How many numbers?"))
tot = 0
for 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"