not all arguments converted during string formatting


Estimated reading time: 2 minutes

In our latest post, we are going to discuss formatting issues that you may come across. It relates to how you format the data when passing it from the input of a user.

This scenario can happen as a result of user input, which then has some comparisons completed on it.

How does the problem occur?

The problem occurs when you pass the data, but do not format it correctly before you present it in the output.

In the below code you will see these lines:

print ("'{0}' is older than '{1}'"% age1, age2)
print("'{0}'is younger than '{1}', that looks correct!" % age1, age2)

The specific problem is that when you put the % before age1, and age 2 you will get this TypeError.

Why does the problem occur?

This problem occurs as the way you are referencing age1 and age2 has been deprecated.

For reference please look at PEP 3101 – Advanced String Formatting, but essentially if you are using % it is the old way of achieving this!

How can the problem be fixed?

So to fix this please look at the below code:

age1 = input("Please enter your age: ")
age2 = input("Please enter your father's age: ")

if age1 == age2:
    print("The ages are the same, are you sure?!")
if age1 > age2:
    #print ("'{0}' is older than '{1}'"% age1, age2)
    print("'{0}' is older than '{1}', you better check!" .format(age1, age2))
if age1 < age2:
    print("'{0}'is younger than '{1}', that looks correct!" % age1, age2)
    #print("'{0}'is younger than '{1}', that looks correct!".format(age1, age2))

As you can see, I have included the old incorrect code and the new correct code, and when I use the proper Python logic, it gives me the correct output as follows:

Please enter your age: 25
Please enter your father's age: 28
'25'is younger than '28', that looks correct!

Process finished with exit code 0