working with negative numbers in python

dman762000 picture dman762000 · Mar 16, 2010 · Viewed 127.5k times · Source

I am a student in a concepts of programming class. The lab is run by a TA and today in lab he gave us a real simple little program to build. It was one where it would multiply by addition. Anyway, he had us use absolute to avoid breaking the prog with negatives. I whipped it up real quick and then argued with him for 10 minutes that it was bad math. It was, 4 * -5 does not equal 20, it equals -20. He said that he really dosen't care about that and that it would be too hard to make the prog handle the negatives anyway. So my question is how do I go about this.

here is the prog I turned in:

#get user input of numbers as variables

numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0
count = 0

#output the total
while (count< abs(numb)):
    total = total + numa
    count = count + 1

#testing statements
if (numa, numb <= 0):
    print abs(total)
else:
    print total

I want to do it without absolutes, but every time I input negative numbers I get a big fat goosegg. I know there is some simple way to do it, I just can't find it.

Answer

Mike Graham picture Mike Graham · Mar 16, 2010

Perhaps you would accomplish this with something to the effect of

text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.

if b > 0:
    num_times = b
else:
    num_times = -b

total = 0
# While loops with counters basically should not be used, so I replaced the loop 
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
    total += a 
    # We do this a times, giving us total == a * abs(b)

if b < 0:
    # If b is negative, adjust the total to reflect this.
    total = -total

print total

or maybe

a * b