# What is the alternative of %d in Python? [C and Python comparison]

Suppose, input is a and b.
and output will be like,
a + b = (summation of a and b)
a - b = (subtraction of a and b)
a * b = (multiplication of a and b)
a / b = (Division of a and b)
Note:i can use just one print function inside this program and normally i’ve to use \n to create newline.
If i write this in C then it;ll be like:

``````#include <stdio.h>
int main()
{
int a, b;
scanf("%d %d",&a,&b);

printf("a+b = %d\na-b = %d\na*b = %d\na/b = %d",a+b,a-b,a*b,a/b);

return 0;
}
``````

And output is correct here:

``````5 2
a+b = 7
a-b = 3
a*b = 10
a/b = 2
Process returned 0 (0x0)   execution time : 5.089 s
Press any key to continue.
``````

Here,i can control every output by %d inside `printf` function.But, how i’ll write this in python just using one print function.
i try it ,but failed.
My code in python:

``````a = input()
b = input()
a = int(a)
b = int(b)
print("a + b = %d\na - b = %d\na * b = %d\na / b =%d\n",a+b,a-b,a*b,a/b)

``````

if i input 5 as a and 2 as b then,output look like,

``````C:\Users\Plabon kumer Sarker\Desktop\python 1st part>arithmeticex3.py
5
2
a + b = %d
a - b = %d
a * b = %d
a / b =%d
7 3 10 2.5
``````

That means, `%d` not work in python But,How can i fix this?

1 Like

Python is maddeningly cavalier with typecasting. When dividing an integer by another integer, Python automatically promotes the result to a float.

To get the expected behavior for those of us from a C background, use floor division, `//`.

`a // b`

1 Like

Actually,i don’t get this concept yet.Can you please explain it more?

1 Like

No problem.

Consider the following code:

C

``````int a = 3, b = 2;
printf("a / b = %d\n", a / b);
``````

Python

``````a = 3; b = 2
print("a / b = " + str(a / b) + "\na // b = " + str(a // b))
``````

You get the following results

C

``````a / b = 1
``````

Python

``````a / b = 1.5
a // b = 1
``````

In C, an arithmetic operation between two integers will return an integer.

In Python, addition, subtraction, and multiplication between integers returns an integer, but division between two integers returns a float. You specifically have to use the integer division operation `//` to get an integer back.

1 Like

Hello Plabon.

The way I have always done it is:

``````a = 5
b = 2
print(f'a + b = {a+b}')
``````

Hope this helps

1 Like

Yes it is!!!

``````a = input()
b = input()
a = int(a)
b = int(b)
print(f"a+b = {a+b}\n"f"a-b = {a-b}\n"f"a*a = {a*a}\n"f"a/a = {a/b}\n"f"a%b = {a%b}\n"f"a//b = {a//b}\n"f"a**b = {a**b}")
``````

Thank you so much Shaun   Thank you so much Bob This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.