On 24May2022 21:14, Kevin M. Wilson <kevinmwilson1...@yahoo.com> wrote:
>future_value = 0
>for i in range(years):
># for i in range(months):
>   future_value += monthly_investment
>   future_value = round(future_value, 2)
>   # monthly_interest_amount = future_value * monthly_interest_rate
>   # future_value += monthly_interest_amount
>   # display the result
>   print(f"Year = ", years + f"Future value = \n", future_value)
>
>When joining a string with a number, use an f-string otherwise, code a
>str() because a implicit convert of an int to str causes a
>TypeError!Well...WTF! Am I not using the f-string function
>correctly...in the above line of code???

The short answer is that you cannot add (the "+" operator) a string to 
an integer in Python because one is a numeric value and one is a text 
value. You would need to convert the int to a str first if you really 
wanted to.  But in your code above, you don't need to.

Let's pick apart that print():

    print(
        f"Year = ",
        years + f"Future value = \n",
        future_value
    )

Like any function, print()'s arguments are separate by commas. So you've 
got 3 expressions there. The problematic expression looks like this 
one:

    years + f"Future value = \n"

You didn't supply a complete runnable example so we don't see "years" 
get initialised.  However, I assume it is an int because range() only 
accepts ints. You can't add an int to a str.

Now, print() converts all its arguments to strings, so there's no need 
for f-strings anywhere in this. I'd go:

    print("Year =", years, "Future value =", future_value)

myself. If you really want that newline, maybe:

    print("Year =", years, "Future value =")
    print(future_value)

Format strings are for embedding values inside strings, which you don't 
need to do in your code as written. And whether you wrote:

    years + f"Future value = \n"

or:

    years + "Future value = \n"

(because that string has no embedded values) it is still wrong because 
years is an int and the string is still a str.

You _could_ use an f-string to compute the whole print line in one go:

    print(f"Year = {years} Future value = \n{future_value}")

but I can't see the point, personally. I've code from people who prefer 
that form though.

BTW, it helps people to help you if you supply a complete example. Your 
example code did not initialise years or monthly_investment, and so will 
not run for someone else. It also helps to winnow it down to the 
smallest example you can which still shows the problem. FOr yoru example 
you could have reduced things to this, perhaps:

    years = 9
    years + f"Future value = \n"

Cheers,
Cameron Simpson <c...@cskk.id.au>
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to