miércoles, 8 de febrero de 2017

Functions (Quiz3)

Functions 

For today´s class we had Quiz 3, which consisted on creating two functions to get the square and cubic roots of any number. This was pretty simple:

First as always, you have to open your editor and save your work as "Quiz3.py".

For this exercise we need to use the math library by using the "import math" function before starting our code.

Now, you have to generate your function, this is pretty simple and I found some help on how to do it in the How to think like a computer scientist interactive book (I´ll leave a link at the end of this post).

  • First you must define the function just like this: def square_root (x): 
  • Then you have to ask your computer to return the value or result of that function:return math.sqrt(x) (FOR THE CUBIC ROOT FUNCTION YOU HAVE TO USE THE "MATH.POW")
After defining your functions, you need to make an input into your code so you can type the number you want to use. x= float(input("Type a number:"))

For this final step you just have to give a variable to the functions r= square_root (x)  so you can ask the code to print the results. print ("The square root of",x, "is", r).

Here´s the complete code:
import math

def square_root (x):
    return math.sqrt(x)
def cubic_root (x):
    return math.pow(x,(1/3))


x= float(input("Type a number:"))
r= square_root (x)
c= cubic_root (x)

print ("The square root of",x, "is", r)
print ("The cubic root of",x, "is", c )

The link to the book: http://interactivepython.org/runestone/static/thinkcspy/GeneralIntro/toctree.html

No hay comentarios:

Publicar un comentario