What is the problem in this code? I am getting a problem in this piece of code

56 views Asked by At
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print('The product of {first} and {sec} is: ',a*b).format(first = a, sec = b)
print('The sum of {first} and {sec} is: ',a+b).format(first = a, sec = b)

Something of AttributeError is coming. Can you guys fix this, Need it for school project.

I tried this placeholder from [https://www.w3schools.com/python/ref_string_format.asp]

2

There are 2 answers

0
Corralien On BEST ANSWER

The order of your parameters is wrong:

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print('The product of {first} and {sec} is: '.format(first=a, sec=b), a*b)
print('The sum of {first} and {sec} is: '.format(first=a, sec=b), a+b)

Or for better understanding:

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
txt_prod = 'The product of {first} and {sec} is:'
txt_sum = 'The sum of {first} and {sec} is:'
print(txt_prod.format(first=a, sec=b), a*b)
print(txt_sum.format(first=a, sec=b), a+b)

However, it would be better to use f-strings:

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f'The product of {a} and {b} is: {a*b}')
print(f'The sum of {a} and {b} is: {a+b}')

Output:

Enter first number: 12
Enter second number: 4
The product of 12.0 and 4.0 is: 48.0
The sum of 12.0 and 4.0 is: 16.0
0
GokuMizuno On

The problem is that you have the .format in the wrong place. It needs to be inside the printf(), not attached behind it.

It would be better to use f-strings:

print(f'The product of {a} and {b} is: {a*b}')
print(f'The sum of {a} and {b} is: {a+b}')