-1

I am learning Python, and I got an error, searched online but I still don't understand why. What am I doing wrong?

Code:

 length = float(input("please input the length: "))
unit = input("please input the unit: ")
if unit == "in" or "inch":
    length_b = float(length / 2.54)
    print("%f inch = %f cm"(length, length_b))
elif unit == "cm":
    length_b = float(length * 2.54)
    print("%f cm = %f inch"(length, length_b))
else:
    print("calculation failed")

and I got this error:

test.py:143: SyntaxWarning: 'str' object is not callable; perhaps you missed a comma?
  print("%f inch = %f cm"(length, length_b))
test.py:146: SyntaxWarning: 'str' object is not callable; perhaps you missed a comma?
  print("%f cm = %f inch"(length, length_b))
halfer
  • 19,824
  • 17
  • 99
  • 186
Fang Guo
  • 1
  • 3
  • 2
    In both print statements you forgot to add %, it should look like this: ```print("%f cm = %f inch"%(length, length_b))``` – EnriqueBet Apr 03 '20 at 15:13

1 Answers1

2

You have to use % in your print statements like this:

length = float(input("please input the length: "))
unit = input("please input the unit: ")
if unit == "in" or unit == "inch":
    length_b = float(length / 2.54)
    print("%f inch = %f cm"%(length, round(length_b,6)))
elif unit == "cm":
    length_b = float(length * 2.54)
    print("%f cm = %f inch"%(length, round(length_b,6)))
else:
    print("calculation failed")

Bonus:You can use format() function easily try this:

length = float(input("please input the length: "))
unit = input("please input the unit: ")
if unit == "in" or unit == "inch":
    length_b = float(length / 2.54)
    print("inch is {} and cm is {}".format(length, length_b))
elif unit == "cm":
    length_b = float(length * 2.54)
    print("cm is {} and inch is {}".format(length, length_b))
else:
    print("calculation failed")

Output:

please input the length: 5                                                                                            
please input the unit: in                                                                                             
inch is 5.0 and cm is 1.968504 
Sheri
  • 1,383
  • 3
  • 10
  • 26
  • 2
    Better yet, `f'inch is {length} and cm is {length_b}'`. – chepner Apr 03 '20 at 15:23
  • 1
    You might not have noticed it yet, but `if unit == "in" or "inch":` will always be `True`. Read [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Matthias Apr 03 '20 at 15:28
  • @Gary8682 One mistake that you have made in your code is when you comparing your `unit ` variable as @Matthias mentioned here – Sheri Apr 03 '20 at 15:34