Home > Back-end >  I got formatting type error but I don't know why this happen
I got formatting type error but I don't know why this happen

Time:05-07

#35
name1 = "eric"
age1 = 10
name2 = "jay"
age2 = 13
print('name:',name1,'age:','%d','\n' 'name:',name2,'age:','%d' % (age1,age2))

I got an error which is this:

TypeError: not all arguments converted during string formatting

May I ask you why this error happen?

CodePudding user response:

You have passed several different string t the print method, they aren't one string, so the final one is incorrect : one placeholder for two values

'%d' % (age1,age2)

Either use one string and a placeholder for each value

print('name:%s  age:%d\nname:%s age:%d' % (name1, age1, name2, age2))

Or pass all of them as parameters of print (note that is puts a space between each)

print('name:', name1, 'age:', age1, '\n'   'name:', name2, 'age:', age2)

CodePudding user response:

Try to use f-strings which makes easier to use such as:

print(f'name: {name1}  age: %d, \n name: {name2} age: %d ' % (age1, age2))
  • Related