Hi again,

I'm here to ask another stupid question so I apologize. I'm going to make a calculator in Python but I've ran into a wall, with the tutorials I've been following I've only ever been taught how to add two numbers together. Never have I learned how to add as many numbers as the user wants.

If you have the time could someone please explain how I could do this? Where a user can enter how many numbers he wants to add instead of just two.

Thank you!

First, never feel like you have to apoligize for asking a question, no matter how stupid it may seem. It's how we come to understand the things we are trying to learn.

On to your question.. there are a couple of ways you can do this. If you only want to add and you are assigning your input to a list you can simply use the sum() function. It looks something like this:

numbers = [1, 2, 3]
answer = sum(numbers)

another way would be to use a for loop, doing something like this:

def add(numbers):
    a = 0
    for num in numbers:
        a += num
    return a

if your writing a calculator, you may find this way to be more flexible than the first.

Thanks for your help, imamyth.

How would I actually impliment that second piece of code?

The example I gave above is pretty much a rewrite of the built-in sum() function. it expects a list of integers as an argument then loops through the list adding each value to the value stored in a. Here is a basic example to put it into context. It will prompt for input, add that input to what was previously entered an print until the total is equal to or greater than 100.

add(numbers):
    a = 0
    for num in numbers:
        a += num
    return a

my_numbers = []
while 1:
    my_numbers.append(input("+ "))
    print(add(my_numbers))     # We call our add function as an argument to 'print'
    if add(my_numbers) >= 100:    # We use it again in combination with an if 
        break

You will get the same results if you use the sum() function:

    my_numbers = []
    while 1:
        my_numbers.append(input("+ "))
        print(sum(my_numbers)) # Using built-in sum() instead of our add()
        if sum(my_numbers) >= 100:
            break

if however, you use something like the add function we've written you can expand it to perform checks on your input or perform operations other than simple addition.

So I do something like this?

while 1:
    my_numbers = input("Type in numbers: ")
    my_numbers.append(input("+ "))
    print(add(my_numbers))     # We call our add function as an argument to 'print'
    if add(my_numbers) >= 100:    # We use it again in combination with an if 
        break

Well, not exactly. If you were to run that through the interpreter as written it will throw an error. The example I gave takes one number at a time. If you want to enter all of your numbers on one line that is a little different. You will want to use raw_input() then the split() method to get the individual numbers. Since your input will be a string you will also need to tell python that you intend to use integers instead of strings.

my_string = raw_input("Type in numbers: ")
my_string = my_string.split()
my_numbers = []
for item in my_string:
    my_numbers.append(int(item)) # Convert to int and append to my_numbers.
result = add(my_numbers) # add it all up and assign to result.

You can also use the Python function eval():

print("A math expression is something like 3+5+7 (no spaces)")
math_expression = raw_input("Enter a math expression: ")
result = eval(math_expression)
print("Result of %s is %s" % (math_expression, result))

Thank you guys so much!

You have helped me a lot!

To prevent some jerko to delete files from your disk with function eval(string), simply add this extra line:

print("A math expression is something like 3+5+7 (no spaces)")
math_expression = raw_input("Enter a math expression: ")
if 'os' not in math_expression:
    result = eval(math_expression)
print("Result of %s is %s" % (math_expression, result))

It's not at all safe, the string could contain shutil.rmtree(). My advice is to write a true math parser, or use pyTony's snippet.

Since all the troublemakers have to be imported, I would change 'os' to 'import' like this:

print("A math expression is something like 3+5+7 (no spaces)")
math_expression = raw_input("Enter a math expression: ")
if 'import' not in math_expression:
    result = eval(math_expression)
print("Result of %s is %s" % (math_expression, result))

It doesn't work, look at this

>>> eval("eval('__imp' + 'ort__(' + '\\'o' + 's\\')').unlink('foo')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'foo'

python is too talented for symbolic manipulations.

Hmm, logic conclusion would be:

print("A math expression is something like 3+5+7 (no spaces)")
math_expression = raw_input("Enter a math expression: ")
if '_' not in math_expression:
    result = eval(math_expression)
print("Result of %s is %s" % (math_expression, result))

Yes, there is:

print(chr(95))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.