joe walley
joe walley

Reputation: 1

Multiplication in a variable

I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.

while True:
    try:
        num = int(input("enter a 7 digit number: "))
        check = len(str(num))

        if check == 7:
            print("This code is valid")
            break

        else:
            num = int(input("enter a number that is only 7 digits: "))

    except ValueError:
        print("you must enter an integer")


num = int(num)        

def multiplication():
    num[0]*3
    num[1]*1
    num[2]*3
    num[3]*1
    num[4]*3
    num[5]*1
    num[6]*3
    return total

multiplication()

When I run it, I get the following error:

Traceback (most recent call last): 
  File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 29, in <module> 
    multiplication() 
  File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 20, in multiplication 
    num[0]*3 
TypeError: 'int' object is not subscriptable

Any feedback is welcome

Upvotes: 0

Views: 815

Answers (5)

Eric
Eric

Reputation: 254

This should help

    num = ''
    check = 0
    while True:
        try:
            num = raw_input("enter a 7 digit number: ")
            check = len(num)

            if check == 7:
                print("This code is valid")
                break

            else:
                print "enter a number that is only 7 digits"

        except ValueError:
            print("you must enter an integer")


    def multiplication():
        total = 0
        for i in range(check):
            if i % 2 == 0:
                total += int(num[i]) * 3
            else:
                total += int(num[i]) * 1

        print total

    multiplication()

Upvotes: 0

user6320679
user6320679

Reputation:

This code will works:

while True:
    try:
        num = int(input("enter a 7 digit number: "))
    except ValueError:
        print("you must enter an integer")

    else:

        if len(str(num)) != 7:
            print("enter a number that is only 7 digits")            
        else:
            break

num = str(num)

def multiplication():
    total = 0 
    for i,m in enumerate([3,1,3,1,3,1,3]):        
       total += int(num[i])*m   # transform the index of text into a integer

    return total

print(multiplication())

Upvotes: 0

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28424

Of course, your code might be written in a number of ways, optimized (check @Kasravand answer, it's awesome) or not, but with a minimal effort this is what I get:

while True:
    try:
        num = input("enter a 7 digit number: ")
        check = len(num)
        int(num) # will trigger ValueError if not a number

        if check == 7:
            print("This code is valid")
            break
        else:
            print("bad length, try again")

    except ValueError:
        print("you must enter an integer")

def multiplication(num):
    total  = int(num[0])*3
    total += int(num[1])*1
    total += int(num[2])*3
    total += int(num[3])*1
    total += int(num[4])*3
    total += int(num[5])*1
    total += int(num[6])*3

    return total

print("Answer: ", multiplication(num))

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

When you convert the input number to an integer you can not use indexing on that object since integers don't support indexing. If you want to multiply your digits by a specific number you better do this before converting to integer.

So first off replace the following part:

num = int(input("enter a number that is only 7 digits: "))

with:

num = input("enter a number that is only 7 digits: ")

The you can use repeat and chain functions from itertools module in order to create your repeated numbers, then use a list comprehension to calculate the multiplication:

>>> from itertools import repeat, chain
>>> N = 7
>>> li = list(chain.from_iterable(repeat([3, 1], N/2 + 1)))
>>> num = '1290286'
>>> [i * j for i, j in zip(map(int, num), li)]
[3, 2, 27, 0, 6, 8, 18]

Upvotes: 1

tschale
tschale

Reputation: 975

If you're bound to use an integer instead of a list for the input, you can do one of the following:

You could access the individual digits using a combination of integer division and modulo, for example:

first_digit = num // 1000000 * 3
second_digit = num // 100000 % 10 * 1
# and so on

Or you could get the input as a string and access and convert the individual digits:

# [...]
num = input("enter a number that is only 7 digits: ")
# [...]
first_digit = int(num[0]) * 3
second_digit = int(num[1]) * 3

Upvotes: 1

Related Questions