python issue can't load functions - python

So i'm using the mit computer science lectures to learn python but i'm having trouble advancing past the functions lecture/assignment. basically I wrote a function designed to find the square root of x. sqrt(x) is what i'm using to call it in the python 2.7 shell. Originally I copied it down myself but i was having issues so I copied the function from the handout but I'm still having the same problem. Basically in the lecture we created the function to find the square roots. when I run the file in terminal it doesn't return any code. just sends me to the next line like nothing happened. and when i do sqrt(16) in the python shell it gives me an error saying'sqrt' is not defined'.
here's the video https://www.youtube.com/watch?v=SXR9CDof7qw&list=PL57FCE46F714A03BC&index=4 the part I'm referring to starts at 11:38. and here's the function copied directly from the handout. it's all indented the same as in the video so I don't think that's a problem.
def sqrt(x):
"""Returns the square root of x, if x is a perfect square.
Prints an error message and returns None otherwise"""
ans = 0
if x >= 0:
while ans*ans < x: ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square'
return None
else: return ans
else:
print x, 'is a negative number'
return None
def f(x):
x=x+1
return x
edit: copy and pasted #JaredJenson 's code into the python shell and got this error message https://imgur.com/4W5EUVG when I ran it. the video I posted above shows the professor writing his function in notepad and then running it in the python shell by typing sqrt(16). When I do that I get an error message
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
sqrt(16)
NameError: name 'sqrt' is not defined
I"m not sure where it's going wrong. It should be outputting 4.

