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.
Related
I'm wondering how I can utilize my code on IDLE to work within the macOS Terminal.
For example, I created a function such as:
def multiplication_by_2(x): return 2 * x
and saved the .py file in a desktop folder.
I want to use terminal to test out various cases such as multipication_by_2(100) etc, however I am unsure about which commands to enter in terminal to achieve this.
Any direction toward this would be helpful. Thank you.
Try this at the end of the code:
number = int(str(input("Enter the number you would like to multiply by 2: ")))
multiplication_by_2(number)
This way, you get user input. Then, in the terminal:
$ python3 <filename>.py
Which should produce the output:
Enter the number you would like to multiply: <your input, ex. 100>
200
Hope that solved it!
If you are asking how to send arguments to your program through the command line, python's sys library has a list named argv that holds arguments passed from the command line. Add this to your python file:
from sys import argv
for argument in argv:
print(multipication_by_2(int(argument))) # All arguments are strings by default
Then in the command line, do python file_name.py 20 50 1 and any other number you might want to try, and the program will print its double.
Note: If your command line says python doesn't exist, try python3.
While learning Python and browsing the internet I stumble upon a piece of code in w3schools.com. I tried to run it using their built-in site Python IDLE and using my own Python 3.9.0 Shell. What I got is two different outputs.
I want to know which output is the correct output and why is it providing two different outputs.
The Codes and Its Output
Built in site Python IDLE
Python 3.9.0 Shell
Notice that the number 21 is only printed(outputted) once when running the code using Built-in site Python IDLE, while it is printed(outputted) twice when running the code using Python 3.9.0 Shell.
My Own Debugging
I have tried a simple print statement debugging. Checking the result there is only one different, using Python 3.9.0 Shell the last return line is executed and it outputted the last result while using the Built-in site Python IDLE the last return is either not executed or not outputted, in this case, I believe it is the former, and I believe the correct output is the Python 3.9.0 Shell, but I have no idea why are there two different output.
Print Statement Using Python 3.9.0 Shell Result Part 1 Result Part 2
Print Statement Using Built-in site Python IDLE Result Part 1 Result Part 2
Source Code
def tri_recursion(k):
if(k>0):
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
tri_recursion(6)
You have added a return result statement at the end. For any IDE, unless you print that value, it wouldn't be displayed. However, IDLE prints the return value as well. Technically, both outputs are correct, since both interpreters are configured to do different actions. As a small example,
def foo():
return(1)
Running foo() on IDLE gives >>> 1, whereas it gives nothing on other IDE's, as there is no print statement
Both are correct.
The built-in python on the site is showing you the output of the execution of your program. This is equivalent to running the following program:
if __name__ == '__main__':
tri_recursion(6)
add this at the end of your code, save it as test.py and run it like this:
python test.py
the results will be the same
The python shell is showing you the output of the REPL (Read-Eval-Print-Loop), the print statement will print to the screen, but the return value of the function is also printed, because of the REPL, there's no way to avoid this, it is so by design.
You could design your function to not return anything, but it wouldn't be recursive anymore.
both are correct you need to understand that the python shell is printing statement's output.
when you write :
>>> tri_recursion(6)
it will execute first all the print inside function then it prints value that the last call returns.
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
I am trying to write a program to find the sum of a list using recursion in python and my code is this
value = 0
def sum_list(alist):
global value
if len(alist) == 0:
return value
value += alist.pop()
return sum_list(alist)
print sum_list(range(10))
But when i am executing this script I am getting a weired error.
Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/%{ <-- HERE (.*?)}/ at /usr/bin/print line 528.
Error: no "print" mailcap rules found for type "text/x-python"
I searched for it but couldn't get why this error is coming.
Help will be appreciated
Your code is valid Python 2. (It's not valid Python 3 because the print statement would have to be different.)
You don't say how you are actually running this code, but it looks like it is not actually being interpreted as a Python program. The error message is coming from /usr/bin/print, so I think you have managed to get this interpreted as a shell script somehow, and the "print" on your final line is running /usr/bin/print. That's obviously not what you want.
If you are executing this inside a source file, try putting the following line at the top of it, to tell the shell to run this as a Python program:
#!/usr/bin/env python
Alternatively, run it using
python myfile.py
I had this problem, it was an oversight at the terminal prompt. I was typing print instead of python
$ print sum.py
$ Error: no "print" mailcap rules found for type "text/x-python"
Correct way:
$ python sum.py
$ program runs successfully...
The error message comes from Perl. No idea how you managed to call it with this Python code.
see also http://www.perlmonks.org/?node_id=113525
I'm trying to execute a python program from Terminal but it isn't working.
Something like:
x = 5
Then typing:
UserName:Documents UserName$ python simple.py
Outputs:
UserName:Documents UserName$
Without actually executing/opening the file.
But if I have a program like:
x = input('Something: ')
Then it shows up in terminal, such as:
UserName:Documents UserName$ python simple.py
Something:
Probably a silly question, but been trying to fix it for the last 1.5 hours and can't find a workable solution.
The short program
x = 5
gets run and then Python exits back to the command line. No problem there, it all works correctly. If you want to stay inside the interpreter, start your program with
python -i simple.py
When running that, you will get the usual interpreter prompt after it is finished:
>>>
and you can see it did run, because x got the expected value:
>>> x
5
>>> x*x*x*x/(x+x+x-x/x)-x/x-x/x
42
Also, from inside the interpreter, you can load-and-run your file again:
>>> execfile('simple.py')
>>> x
5
See Bojan Nikolic's Running Python Programs from the Command-line for a number of other startup options.
It looks like it is working exactly as written... but maybe not as intended... The input prompt asks you to enter a value...
maybe you want to add a print so that you get a feedback that your program does something:
x = input('Something: ')
print(x)
if you are using python 2.x:
x = raw_input('Something: ')
print x
Then, on the prompt, input a value and press enter