'I got formatting type error but I don't know why this happen
#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?
Solution 1:[1]
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)
Solution 2:[2]
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | azro |
| Solution 2 | Gino Mempin |