It sounds like you're defining the function in a separate place from where you're executing it. There are three options here.
Copy and paste the entire sqrt function into the python shell, and then run sqrt(16).
If you do this, your shell should look like this:
def sqrt(x):
"""Returns the square root of x, if x is a perfect square.
Prints an error message and returns None otherwise"""
ans = 0
if x >= 0:
while ans*ans < x: ans = ans + 1
if ans*ans != x:
print x, 'is not a perfect square'
return None
else: return ans
else:
print x, 'is a negative number'
return None
print sqrt(16)
After you copy and paste that whole thing into your python 2.7 shell, it should print out a 4 at the end
Keep the whole thing in a file, and run the file
All you need to do here is copy and paste the above code into a file (let's call it mysqrt.py) and then run
python mysqrt.py
on the command line
Import your file and run the command from the shell
What you'll do here is the same as #2, except you delete the last line (print sqrt(16)) from the file.
Then, save your file, and make sure you're cd'd into the same directory that the file is in.
Start up the python interpreter
python
import your function
>>> from mysqrt import sqrt
then run it
>>> print(sqrt(16))

Let's go over step by step how using the Python shell works, and see if we can figure out where you've gone wrong.
You open the shell, e.g. from the command line with python, or by using a shell window in IDLE or another IDE.
You see the >>> prompt, and you start typing the code for the function.
Each time you hit enter while inputting the function, you see a ... prompt at the beginning of the next line.
You let the shell know that you're done writing the function, by inputting a blank line (just hit enter again on an empty line).
The prompt goes back to >>>.
You attempt to call the function.
Edit, following your clarifying comment: it looks like what you're trying to do is save the code in a file, and then call the function defined there. Your screenshot does not show you using "the Python shell" (it shows you using the command line). Right now, your program file britney.py defines functions, but doesn't do anything with them.
There are a few ways you can test out the functions from here:
You can just have the file include a call to the function at top level, after it's defined.
You can start up the shell (from the same folder that your source file is in - use just python without a filename), and then import the module defined by your file (in the given example, you would import britney) and call the function from it (britney.sqrt(64)).
You can start up the shell, and then import the function directly (from britney import sqrt) and call it (sqrt(64)).
You can run the file with the -i command-line option (python -i britney.py), which lets you "inspect" the program state after it runs - you get a Python shell, so after that you can call sqrt yourself.

def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x: ans = ans + 1
if ans*ans != x:
print(x, 'is not a perfect square')
return None
else:
return ans
else:
print(x, 'is a negative number')
print(sqrt(4))
print(sqrt(5))
>>>
2
5 is not a perfect square
None
Looks works for me on Python3, please make sure your indent

Related

There is a problem when I use indentation in Python

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
This is a basic example for defining a function, and when I run this code on Python 3.8.5 by VSC, the result is like below.
>>> def greet(name):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
It says that there is an indentation error but I really don't know why. And also, line 2 is not just blank but according to the result, line 2 seems like blank.
for number in range(5):
print("Thank you")
>>> for number in range(5):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
Same error for 'for'. Can anyone help?
Right now, you are running the Python script line-by-line by placing the VS Code cursor on each line of code and then pressing shift+enter. This utilizes the Python Interactive window afaik. It works fine for running individual lines but if you want to run a collection of lines that include indentation e.g. a for loop or function definition, then select all of those lines together and then press shift+enter. You would need to do this for code that's indented, for example:
def greet(name):
print("Hello, " + name + ". Good morning!")
Alternatively, if you have read Getting Started with Python in VS Code and specifically installed the Python extension for VS Code then you will be able to click the Run Python File in Terminal button (it looks like a Play icon) to run your Python script.
Alternatively, you can launch a Terminal Window in VS Code and manually run the Python script using python3 hello.py (or potentially python hello.py, depending on your Python installation).
You should not press Shift+Enter to run the code in the terminal line by line.
Because the REPL will add an Enter to start a new line automatically like this:
You can select all of the codes then send them to the REPL:

Code runs fine on editor but has an EOF error in Code Wars

I'm new to programming and just joined Code Wars a day ago. So I had a Kata called "Alan Partridge II - Apple Turnover".
It basically told me to do this:
"Your job is simple, if (x) squared is more than 1000, return 'It's hotter than the sun!!', else, return
'Help yourself to a honeycomb Yorkie for the glovebox.'.
X will be a valid integer number.
X will be either a number or a string. Both are valid."
Here is the code that I wrote:
import math
def apple(x):
if math.sqrt(x)>=1000:
print("It's hotter than the sun!!")
else:
print("Help yourself to a honeycomb Yorkie for the glovebox.")
apple(x=int(input("gimme a temp\n")))
When I tried it on Pycharm, I'm pretty sure everything works. But when I tested it on Code Wars, this happened:
Log
gimme a temp
STDERR
Traceback (most recent call last):
File "tests.py", line 2, in <module>
from solution import apple
File "/workspace/default/solution.py", line 7, in <module>
apple(x=int(input('gimme a temp')))
EOFError: EOF when reading a line
Here is the screenshot of my test results:
Since I'm new, I'm not really sure what's going on.
Can anyone please help me to figure out what's wrong?
It looks like Code Wars imports the function to its own code and then runs it. The problem is that when importing a function, Python will run your whole file. It does probably not expect you to run the input() function. You can solve this by putting your own function call in an if __name__== "__main__": statement like this:
import math
def apple(x):
if math.sqrt(x)>=1000:
print("It's hotter than the sun!!")
else:
print("Help yourself to a honeycomb Yorkie for the glovebox.")
if __name__ == "__main__":
apple(x=int(input("gimme a temp\n")))
The if-statement basically checks if you are running the file itself, or importing it from another Python script. So when Code Wars tries to validate your function, it will import it and not execute your own function call.

How do I call a function in vs code using python?

I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.

My mac terminal can't run python functions

I've tried to run multiple python functions on mac terminal and they all return syntax error, for this program
def spam():
print "R"
spam()
it returned the error:
./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `def spam():'
this is really the simplest function I could find.
Just to be clear terminal is running the rest of the program but it can't handle functions.
#!/usr/bin/python
import math
number = int(raw_input("What's your surd?"))
print type(number)
#Just to let us know what the input is
if type(number) == int:
print "Number is an integer"
else:
print "Please enter a number"
value = math.sqrt(number)
#Takes the number and square roots it
new_value = int(value)
#Turns square root of number into an integer
if type(new_value) == int:
print "Surd can be simplified"
print new_value
else:
print "Surd cannot be simplified"
print value
This program runs fine even if it is a bit buggy at the moment but the following program returns the same error as the previous function.
# define a function
def print_factors(x):
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
num = int(input("What's your number? "))
print_factors(num)
Why terminal is returning a syntax error where there isn't one?
The problem here (at least for that first example) is that you're not using a python interpreter. The terminal is using a bash interpreter for your python code and getting very confused. Use a command like this to execute your code python spam.py . Or first enter the python command interpreter by running python, then entering your code in the command line interpreter.
What might be even easier while getting started is to get an IDE like PyCharm (https://www.jetbrains.com/pycharm/) and running through a couple of their tutorials to get the feel of it.
Your issue is that your shell doesn't know you are running a Python script. You need to make it clear that you should be using the Python interpreter. You can either do this by:
1) Call python test.py at your terminal.
2) Add #!/usr/bin/python at the top of your Python script (you may need to alter the path to the Python executable on your system). Make the script executable, and call ./test.py at your terminal.
The benefits of 2) are that you know what version of Python you will be running your script with (Python 2.x in your case?).
Method 1) will use whatever Python version is encountered first in your PATH, which may be Python 3 or Python 2, depending on whether you have installed Python 3 at some point. The code you have written will work with Python 2.7, but not Python 3.x. Of course you can always explicitly call python2.7 ./test.py.

How can I debug manually typed expression and statements in pdb?

In pdb (or ipdb) we can execute statements and evaluate expressions with the ! or p commands:
p expression
Evaluate the expression in the current context and print its value.
[!]statement
Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To set a global variable, you can prefix the assignment command with a global command on the same line
So, for example, I can type p reddit.get_subreddits() while debugging in ipdb and the code will be executed in the current context and I will see the return value.
Is there a way I can debug the execution of such "manually typed" expressions?
Basically I would like to do is s reddit.get_subreddits(), but that just executes the step command and ignores the expression.
EDIT: A trivial example
Take this simple function:
import random
def get_value_for_weekday(weekday_index=None):
values = [10, 20, 20, 10, 30, 30, 30]
if not weekday_index:
# If no weekday provided, return the average of all weekdays
return sum(values) / 7
return averages[weekday_index]
if __name__ == '__main__':
while True:
import ipdb; ipdb.set_trace() # enter ipbd for debug
get_value_for_weekday(random.randint(0, 7))
Which is bugged because of the if not weekday_index (it should check weekday_index is not None.)
Let's assume I notice I get 10 half the number of times I was expecting. So I added a import ipdb; ipdb.set_trace() before the call to the function to try and debug the code.
So I'm in the ipdb console and I suddenly get the idea that maybe the problem is when I pass 0 as weekday_index.
I can test my hypothesis directly in ipdb:
ipdb> p get_value_for_weekday(0)
22
Ok, so I realize there's something wrong when weekday_index=0.
What I would like to do now is debug step by step the call to get_value_for_weekday(0), so that I could see that I erranously enter the if block.
Obviously I could exit ipdb, stop the script, change the code to always pass 0, relaunch the script and when I enter ipdb, debug the call with the ipdb step (s) command.
But wouldn't it be easier if I could just do s get_value_for_weekday(0) much the same way I was able to do p get_value_for_weekday(0)?
Is there a way do something like this?
I think you're looking for the (d)ebug command which, for some reason, is not specified in the Debugger Commands. Just for future reference, pdb has a nice set of commands specified (which you can see by typing help in the interactive prompt). On to the debug command:
(Pdb) help debug
debug code
Enter a recursive debugger that steps through the code
argument (which is an arbitrary expression or statement to be
executed in the current environment).
Which seems to do what you're after. Using your sample script from the terminal:
python -m pdb pdbscript.py
After issuing two n commands in order for the function to get parsed (I believe this is how pdb works). You can issue a debug get_value_for_weekday(0) command to recursively step in the function:
(Pdb) debug get_value_for_weekday(0)
ENTERING RECURSIVE DEBUGGER
> <string>(1)<module>()
((Pdb)) s
--Call--
> /home/jim/Desktop/pdbscript.py(3)get_value_for_weekday()
-> def get_value_for_weekday(weekday_index=None):
((Pdb)) n
> /home/jim/Desktop/pdbscript.py(4)get_value_for_weekday()
-> values = [10, 20, 20, 10, 30, 30, 30]
((Pdb)) n
> /home/jim/Desktop/pdbscript.py(5)get_value_for_weekday()
-> if not weekday_index:
((Pdb)) p weekday_index
0
((Pdb)) n
> /home/jim/Desktop/pdbscript.py(7)get_value_for_weekday()
-> return sum(values) / 7
Do note, I feel really sketchy about this form of meta-debugging but it seems to be what you're after.
With regards to your example,
you don't need to exit pdb and change the code.
You can step into the function (with 's') and set weekday_index=0 inside.
One solution to your original problem is to use the debugger's jump command as follows:
jump before the function call using 'j #line-number'
step in the function with 's'
set the input params, and continue debugging.
This worked when I tried it, but the debugger complained when I tried to do step 3 before step 2 for some reason.

Categories