Reputation: 3
I'm quite new to the for loops in Python. So, I want to write a program that asks the user to enter to enter 20 different scores and then I want the program to calculate the total and display it on the screen. How could I use a for loop to do this? edit: I can ask the user to for the different numbers but I don't know how to then add them.
Upvotes: 0
Views: 1591
Reputation: 431
total = 0
for _ in range(1,20):
num = input('> ')
total += int(num)
print(total)
I hope this helps.
Upvotes: 1
Reputation: 2652
Try something like this:
total = 0; # create the variable
for i in range(1,20): # iterate over values 1 to 20 as a list
total += int(input('Please enter number {0}: '.format(i)));
print("Sum of the numbers is '{0}'".format(total))
I'd suggest you go through the tutorials on the python site:
I could go into a lot of detail here and explain everything, however I'd only be duplicating the resources already available. Written far better than I could write them. It would be far more beneficial for you (and anyone else reading this who has a similar issue) to go through these tutorials and get familiar with the python documentation. These will give you a good foundation in the basics, and show you what the language is capable of.
To read a value from the commandline you can use the input
function, e.g. valueString = input("prompt text")
. Notice the value stored is of type string, which is effectively an array of ASCI/Unicode characters.
So in order to perform math on the input, you first need to convert it to its numerical value - number = int(valueString)
does this. So you can now add numbers together.
Say you had two numbers, num1
and num2
, you can just use the addition operator. For example num3 = num1 + num2
. Now suppose you have a for loop and want to add a new number each time the loop executes, you can use the total += newNum
operator.
Upvotes: 1
Reputation: 2440
Without giving you the full code here is the pseudocode for what your code should look like
x = ask user for input
loop up till x //Or you could hard code 20 instead of x
add user input to a list
end
total = sum values in list
print total
Here are all the things you need to implement the logic
User input/output: http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html
Loops: https://wiki.python.org/moin/ForLoop
Summing a list: https://docs.python.org/2/library/functions.html
Upvotes: 1