Reputation: 17
Hello i am trying to make a converting program but i can't get it to work, I am going to convert multiply different things but i start with CM to INCH. I get error TypeError: unsupported operand type(s) for /: 'str' and 'float'. Here is some of the code:
print('Press the number of the one you want to convert: ')
number = input()
inch = float(2.54)
if number == '1':
print('How many inch? ')
print('There are %s'.format(number / inch))
Here is the whole code:
print('Welcome to the converting program')
print('What of these do you want to convert?')
print( "\nHow many centimeters in inches? 1"
"\nHow many milliliters in a pint? 2"
"\nHow many acres in a square-mile? 3"
"\nHow many pounds in a metric ton? 4"
"\nHow many calories in a BTU? 5")
print('Press the number of the one you want to convert: ')
number = float(input())
inch = float(2.54)
if number == '1':
print('How many inch? ')
print('There are {0}'.format(number / inch))
elif number == '2':
print('millimeters')
elif number == '3':
print('acres')
elif number == '4':
print('pounds')
elif number == '5':
print('calories')
Upvotes: 1
Views: 2219
Reputation: 766
%s is the notation for formatting a string, %f should be used for floats. In newer versions of python however you should use {0}
print('There are {0}'.format(number / inch))
Read PEP 3101 for more information on this.
Further to this, as Sebastian Hietsch mentioned in his answer, your input variable is a string that will need to be converted to a float first. Do this before your formatting expression.
number = float(input())
inch = float(2.54)
You may want to add some error handling:
try:
number = float(input())
except TypeError as e:
print('input must be a float')
inch = float(2.54)
Of course, you will need to remove the quotes from the '1' in the if statement.
Upvotes: 1
Reputation: 474
The problem is that number
is a string and you can't perform mathematical operations on it. What you'll need to do is convert it to an integer or a float using int(number)
or float(number)
.
So you could do: print("There are ℅f".format(float(number)/inch))
Upvotes: 0