python issue can't load functions -


so i'm using mit computer science lectures learn python i'm having trouble advancing past functions lecture/assignment. wrote function designed find square root of x. sqrt(x) i'm using call in python 2.7 shell. copied down myself having issues copied function handout i'm still having same problem. in lecture created function find square roots. when run file in terminal doesn't return code. sends me next line nothing happened. , when sqrt(16) in python shell gives me error saying'sqrt' not defined'. here's video https://www.youtube.com/watch?v=sxr9cdof7qw&list=pl57fce46f714a03bc&index=4 part i'm referring starts @ 11:38. , here's function copied directly handout. it's indented same in video don't think that's problem.

def sqrt(x):   """returns square root of x, if x perfect square.        prints error message , returns none otherwise"""   ans = 0   if x >= 0:       while ans*ans < x: ans = ans + 1       if ans*ans != x:           print x, 'is not perfect square'           return none       else: return ans   else:         print x, 'is negative number'         return none def f(x):      x=x+1     return x 

edit: copy , pasted @jaredjenson 's code python shell , got error message https://imgur.com/4w5euvg when ran it. video posted above shows professor writing function in notepad , running in python shell typing sqrt(16). when error message

traceback (most recent call last):  file "<pyshell#23>", line 1, in <module>   sqrt(16)  nameerror: name 'sqrt' not defined 

i"m not sure it's going wrong. should outputting 4.

it sounds you're defining function in separate place you're executing it. there 3 options here.

  1. copy , paste entire sqrt function python shell, , run sqrt(16).

if this, shell should this:

def sqrt(x):   """returns square root of x, if x perfect square.        prints error message , returns none otherwise"""   ans = 0   if x >= 0:     while ans*ans < x: ans = ans + 1     if ans*ans != x:       print x, 'is not perfect square'       return none     else: return ans   else:     print x, 'is negative number'     return none  print sqrt(16) 

after copy , paste whole thing python 2.7 shell, should print out 4 @ end

  1. keep whole thing in file, , run file

all need here copy , paste above code file (let's call mysqrt.py) , run

python mysqrt.py 

on command line

  1. import file , run command shell

what you'll here same #2, except delete last line (print sqrt(16)) file.

then, save file, , make sure you're cd'd same directory file in.

start python interpreter

python 

import function

>>> mysqrt import sqrt 

then run it

>>> print(sqrt(16)) 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -