[Tutor] Issue with Python

Steven D'Aprano steve at pearwood.info
Fri Nov 14 05:22:05 CET 2014


On Fri, Nov 14, 2014 at 10:07:08AM +1100, Daniel Williams wrote:
> Hi, I'm dw0391
> I have an issue with a class task that my teacher can't seem to fix.

Oooh, that's sad that your teacher can't fix this.

Jumping ahead to the relevant part of the code, I can see two errors 
with the same line of code:

print ("You need to pay:"% rate, "each month")

The first error is that the variable `rate` is not defined when the 
print line is run. You will get an error like:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'rate' is not defined

The print line should be indented, so that it is part of the main 
function. Putting some comments in, you have:

# define a function called "main"
def main():
    # everything indented is part of main()
    loantotal = float(input("Total of Loan: $"))
    timetotal = float(input("Time Provided (in months):"))
    rate = payrate(loantotal, timetotal)

# The next line is NOT indented, so it is not part of the function.
# Instead, it tries to run immediately, but fails because there is
# no variable called `rate` defined yet.
print ("You need to pay:"% rate, "each month")



To fix that bug, simply indent the print(...) line so that it is level 
with the rest of the main() function:

def main():
    # everything indented is part of main()
    loantotal = float(input("Total of Loan: $"))
    timetotal = float(input("Time Provided (in months):"))
    rate = payrate(loantotal, timetotal)
    print ("You need to pay:"% rate, "each month")


That will then reveal the second error:

TypeError: not all arguments converted during string formatting

which seems a bit cryptic, but all it means is that when Python tries to 
"glue" the pieces of the strings together, it doesn't know where to 
stick them together. The problem is that you try using the string 
formatting operator % like this:

    "You need to pay:" % rate


which causes Python to glue the string value of `rate` into the string 
"You need to pay:", but it needs a formatting code %s to know where to 
put the pieces together. You can fix this problem in two ways:

    print("You need to pay: %s" % rate, "each month")

or avoid string formatting altogether:

    print("You need to pay:", rate, "each month")


The difference between a comma and a percent sign isn't much, but they 
do completely different things and work in very different ways.


-- 
Steven


More information about the Tutor mailing list