Python – Execution of Code

By | January 13, 2017

One of the first things you need to do when you learn python is how to run the python code you wrote. The most important thing when you learn a language is to try it yourself and see the results with your eyes.

There are several ways to execute code written in python.

1. Running directly from the python interpreter
2. Create a .py file and run it as a python argument
3. Run the .py file directly

Let’s look at each one.

1. Running directly from the python interpreter

This is the most basic code execution method.

1
2
3
4
5
python@Test:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

You can see the python console by executing “python” command.
Enter the python code directly in the console to see the results in real time.

1
2
>>> print "Hello, world"
Hello, world

This is useful when you need to trace each code you want to check.

2. Create a .py file and run it as a python argument

There is one problem with method 1.

Because method 1 do not save the code you have entered, you have to re-write code again whenever you want to execute.

So there is another method to execute with saved file.

You can create a .py (python code file) and run it.

[Create .py file]

In the above, I put the code “Hello, world” in the hello.py file.

The saved file can be executed as follows.

1
2
python@Test:~$ python hello.py
Hello, world

 

3. Run the .py file directly

To make it more usable, you can execute “hello.py” directly instead of “python hello.py”.

First, in general, if you just created a hello.py file, you do not have permission to execute, and a “Permission denied” error is generated.

“chmod 755” give execution permission on hello.py and run ./hello.py, but it will not work.
This is because the bash shell does not know what print “Hello, world” means.

Therefore, you should write down the information about the program that will run this file first in the file.

1
#!/usr/bin/python

After putting information about the program that will execute the file, run ./hello.py and it will run normally.

1
2
python@Test:~$ ./hello.py
Hello, world

 

One thought on “Python – Execution of Code

Leave a Reply

Your email address will not be published. Required fields are marked *