Alfie Baker
Alfie Baker

Reputation: 11

Making a loop to go on for as long as the number is

I want a program so I can enter a big integer and it will do a calculation like this: 62439 = (6 - 2 + 4 - 3 + 9)

Basically it splits them up and the first and third should be added and the second and the fourth should be subtracted. Please follow the loop sort of method. I can't have the elif and if working in the same run of the loop.

num = input("Input any number: ")
total = 0
p = 0
x= 0
q = 0
number = len(num)
if len(num) ==5 :
    total = 0
    for i in range(0,(number)):
        p = p+2
        q = q +1
        if x == 2 and q == p:
            total = total+(int(num[q]))
            x=1
            p=p-1
        elif  x == 1 and q == p :
            total = total-(int(num[q]))
            x=2
            p=p-1
    print("your number is: ",total)

I expect it to repeat the loop as many times as there are numbers in the integer that is entered e.g (333) executes 3 times

Upvotes: 1

Views: 68

Answers (3)

Paul M.
Paul M.

Reputation: 10799

Maybe like this:

def main():

    digits = input("Enter a number: ")
    assert digits.isdigit()
    result = sum(int(digit) * [1, -1][index%2] for index, digit in enumerate(digits))
    print(f"Result: {result}")

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

Or like this if you wanna be more deliberate - also easier to extend:

def main():

    from operator import add, sub

    digits = input("Enter a number: ")
    assert digits.isdigit()

    operations = [add, sub]
    result = 0
    for index, digit in enumerate(digits):
        result = operations[index%len(operations)](result, int(digit))
    print(f"Result: {result}")

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

Or just go overkill (also known as "taking advantage of the standard library"):

def main():

    from itertools import cycle
    from operator import add, sub
    from functools import reduce

    while True:
        digits = input("Enter a number: ")
        if digits.isdigit():
            break

    operation_iter = cycle([sub, add])
    def operation(a, b):
        return next(operation_iter)(a, b)

    result = reduce(operation, map(int, digits))

    print(f"Result: {result}")

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

Upvotes: 0

Booboo
Booboo

Reputation: 44108

num = input("Enter a number: ")

sum = 0
do_add = True
try:
    for digit in num:
        if do_add:
            sum += int(digit)
        else:
            sum -= int(digit)
        do_add = not do_add
except Exception:
    print("Invalid input")
else:
    print("The result is", sum)

Upvotes: 2

quamrana
quamrana

Reputation: 39354

Why not just perform the calculation:

num = input("Input any number: ")
if len(num) == 5:
    total = int(num[0])-int(num[1])+int(num[2])-int(num[3])+int(num[4])
    print("your number is: ",total)

Upvotes: 0

Related Questions