Python Forum

Full Version: multiplication by successive addition
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Guys, im from Brazil and I just started a python course a couple days back. This program is supposed to multiply 2 numbers and show the subtotal of the calculation. However, in this project, i'm not supposed to use the "*" operator, just "-" or "+". How can I do that? In my code, I used "*" twice, as you can see.
Thanks.

def back():
    while True:
        try:
            m1=input("Number 1: ")
            m2=input("Number 2: ")
            m1=int(m1)
            m2=int(m2)
            result=m1*m2 #### i'm not supposed to use "*"
            save1=m1
            save2=m2
        except ValueError:
            print("Error in number 1 or 2. Try again.")
            continue
        break
    subtotal=0
    if m1<m2:
        aux = m2
        m2 = m1
        m1 = aux
    if m2>0:
        while m2>0:
            m2=m2-1
            subtotal=subtotal+m1
            print("ST:", subtotal)
    if m2<0:
        while m2<0:
            m2=m2+1
            subtotal=subtotal+m1
            print("ST:", subtotal * -1)   ### again, i'm not supposed to use "*"
    print(save1,"*",save2,"=", result)
    reset=input("Type Y for a new operation")
    if reset == "Y" or reset == "y" or reset == "Yes" or reset == "yes":
        back()
    else:
        print("Closing...")
back()
If you need to multiply x and y using addition, you add up y x's. 2 * 3 = 2 + 2 + 2. So use a for loop. Start with the result equal to zero. Have a for loop to loop y times. Each time through the loop add x to the result.