Be very careful with indentation, as Python code depends very strong on it.
The print() function doesn't return a result. It just prints out what you ask it.
Also, be careful with executing the line bmi=(height/weight**2)
before you checked the validity of height and weight. Best wait until you checked them. Otherwise, Python would write out a cryptic error about these types.
A function is not executed when you define it. You should add a call to the function bmi() you defined, as in:
import sys
def bmi (height,weight):
return height/weight**2
#if the script has been given 2 arguments, he continues, if not(=else) he print a message
if len(sys.argv) == 3:
#The first argument should be the height and the second one should be the weight
height=float(sys.argv[1]) # argv[1] is a string and should be converted to float
weight=int(sys.argv[2]) # argv[2] is a string and should be converted to int
if type(height) is float and type(weight) is int:
print("your bmi is {}".format(bmi(height,weight)))
# "bmi()" calls the bmi function
else:
print(" height should be a float and weight an int")
else:
print("you should enter 2 arguments")
Although Python allows to define functions anywhere in your code, it is best to separate such functions. isinstance()
is normally preferred to type() ==
because isinstance()
also checks for subclasses.
edit: added conversions from string to int/float as indicated by Patrick Artner
PS: Check out Checking if a string can be converted to float in Python for information about better checking whetter a string is a valid float.
This would mean following adaption to the code:
try:
height=float(sys.argv[1]) # argv[1] is a string and should be converted to float
weight=int(sys.argv[2]) # argv[2] is a string and should be converted to int
except ValueError:
print(" height should be a float and weight an int")