# If Statements¶

Simple If Statement

In [1]:
x=3
if x>0:
print x

3


Else If Statement

In [2]:
x = 3
if x > 0:
print "{} is a positive number".format(x)
elif x < 0:
print "{} is a negative number".format(x)
else:
print "x equals 0"

3 is a positive number


## Exercise: Update your function to handle errors and convert Fahrenheit to Celsius¶

#### 1. Create a function that checks the type of an input and returns True if the input is numeric (float or integer) or a False if it is another data type.¶

In [3]:
def check_type(x):
if type(x) == int or type(x) == float:
return True
else:
return False

In [13]:
# Short hand version of solution
def check_type(x):
return (type(x) == int) | (type(x) == float)

In [11]:
# Alternative solution using the in command
def check_type(x):
return type(x) in [int,float,bool]

In [14]:
print check_type(10)
print check_type(10.1)
print check_type(True)
print check_type('Test')

True
True
False
False


#### 2. Update your temperature function from the Python Fundamentals exercise to return an error message if a string is entered instead of a number.¶

In [15]:
def convert_temp_check(degrees_c):
if (type(degrees_c) == int) | (type(degrees_c) == float):
degrees_f = degrees_c * 9.0 / 5.0 + 32.0
return degrees_f
else:
return "Error. {} is a non-numeric value.".format(degrees_c)

In [16]:
print convert_temp_check(100)
print convert_temp_check('Test')

212.0
Error. Test is a non-numeric value.

In [9]:
# Use checkType function we've already created
def convert_temp_check2(degrees_c):
if check_type(degrees_c):
degrees_f = degrees_c * 9.0 / 5.0 + 32.0
return degrees_f
else:
return "Error. {} is a non-numeric value.".format(degrees_c)

print convert_temp_check2(100)
print convert_temp_check2('Test')

212.0
Error. Test is a non-numeric value.

In [17]:
# Use convertTemp and checkType functions we've already created
def convert_temp(degrees_c):
degrees_f = degrees_c * 9.0 / 5.0 + 32.0
return degrees_f

def convert_temp_check3(degrees_c):
if check_type(degrees_c):
return convert_temp(degrees_c)
else:
return "Error. {} is a non-numeric value.".format(degrees_c)

print convert_temp_check3(100)
print convert_temp_check3('Test')

212.0
Error. Test is a non-numeric value.

In [ ]: