# Translating an algorithm into Python (int to str problem)

Hello:

As an exercise, I want to translate the algorithm for this question into code:

Question:
A bank account starts out with £10000. Interest is compounded monthly at 0.5 per cent per month. Every month £500 is withdrawn to meet college expenses. After how many years is the account depleted.

Algorithm:
balance = 10000
months = 0
while balance is > 0
Reduce the balance by £500
Increase the number of months by 1
Compute the number of years as months divided by 12
Report the number of years.

The code is:

``````balance = 10000
months = 0
interest = 0

while balance > 0 :
interest = balance * 0.005
balance += interest
balance -= 500
print("Month: " + months + "Balance: " + balance)
months += 1

years = months // 12
print ("The account will be depleted in: " + years )
``````

So how is it not doing what you want? Some more detail will help those that can…

This is the error:

Traceback (most recent call last):
File
line 12, in
print("Month: " + months + "Balance: " + balance)
TypeError: Can’t convert ‘int’ object to str implicitly

You have to cast your numbers to strings:

``````print("Month: " + str(months) + "Balance: " + str(balance))
``````

An alternative is to use the format method (this can be cleaner than concatenating multiple values):

``````print( "Month: {} Balance: {}".format(months, balance) )
``````
3 Likes
``````Or this:   print("Month", months, "Balance", balance)
``````

Without the `+` sign.

But why does this work:

``````print("The account will be depleted in", + years)
``````

when it’s a concatenation of string plus number?

Thanks!

Nothing is being concatenated in that example. You’re passing print two separate arguments: `"The account will be depleted in"` and `+4` (if years = 4). In this case Python is interpreting the + sign as positive 4 (as opposed to -4) and casting the int to a string.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.