Search

Series List Filter

How To Run Your Python Scripts

If you are planning to enter the world of Python programming, the first and the most essential skill you should learn is knowing how to run Python scripts and code. Once you grab a seat in the show, it will be easier for you to understand whether the code will actually work or not.Python, being one of the leading programming languages, has relatively easy syntax which makes it even easier for the ones who are in their initial stage of learning the language. Also, it is the language of choice for working with large datasets and data science projects. Get certified and learn more about Python Programming and apply those skills and knowledge in the real world.What is the difference between Code, Script and Modules?In computing, the code is a language that is converted from a human language into a set of ‘words’ which the computer can understand. It is also referred to as a piece of statements together which forms a program. A simple function or a statement can also be considered a code.On the other hand, a script is a file consisting of a logical sequence of instructions or a batch processing file that is interpreted by another program instead of the computer processor.In simple terms, a script is a simple program, stored in a plain file text which contains Python code. The code can be directly executed by the user. A script is also called a top-level-program-file. A module is an object in Python with random attributes that you can bind and reference.Is Python a Programming Language or a Scripting Language?Basically, all scripting languages are considered to be programming languages. The main difference between the two is that programming languages are compiled, whereas scripting languages are interpreted. Scripting languages are slower than programming languages and usually sit behind them. Since they only run on a subset of the programming language, they have less access to a computer’s local abilities. Python can be called a scripting language as well as a programming language since it works both as a compiler and an interpreter. A standard Python can compile Python code into bytecodes and then interpret it just like Java and C.However, considering the historical relationship between the general purpose programming language and the scripting language, it will be more appropriate to say that Python is a general-purpose programming language which works nicely as a scripting language too.The Python InterpreterThe Interpreter is a layer of software that works as a bridge between the program and the system hardware to keep the code running. A Python interpreter is an application which is responsible for running Python scripts.The Python Interpreter works on the Read-Eval-Print-Loop (REPL) environment.Reads the command.Evaluates the command.Prints the result.Loops back and process gets repeated.The interpreter terminates when we use the exit() or quit() command otherwise the execution keeps on going.A Python Interpreter runs code in two ways— In the form of a script or module.In the form of a piece of code written in an interactive session.Starting the Python InterpreterThe simplest way to start the interpreter is to open the terminal and then use the interpreter from the command-line.To open the command-line interpreter:On Windows, the command-line is called the command prompt or MS-DOS console. A quicker way to access it is to go to Start menu → Run and type cmd.On GNU/Linux, the command-line can be accessed by several applications like xterm, Gnome Terminal or Konsole.On MAC OS X, the system terminal is accessed through Applications → Utilities → Terminal. Running Python Code InteractivelyRunning Python code through an interactive session is an extensively used way. An interactive session is an excellent development tool to venture with the language and allows you to test every piece of Python code on the go.To initiate a Python interactive session, type python in the command-line or terminal and hit the ENTER key from the keyboard.An example of how to do this on Windows:C:\users>python Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>>The >>> on the terminal represents the standard prompt for the interactive mode. If you do not see these characters, you need to re-install Python on your system.The statements you write when working with an interactive session are evaluated and executed immediately:print('HELLO WORLD!') HELLO WORLD! 2 + 3 5 print('Welcome to the world of PYTHON') Welcome to the world of PYTHON The only disadvantage is when you close the interactive session, the code no longer exists.Running Python Scripts by the InterpreterThe term Python Execution Model is given to the entire multi-step process to run Python scripts.At first, the statements or expressions of your script are processed in a sequential manner by the interpreter. Then the code is compiled into a form of instruction set called the bytecode.Basically, the code is converted into a low-level language known as the bytecode. It is an intermediate, machine-independent code which optimizes the process of code execution. So, the interpreter ignores the compilation step when executing the code for the next time.Finally, the interpreter transfers the code for execution.The Python Virtual Machine (PVM) is the ultimate step of the Python interpreter process. It is a part of the Python environment installed in your system. The PVM loads the bytecode in the Python runtime and reads each operation and executes them as indicated. It is the component which actually runs your scripts.Running Python Scripts using Command-LineThe most sought after way of writing a Python program is by using a plain text editor. The code written in the Python interactive session is lost once the session is closed, though it allows the user to write a lot of lines of code. On Windows, the files use the .py extension.  If you are at the beginning of working with Python, you can use editors like Sublime or Notepad++ which are easy-to-use or any other text editors.Now you need to create a test script. In order to do that, open your most suited text editor and write the following code:print('Hello World!')Then save the file in your desktop with the name first_script.py or anything you like. Remember you need to give the .py extension only.Using python commandThe most basic and the easy way to run Python scripts is by using the python command. You need to open a command-line and type the word python followed by the path to your script file, like this:python first_script.py Hello World!Then you hit the ENTER button from the keyboard and that's it. You can see the phrase Hello World! on the screen. Congrats! You just ran your first Python script. However, if you do not get the output, you might want to check your system PATH and the place where you saved your file. If it still doesn’t work, re-install Python in your system and try again.Redirecting outputWindows and Unix-like systems have a process called stream redirection. You can redirect the output of your stream to some other file format instead of the standard system output. It is useful to save the output in a different file for later analysis.An example of how you can do this:python first_script.py > output.txtWhat happens is your Python script is redirected to the output.txt file. If the file doesn’t exist, it is systematically created. However, if it already exists, the contents are replaced.Running modules with the -m optionA module is a file which contains the Python code. It allows you to arrange your Python code in a logical manner. It defines functions, classes, and variables and can also include runnable code.If you want to run a Python module, there are a lot of command-line options which Python offers according to the needs of the user. One of which is the command  python -m <module-name>. It searches the module name in the sys.path and runs the content as __main__:python -m first_script Hello World!Note that the module-name is a module object and not any string.Using Script FilenameWindows makes use of the system registers and file association to run Python scripts. It determines the program needed to run that particular file. You need to simply enter the file-name containing the code.An example on how to do this using command prompt:C:\Users\Local\Python\Python37> first_script.py Hello World!On GNU/Linux systems, you need to add a line before the text— #!/usr/bin/env python. Python considers this line nothing but the operating system considers it everything. It helps the system to decide what program should it use to run the file.The character combination #! known as hashbang or shebang is what the line starts with, which is then followed by the interpreter path.Finally, to run scripts, assign execution permissions and configure the hashbang line and then simply type the filename in the command line:#Assign the execution permissions chmod +x first_script.py #Run script using its filename ./first_script.py Hello World!However, if it doesn’t work, you might want to check if the script is located in your currentworking directory or not. Otherwise, you can use the path of the file for this method. Running Python Scripts InteractivelyAs we have discussed earlier, running Python scripts in an interactive session is the most common way of writing scripts and also offers a wide range of possibilities.Using importImporting a module means loading its contents so that it can be later accessed and used. It is the most usual way of invoking the import machinery. It is analogous to #include in C or C++. Using import, the Python code in one module gets access to the code in another module. An implementation of the import:import first_script Hello World!You can see its execution only when the module contains calls to functions, methods or other statements which generate visible output.One important thing to note is that the import option works only once per session. This is because these operations are expensive.For this method to work efficiently, you should keep the file containing the Python code in your current working directory and also the file should be in the Python Module Search Path (PMSP). The PMSP is the place where the modules and packages are imported.You can run the code below to know what’s in your current PSMP:import sys for path in sys.path: print(path)\Users\Local\Python37\Lib\idlelib \Users\Local\Python37\python37.zip \Users\Local\Python37\DLLs \Users\Local\Python37\lib \Users\Local\Python37 \Users\Local\Python37\lib\site-packagesYou’ll get the list of directories and .zip files where your modules and packages are imported.Using importlibimportlib is a module which is an implementation of the import statement in the Python code. It contains the import_module whose work is to execute any module or script by imitating the import operation.An example to perform this:import importlib importlib.import_module('first_script') Hello World! <module 'first_script' from '\Users\Local\Python37\first_script.py'>importlib.reload() is used to re-import the module since you cannot use import to run it for the second time. Even if you use import after the first time, it will do nothing. importlib.reload() is useful when you want to modify and test your changes without exiting the current session.The following code shows that:import first_script #First import Hello World! import first_script import importlib #Second import does nothing importlib.reload(first_script) Hello World! <module 'first_script' from '\Users\Local\Python37\\first_script.py'>However, you can only use a module object and not any string as the argument of reload(). If you use a string as an argument, it will show a TypeError as follows:importlib.reload(first_script)Traceback (most recent call last): ... ...   raise TypeError("reload() argument must be a module") TypeError: reload() argument must be a moduleUsing runpy.run_module() and runpy.run_path()The Python Standard Library has a module named runpy. run_module() is a function in runpy whose work is to execute modules without importing them in the first place. The module is located using import and then executed. The first argument of the run_module() must contain a string:import runpy runpy.run_module(mod_name='first_script') Hello World! {'__name__': 'first_script',     ... '_': None}}Similarly, runpy contains another function run_path() which allows you to run a module by providing a location.An example of such is as follows:import runpy runpy.run_path(file_path='first_script.py') Hello World! {'__name__': '<run_path>',     ... '_': None}}Both the functions return the globals dictionary of the executed module.Using exec()Other than the most commonly used ways to run Python scripts, there are other alternative ways. One such way is by using the built-in function exec(). It is used for the dynamic execution of Python code, be it a string or an object code.An example of exec() is:exec(open('first_script.py').read()) Hello World!Using py_compilepy_compile is a module which behaves like the import statement. It generates two functions— one to generate the bytecode from the source file and another when the source file is invoked as a script.You can compile your Python script using this module:import py_compile py_compile.compile('first_script.py'  '__pycache__\\first_script.cpython-37.pyc' The py_compile generates a new subdirectory named "__pycache__" if it doesn’t already exist. Inside the subdirectory, a Compiled Python File (.pyc) version of the script file is created. When you open the .pyc file, you can see the output of your Python script.Running Python Scripts using an IDE or a Text EditorAn Integrated Development Environment (IDE) is an application that allows a developer to build software within an integrated environment in addition to the required tools.You can use the Python IDLE, a default IDE of the standard Python Distribution to write, debug, modify, and run your modules and scripts. You can use other IDEs like Spyder, PyCharm, Eclipse, and Jupyter Notebook which also allow you to run your scripts inside its environment.You can also use popular text editors like Sublime and Atom to run Python scripts.If you want to run a Python script from your IDE or text editor, you need to create a project first. Once it is created, add your .py file to it or you can just simply create one using the IDE. Finally, run it and you can see the output in your screen.Running Python Scripts from a File ManagerIf you want to run your Python script in a file manager, all you need to do is just double-click on the file icon. This option is mainly used in the production stage after you have released the source code.However, to achieve this, some conditions must be met:On Windows, to run your script by double-clicking on them, you need to save your script file with extension .py for python.exe and .pyw for pythonw.exe.If you are using the command-line for running your script, you might likely come  through a situation where you’ll see a flash of a black window on the screen. To avert this, include a statement at the tail of the script — input(‘Enter’). This will exit the program only when you hit the ENTER key. Note that the input() function will work only if your code is free of errors.On GNU/Linux and other Unix-like systems, your Python script must contain the hashbang line and execution permissions. Otherwise, the double-click trick won’t work in a file manager.Though it is easy to execute a script by just double-clicking on the file, it isn’t considered a feasible option because of the limitations and dependency factors it comes with, like the operating system, the file manager, execution permissions, and also the file associations.So it is suggested to use this option only after the code is debugged and ready to be in the production market.ConclusionWorking with scripts has its own advantages like they are easy to learn and use, faster edit and run, interactivity, functionality and so on. They are also used to automate complex tasks in a simplified manner.In this article, you have learned to run your Python scripts using:The terminal or the command-line of the operating system.The Python Interactive session.Your favorite IDE or text editor.The system file manager.Here, you have gathered the knowledge and skills of how to run your scripts using various techniques.You will feel more comfortable working with larger and more complex Python environments which in turn will enhance the development process and increase efficiency. You can learn more about such techniques as KnowledgeHut offers Python Certification Course.
Rated 4.5/5 based on 19 customer reviews

How To Run Your Python Scripts

5912
How To Run Your Python Scripts

If you are planning to enter the world of Python programming, the first and the most essential skill you should learn is knowing how to run Python scripts and code. Once you grab a seat in the show, it will be easier for you to understand whether the code will actually work or not.

Python, being one of the leading programming languages, has relatively easy syntax which makes it even easier for the ones who are in their initial stage of learning the language. Also, it is the language of choice for working with large datasets and data science projects. Get certified and learn more about Python Programming and apply those skills and knowledge in the real world.

What is the difference between Code, Script and Modules?

In computing, the code is a language that is converted from a human language into a set of ‘words’ which the computer can understand. It is also referred to as a piece of statements together which forms a program. A simple function or a statement can also be considered a code.

On the other hand, a script is a file consisting of a logical sequence of instructions or a batch processing file that is interpreted by another program instead of the computer processor.

In simple terms, a script is a simple program, stored in a plain file text which contains Python code. The code can be directly executed by the user. A script is also called a top-level-program-file. 

A module is an object in Python with random attributes that you can bind and reference.

Is Python a Programming Language or a Scripting Language?

Basically, all scripting languages are considered to be programming languages. The main difference between the two is that programming languages are compiled, whereas scripting languages are interpreted

Scripting languages are slower than programming languages and usually sit behind them. Since they only run on a subset of the programming language, they have less access to a computer’s local abilities. 

Python can be called a scripting language as well as a programming language since it works both as a compiler and an interpreter. A standard Python can compile Python code into bytecodes and then interpret it just like Java and C.

However, considering the historical relationship between the general purpose programming language and the scripting language, it will be more appropriate to say that Python is a general-purpose programming language which works nicely as a scripting language too.

The Python Interpreter

The Interpreter is a layer of software that works as a bridge between the program and the system hardware to keep the code running. A Python interpreter is an application which is responsible for running Python scripts.

The Python Interpreter works on the Read-Eval-Print-Loop (REPL) environment.

  • Reads the command.
  • Evaluates the command.
  • Prints the result.
  • Loops back and process gets repeated.

The interpreter terminates when we use the exit() or quit() command otherwise the execution keeps on going.

A Python Interpreter runs code in two ways— 

  • In the form of a script or module.
  • In the form of a piece of code written in an interactive session.

Starting the Python Interpreter

The simplest way to start the interpreter is to open the terminal and then use the interpreter from the command-line.

To open the command-line interpreter:

  • On Windows, the command-line is called the command prompt or MS-DOS console. A quicker way to access it is to go to Start menu  Run and type cmd.
  • On GNU/Linux, the command-line can be accessed by several applications like xterm, Gnome Terminal or Konsole.
  • On MAC OS X, the system terminal is accessed through Applications → Utilities → Terminal

Running Python Code Interactively

Running Python code through an interactive session is an extensively used way. An interactive session is an excellent development tool to venture with the language and allows you to test every piece of Python code on the go.

To initiate a Python interactive session, type python in the command-line or terminal and hit the ENTER key from the keyboard.

An example of how to do this on Windows:

C:\users>python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>

The >>> on the terminal represents the standard prompt for the interactive mode. If you do not see these characters, you need to re-install Python on your system.

The statements you write when working with an interactive session are evaluated and executed immediately:

print('HELLO WORLD!')
HELLO WORLD!
2 + 3
5
print('Welcome to the world of PYTHON')
Welcome to the world of PYTHON 

The only disadvantage is when you close the interactive session, the code no longer exists.

Running Python Scripts by the Interpreter

The term Python Execution Model is given to the entire multi-step process to run Python scripts.

  1. At first, the statements or expressions of your script are processed in a sequential manner by the interpreter. 
  2. Then the code is compiled into a form of instruction set called the bytecode.
    Basically, the code is converted into a low-level language known as the bytecode. It is an intermediate, machine-independent code which optimizes the process of code execution. So, the interpreter ignores the compilation step when executing the code for the next time.
  3. Finally, the interpreter transfers the code for execution.
    The Python Virtual Machine (PVM) is the ultimate step of the Python interpreter process. It is a part of the Python environment installed in your system. The PVM loads the bytecode in the Python runtime and reads each operation and executes them as indicated. It is the component which actually runs your scripts.

Running Python Scripts using Command-Line

The most sought after way of writing a Python program is by using a plain text editor. The code written in the Python interactive session is lost once the session is closed, though it allows the user to write a lot of lines of code. On Windows, the files use the .py extension.  

If you are at the beginning of working with Python, you can use editors like Sublime or Notepad++ which are easy-to-use or any other text editors.

Now you need to create a test script. In order to do that, open your most suited text editor and write the following code:

print('Hello World!')

Then save the file in your desktop with the name first_script.py or anything you like. Remember you need to give the .py extension only.

Using python command

The most basic and the easy way to run Python scripts is by using the python command. You need to open a command-line and type the word python followed by the path to your script file, like this:

python first_script.py
Hello World!

Then you hit the ENTER button from the keyboard and that's it. You can see the phrase Hello World! on the screen. Congrats! You just ran your first Python script. 

However, if you do not get the output, you might want to check your system PATH and the place where you saved your file. If it still doesn’t work, re-install Python in your system and try again.

Redirecting output

Windows and Unix-like systems have a process called stream redirection. You can redirect the output of your stream to some other file format instead of the standard system output. It is useful to save the output in a different file for later analysis.

An example of how you can do this:

python first_script.py > output.txt

What happens is your Python script is redirected to the output.txt file. If the file doesn’t exist, it is systematically created. However, if it already exists, the contents are replaced.

Running modules with the -m option

A module is a file which contains the Python code. It allows you to arrange your Python code in a logical manner. It defines functions, classes, and variables and can also include runnable code.

If you want to run a Python module, there are a lot of command-line options which Python offers according to the needs of the user. One of which is the command 

 python -m <module-name>. 

It searches the module name in the sys.path and runs the content as

 __main__:
python -m first_script
Hello World!

Note that the module-name is a module object and not any string.

Using Script Filename

Windows makes use of the system registers and file association to run Python scripts. It determines the program needed to run that particular file. You need to simply enter the file-name containing the code.

An example on how to do this using command prompt:

C:\Users\Local\Python\Python37> first_script.py
Hello World!

On GNU/Linux systems, you need to add a line before the text— #!/usr/bin/env python. Python considers this line nothing but the operating system considers it everything. It helps the system to decide what program should it use to run the file.

The character combination #! known as hashbang or shebang is what the line starts with, which is then followed by the interpreter path.

Finally, to run scripts, assign execution permissions and configure the hashbang line and then simply type the filename in the command line:

#Assign the execution permissions
chmod +x first_script.py
#Run script using its filename
./first_script.py
Hello World!

However, if it doesn’t work, you might want to check if the script is located in your current

working directory or not. Otherwise, you can use the path of the file for this method. 

Running Python Scripts Interactively

As we have discussed earlier, running Python scripts in an interactive session is the most common way of writing scripts and also offers a wide range of possibilities.

Using import

Importing a module means loading its contents so that it can be later accessed and used. It is the most usual way of invoking the import machinery. It is analogous to #include in C or C++. Using import, the Python code in one module gets access to the code in another module. 

An implementation of the import:

import first_script
Hello World!

You can see its execution only when the module contains calls to functions, methods or other statements which generate visible output.

One important thing to note is that the import option works only once per session. This is because these operations are expensive.

For this method to work efficiently, you should keep the file containing the Python code in your current working directory and also the file should be in the Python Module Search Path (PMSP). The PMSP is the place where the modules and packages are imported.

You can run the code below to know what’s in your current PSMP:

import sys
for path in sys.path:
print(path)
\Users\Local\Python37\Lib\idlelib
\Users\Local\Python37\python37.zip
\Users\Local\Python37\DLLs
\Users\Local\Python37\lib
\Users\Local\Python37
\Users\Local\Python37\lib\site-packages

You’ll get the list of directories and .zip files where your modules and packages are imported.

Using importlib

importlib is a module which is an implementation of the import statement in the Python code. It contains the import_module whose work is to execute any module or script by imitating the import operation.

An example to perform this:

import importlib
importlib.import_module('first_script')
Hello World!
<module 'first_script' from '\Users\Local\Python37\first_script.py'>

importlib.reload() is used to re-import the module since you cannot use import to run it for the second time. Even if you use import after the first time, it will do nothing. importlib.reload() is useful when you want to modify and test your changes without exiting the current session.

The following code shows that:

import first_script #First import
Hello World!
import first_script
import importlib #Second import does nothing
importlib.reload(first_script)
Hello World!
<module 'first_script' from '\Users\Local\Python37\\first_script.py'>

However, you can only use a module object and not any string as the argument of reload(). If you use a string as an argument, it will show a TypeError as follows:

importlib.reload(first_script)
Traceback (most recent call last):
...
...
  raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module

Using runpy.run_module() and runpy.run_path()

The Python Standard Library has a module named runpy. run_module() is a function in runpy whose work is to execute modules without importing them in the first place. 

The module is located using import and then executed. The first argument of the run_module() must contain a string:

import runpy
runpy.run_module(mod_name='first_script')
Hello World!
{'__name__': 'first_script',
    ...
'_': None}}

Similarly, runpy contains another function run_path() which allows you to run a module by providing a location.

An example of such is as follows:

import runpy
runpy.run_path(file_path='first_script.py')
Hello World!
{'__name__': '<run_path>',
    ...
'_': None}}

Both the functions return the globals dictionary of the executed module.

Using exec()

Other than the most commonly used ways to run Python scripts, there are other alternative ways. One such way is by using the built-in function exec(). It is used for the dynamic execution of Python code, be it a string or an object code.

An example of exec() is:

exec(open('first_script.py').read())
Hello World!

Using py_compile

py_compile is a module which behaves like the import statement. It generates two functions— one to generate the bytecode from the source file and another when the source file is invoked as a script.

You can compile your Python script using this module:

import py_compile
py_compile.compile('first_script.py' 
'__pycache__\\first_script.cpython-37.pyc' 

The py_compile generates a new subdirectory named "__pycache__" if it doesn’t already exist. Inside the subdirectory, a Compiled Python File (.pyc) version of the script file is created. When you open the .pyc file, you can see the output of your Python script.

Running Python Scripts using an IDE or a Text Editor

An Integrated Development Environment (IDE) is an application that allows a developer to build software within an integrated environment in addition to the required tools.

You can use the Python IDLE, a default IDE of the standard Python Distribution to write, debug, modify, and run your modules and scripts. You can use other IDEs like Spyder, PyCharm, Eclipse, and Jupyter Notebook which also allow you to run your scripts inside its environment.

You can also use popular text editors like Sublime and Atom to run Python scripts.

If you want to run a Python script from your IDE or text editor, you need to create a project first. Once it is created, add your .py file to it or you can just simply create one using the IDE. Finally, run it and you can see the output in your screen.

Running Python Scripts from a File Manager

If you want to run your Python script in a file manager, all you need to do is just double-click on the file icon. This option is mainly used in the production stage after you have released the source code.

However, to achieve this, some conditions must be met:

  • On Windows, to run your script by double-clicking on them, you need to save your script file with extension .py for python.exe and .pyw for pythonw.exe.

If you are using the command-line for running your script, you might likely come  through a situation where you’ll see a flash of a black window on the screen. To avert this, include a statement at the tail of the script — input(‘Enter’). This will exit the program only when you hit the ENTER key. Note that the input() function will work only if your code is free of errors.

  • On GNU/Linux and other Unix-like systems, your Python script must contain the hashbang line and execution permissions. Otherwise, the double-click trick won’t work in a file manager.

Though it is easy to execute a script by just double-clicking on the file, it isn’t considered a feasible option because of the limitations and dependency factors it comes with, like the operating system, the file manager, execution permissions, and also the file associations.

So it is suggested to use this option only after the code is debugged and ready to be in the production market.

Conclusion

Working with scripts has its own advantages like they are easy to learn and use, faster edit and run, interactivity, functionality and so on. They are also used to automate complex tasks in a simplified manner.

In this article, you have learned to run your Python scripts using:

  • The terminal or the command-line of the operating system.
  • The Python Interactive session.
  • Your favorite IDE or text editor.
  • The system file manager.

Here, you have gathered the knowledge and skills of how to run your scripts using various techniques.You will feel more comfortable working with larger and more complex Python environments which in turn will enhance the development process and increase efficiency. You can learn more about such techniques as KnowledgeHut offers Python Certification Course.

Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

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

Suggested Blogs

What is Python, it's basics and getting started with Python

Learning something new is always interesting and exciting but how to learn makes it challenging. It is believed that learning how to learn is the most critical task while learning a new programming language. A proper strategy to learn makes the journey easier and smooth. Let us look into such essential learning strategies which will help you learn the basics of Python and guide you through the journey of becoming a programmer.Code Regularly: It is important for a beginner to practice Python coding on a regular basis which will develop a muscle memory. At first it might seem to be difficult but a regular practice of half an hour will make your basics stronger.Use Pen and Paper: Many learners have this question in mind, whether they should write codes using a pen and paper or not. It is recommended to write codes or take notes by hand as it is beneficial for long-term retention as you get a firm hold over writing flawless codes. Also, in a lot of interviews, you are asked to write codes on a white board.Program as a Pair: With a friend or another learner completing a task together is called pair programming. It is a technique where two developers work at a single workstation. One of the developers should be the “driver” and the other should be the “navigator”. The “driver” writes the code, while the “navigator” helps guide the problem solving and reviews the code as it is written. Both the developers should switch between the roles.Build new things: There are a lot of short exercises for beginners which will make you confident with Python. You should have good knowledge about basic data structures (strings, lists, dictionaries, sets), object-oriented programming, and writing classes. Here, let us discuss about what Python is all about, how to get started with Python and learn about the basics of Python.What is Python?Python is an interpreted, interactive, object-oriented and multi-purpose programming language created by Guido Van Rossum in the late 1980s. It is a programming language— a language which people and computers both can understand. It is powerful and has an easy-to-use syntax, making it perfect for beginners.Python is a flexible language which has the ability to write simple programs and also create large complex programming solutions. It is used extensively for web and internet developments, for mathematical and scientific computations of data and also in the field of game and graphics development. Some of the popular websites that use Python are Youtube, Instagram, Dropbox, Pinterest etc. Join the certification course on Python Programming to learn more about Python and its capabilities.Why Choose Python?Whether you’re a beginner to programming or an experienced programmer designing a complex application, Python is a great choice because of its easily understandable nature and vast capabilities. Some of the features of Python that make it irresistible to users:Popularity: Python is considered as the 4th most popular and fastest growing programming language according to the Stack Overflow Developer Survey 2019. Python is used by the world’s most renowned Software Companies like Google, YouTube, Instagram, Netflix, Spotify, Quora and much more.Interpretation: Python is an interpreted language which means the programs are passed straight to the interpreter which executes them directly; unlike compilers where the source code is converted to machine code before running.OpenSource: Python is a free language developed under OSI-approved open-source license which makes it free to use and distribute even for commercial purposes.Portability: Python code is portable, which means the code written in one platform will work in any other platform, having the Python interpreter installed.Simplicity: Python’s coding style is very simple and clean which makes it easy to read and learn. It uses less keywords compared to other languages like C++ or Java. Developers tend to use it all the time because of its neat and organized code structure.How to Get Python?Python is an open-source software that comes pre-installed in Mac and works on most distributions of Linux and other platforms. However, you might need to download the latest version to get the most out of it.Choosing Python Presently, there are two major versions of Python - 2.x and 3.x. However, at an early stage, you can use either of the two because there are very few differences between them. Also once you have learned one, the other one won’t be difficult to learn.In simple terms, if you’re starting to learn Python, the latest version 3.7.x would be more suitable since it comes with extra features with a number of bug fixes. On the other hand, you can use the version 2.7.x when you need support from third-party libraries to perform your task.Installing PythonYou can download the specific version of Python that suits your OS and processor (32-bit or 64-bit) from the Python Software Foundation (PSF).Installation pertaining to OS requirement:Windows: In any Windows platform, you can directly download Python software from the PSF.Linux: You can download the latest version of Python on Linux in the same manner. However, you can also use a package manner, if needed.Mac: For Mac systems, download the software from PSF and then install it. Moreover, it is suggested to use a package manager like Homebrew for installing and managing different versions of Python.Python ShellAfter you have successfully installed Python in your system, you can check whether it is installed or not using the Python Interactive Shell:Windows: Open the terminal and type python for Python 2.7 or py -3 for Python 3.Linux: Open your terminal and simply run python.Mac: Depending on the version of Python you’ve installed, open your terminal and run python or python3.The command prompt or the terminal will look somewhat like this:Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:21) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>You can use the exit() to leave the Python shell or you can also use CTRL + D and then press the ENTER key to terminate the command prompt.What are the Basics of Python?Python is a very beautiful language and feels very natural to work with. It consists of a number of coding basics. Let us first start by running the universal Hello World program.The Hello World ProgramIf you want to display a line in the terminal, you can do so by using the print statement:>>> print("HELLO WORLD!")The output will be displayed as follows:HELLO WORLD!VariablesVariables are defined as containers or memory locations for storing data. The syntax of declaring a variable is variable_name = variable_value. However, it is recommended to use variables names like num1, my_int or mystring other than simple variables like x or y.Sensible names gives a clear indication of the type of variable and it is also useful for others to understand your code clearly. Thinking of others while writing your program will improve your coding skills.Built-in Data TypesPython comprises of many built-in data types starting from numbers, strings, lists, tuples and dictionaries.NumbersPython supports many types of numbers like integers (1, 2, 55, 599, -99), floating points (1.0, 5.55,  661.1, -99.9),  Booleans (True or False) or complex numbers. We can perform addition and subtraction with numbers just like normal addition and subtraction we learnt in our school:>>> 1 + 5   # Addition 6 >>> num1 = 5 >>> num2 = 5.01 >>> num3 = num1 + num2 >>> 10 - 5   # Subtraction 5We can also compare numbers that will result in a boolean value:>>> 1 >> 4 > 5 FalsePython consists of a number of built-in functions that you can use to handle numbers:>>> float(13) 13.0A float() function takes an integer and returns a floating point number.Other than functions, Python also has a number of data-type methods connected to each type of number. float.is_integer() is a data-type method which checks whether a floating point number is finite or not:>>> (10.1).is_integer() False >>> (5.0).is_integer() True StringsA String is a list of characters in an organized manner. A character can be a number or letter or even a backslash. In simple words, they are lines enclosed in single or double quotes:>>> string1 = "hello" >>> string 'hello' >>> string2 = 'hey' >>> string2 "hey"In Python, we can combine strings in a series without any gaps. This is called Concatenation:>>> "Python is" + "easy" 'Python is easy'We can also manipulate strings using functions:>>> len('Python') 6Here, len() is a function that takes a string as an input and returns the size of the string.Data-type methods also exist for handling strings. string.capitalize() takes an input string and returns by capitalizing the first string:>>> lower_case_string = 'python' >>> lower_case_string.capitalize() 'Python' >>> ('the Avengers').capitalize() 'The Avengers' ListsA list is an ordered sequence of elements in Python. Each element in a list is known as an item. They are similar to array in C or C++.Lists may consist of any data type like numbers or strings mixed together, or other lists or they may be empty too. The syntax is usual:>>> create_a_list = [] >>> list_of_numbers = [1, 5, 10, 1000] >>> list_of_numbers [1, 5, 10, 1000] >>> list = ["ironman", "thor", "hulk"] >>> list ['ironman', 'thor', 'hulk'] >>> mixed_list = ["Python", [1, 2, 3], True] >>> mixed_list ['Python', [1, 2, 3], True]Elements of lists can be accessed either from the start or the end. Also, you can create a new list just by accessing the elements:>>> list_of_numbers = [1, 5, 10, 1000] >>> new_list = list_of_numbers[0:2] >>> new_list [1, 5]Concatenation of lists using operators:>>> marvel = ["ironman", "thor", "hulk"] >>> dc = ["superman", "batman", "flash"] >>> multiverse = marvel + dc >>> multiverse [‘ironman’, ‘thor’, ‘hulk’, ‘superman’, ‘batman’, ‘flash’]The function of lists works in the same manner as of strings:>>> list_of_numbers = [1, 5, 10, 1000] >>> len(list_of_numbers) 4len() returns the size of the list.Data-type methods like list.sort() and list.append() are used to sort  and append lists:#append >>> stationary = ["inkpen", "pencil", "eraser"] >>> stationary.append("sharpener") >>> fruits ['inkpen', 'pencil', 'eraser', 'sharpener']#sort>>> stationary.sort()>>> stationary[ 'eraser', 'inkpen', 'pencil', 'sharpener']TuplesTuples are sequence of Python objects that cannot be changed after creation. They are similar to lists, the only difference being that lists are mutable.An example of a tuple:my_tuple = ("Alex", "Blanc", 27, "Technical Blogger")You can concatenate two tuples using operators just like lists:>>> tuple1 = (11, 29) >>> tuple2 = (30, 90) >>> tuple3 = tuple1 + tuple1 >>> tuple3 (11, 29, 30, 90)You can convert a tuple into a list by using the function list():>>> tuple1 = (100, 500)>>> list(tuple1)[100, 500]Since tuples cannot be changed after it is created, most of the data-type methods like sort() or append() or reverse() will not work on tuples.DictionaryA dictionary in Python is an unordered collection of associative arrays (or objects).An example of a dictionary of phone numbers:>>> phonebook = {} >>> phonebook["Alex"] = 9038478766 >>> phonebook["Bob"] = 9098379264 >>> phonebook["Charlie"] = 9017652781ConditionsA conditional statement is a statement that handles the flow of execution depending on some condition.Statements can be compared or evaluated in Python using boolean expressions as follows:>>> x = 5 >>> print(x == 5) # prints True >>> print(x == 2) # prints FalseYou can also use the if-else statements to check if a statement is true or not:>>>if 2 > 3:   print("2 is greater than 3")   else:   print("2 is not greater than 3")LoopsYou can use loops when you want to repeat a block of code in a fixed number of time. You can iterate in two different ways, the first is by using the while loop:>>> num = 1 >>> while num >> for num in range(1, 10):     print(num) Here, the range starts from 1 and goes until 10. The loop iterates 10 times over the statement.FunctionsFunctions in Python are a block of organized code which is useful in performing a single action. Syntax of defining a function is def function_name.An example of a function is:>>> def my_first_function(): print("HELLO WORLD!")You can also return a value to the caller in a function using the return statement:>>> def multiply_by_2(a): return a * 2Classes and ObjectsAn object in Python is a collection of variables and methods. A class is a blueprint for the object.For example, we can consider a prototype of a house as the class. It consists of all the details of the floors, walls, doors, windows etc. We can build the house on the basis of the details. So, house becomes the object. Objects are instances of a class.You can define a class in Python using the keyword class as follows: >>> class My_First_Class:     my_variable = "blah"You can create an object in Python which can be used to access different attributes of a class. This process of creating new object instances is called instantiation.An example to illustrate that:class My_First_Class: def func(self): print('Hello') ob = My_First_Class() #creating a class objectModules and PackagesA module is a single file (or files) that are imported under one import and then used. In simple words, any Python file is a module. On the other hand, packages are simple directories consisting of multiple modules and packages themselves.Python consists of a number of packages and modules to increase the extent of the language. Some of the useful built-in Python modules are:math: This module gives access to mathematical functions from the standard library of C.random: This module is a pseudo-random number generator.datetime: This module comprises of classes by which you can manipulate dates and times.Pip is the standard package manager which is used to handle Python’s third party packages and modules in an efficient manner. It allows you to install the packages that are not part of the Python Standard Library. You can download Pip from pypi.org.CommentsComments can be in the form of module-level docstrings or inline explanations that are used to describe your code in a clear manner so that developers can understand. It starts with a hash (#) character and can extend to the end of the line.An example of a simple comment:# This is a commentAn example of an inline comment:variable = "Hello World"  # This is an inline commentErrors and Exceptions Python consists of two types of errors:Syntax errors.Exceptions or errors during execution.Syntax ErrorsSyntax errors occur when the Python parser is unable to understand a line of code. Most syntax errors occur because of incorrect indentation or arguments.An example to illustrate such:>>> if 2 < 5   File "", line 1      if 2 < 5              ^ SyntaxError: invalid syntaxHere, the if statement is missing a colon(:)at the end of the statement which results into a syntax error.ExceptionsErrors that occur during execution are known as exceptions. There are a number of built-in exceptions in Python.An example of an exception:>>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25} >>> prices['Eraser'] Traceback (most recent call last):   File "", line 1, in     prices['Eraser'] KeyError: 'Eraser'Here, dictionary prices is declared with the prices of three items. The KeyError is raised when the item ‘Eraser’ is being accessed which is not present in prices. Learn more about exceptions in our blog- Python KeyError Exceptions and How to Handle Them.Semantic ErrorsA semantic error, also known as logic error, is an error that occurs because of an incorrect logic. They are much more difficult to catch as compared to syntax errors.These type of errors are complex in nature and generate incorrect or no output. The most common example of a semantic error is an infinite loop. Programmers in their early stage of learning encounter an infinite loop at least once.What are the Different ways of Coding in Python?When you’re in the process of learning a new programming language, you might want things to be simple and your path of becoming a good programmer to be smooth and clear. The first approach to this will be choosing an efficient way of running and executing code in Python.There are mainly three primary approaches to coding in Python— the shell, IDLE and the code editor.The ShellPython provides the Python Shell, which is useful for simple, one-line statements. It waits for the input commands from the user and returns the result of the execution. It is the least powerful among the three.You can open shell in your system and run the following command:>>> 11 + 9 20 Here, the Python Shell evaluated the statement 11 + 9 , performed the addition operation and displayed the result 20.Another example of coding in shell:>>> import thisWhen you execute this statement, you can see the Zen of Python. It is a collection of 19 principles which acts as a guide to write idiomatic Python code.However, the shell has a drawback. The code written in a Python Shell is not persistent which means the code cannot be reused. IDLEIDLE stands for Integrated Development and Learning Environment. It is similar to the shell and contains both the Shell window and the Editor Window. You can create and save Python code because the IDLE allows code reusability. However, it still stands second in the rank powerfulness. Code EditorA code editor is the most powerful among all the three. It is a text-editor program that is useful in editing source codes of computer programs. A code editor can be a single application or act as an Integrated Development Environment or IDE.There are a lot of code editors available in the market. Choosing a code-editor for your task might be a time-consuming work. However, you can take into consideration some factors while choosing a code editor like easy to use, line numbering, auto-indentation, highlighting of syntax and availability of adding extra features.One of the most powerful and popular cross-platform code editor is the Sublime Text.  Other code editors might include gedit,  which is a bit simpler than Sublime. You can also use Notepad++, however it is only for Windows.ConclusionLet’s sum up what we have learnt so far in this article:What is Python programming and what is the need.How to install and run Python.What are the primitives of the Python programming language.What are the ways of Python coding.Though you have learned the basics of the Python Programming Language, here are some tricks and tricks for you remember while coding in Python—Good coding is happy coding. Good code depends on the way you write a code. The key to a good code is to maintain a proper style. You can go through the blog on How To Write Beautiful Python Code With PEP 8 which focuses on enhancing the readability and consistency of code.The logic is the most crucial part when you’re writing a program. If you have a clear understanding of the concepts, you can easily shape your code into a logical program. And the most effective way to do that is to logically break your problem into different parts and then solve it one by one.The best way of learning how to code is by building a project-driven learning approach. There are a lot of free resources, online courses, books and tutorials available. You can refer to the official Python documents - Python 2.7 or Python 3 for more information.You can also join the Python certification course offered by KnowledgeHut.And last but not the least, always keep brushing up the concepts. As a beginner, you might face difficulties in every step, but always try and resolve your issues on your own. Test your skills and take up new challenges everyday.
Rated 4.5/5 based on 3 customer reviews
8791
What is Python, it's basics and getting start...

Learning something new is always interesting and e... Read More

How To Write Beautiful Python Code With PEP 8

It gets difficult to understand a messed up handwriting, similarly an unreadable and unstructured code is not accepted by all. However, you can benefit as a programmer only when you can express better with your code. This is where PEP comes to the rescue. Python Enhancement Proposal or PEP is a design document which provides information to the Python community and also describes new features and document aspects, such as style and design for Python.Python is a multi-paradigm programming language which is easy to learn and has gained popularity in the fields of Data Science and Web Development over a few years and PEP 8 is called the style code of Python. It was written by Guido van Rossum, Barry Warsaw, and Nick Coghlan in the year 2001. It focuses on enhancing Python’s code readability and consistency. Join the certification course on Python Programming and gain skills and knowledge about various features of Python along with tips and tricks.A Foolish Consistency is the Hobgoblin of Little Minds‘A great person does not have to think consistently from one day to the next’ — this is what the statement means.Consistency is what matters. It is considered as the style guide. You should maintain consistency within a project and mostly within a function or module.However, there will be situations where you need to make use of your own judgement, where consistency isn’t considered an option. You must know when you need to be inconsistent like for example when applying the guideline would make the code less readable or when the code needs to comply with the earlier versions of Python which the style guide doesn’t recommend. In simple terms, you cannot break the backward compatibility to follow with PEP.The Zen of PythonIt is a collection of 19 ‘guiding principles’ which was originally written by Tim Peters in the year 1999. It guides the design of the Python Programming Language.Python was developed with some goals in mind. You can see those when you type the following code and run it:>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!The Need for PEP 8Readability is the key to good code. Writing good code is like an art form which acts as a subjective topic for different developers.Readability is important in the sense that once you write a code, you need to remember what the code does and why you have written it. You might never write that code again, but you’ll have to read that piece of code again and again while working in a project. PEP 8 adds a logical meaning to your code by making sure your variables are named well, sufficient whitespaces are there or not and also by commenting well. If you’re a beginner to the language, PEP 8 would make your coding experience more pleasant.Following PEP 8 would also make your task easier if you’re working as a professional developer. People who are unknown to you and have never seen how you style your code will be able to easily read and understand your code only if you follow and recognize a particular guideline where readability is your de facto.And as Guido van Rossum said— “Code is read much more than it is often written”.The Code LayoutYour code layout has a huge impact on the readability of your code.IndentationThe indentation level of line is computed by the leading spaces and tabs at the beginning of a line of logic. It influences the grouping of statements. The rules of PEP 8 says to use 4 spaces per indentation level and also spaces should be preferred over tabs.An example of code to show indentation:x = 5 if x < 10:   print('x is less than 10') Tabs or Spaces?Here the print statement is indented which informs Python to execute the statement only if the if statement is true. Indentation also helps Python to know what code it will execute during function calls and also when using classes.PEP 8 recommends using 4 spaces to show indentation and tabs should only be used to maintain consistency in the code.Python 3 forbids the mixing of spaces and tabs for indentation. You can either use tabs or spaces and you should maintain consistency while using Python 3. The errors are automatically displayed:python hello.py  File "hello.py", line 3       print(i, j)                 ^TabError: inconsistent use of tabs and spaces in indentationHowever, if you’re working in Python 2, you can check the consistency by using a -t flag in your code which will display the warnings of inconsistencies with the use of spaces and tabs.You can also use the -tt flag which will show the errors instead of warnings and also the location of inconsistencies in your code. Maximum Line Length and Line BreakingThe Python Library is conservative and 79 characters are the maximum required line limit as suggested by PEP 8. This helps to avoid line wrapping.Since maintaining the limit to 79 characters isn’t always possible, so PEP 8 allows wrapping lines using Python’s implied line continuation with parentheses, brackets, and braces:def function(argument_1, argument_2,             argument_3, argument_4):     return argument_1Or by using backslashes to break lines:with open('/path/to/some/file/you/want/to/read') as example_1, \     open('/path/to/some/file/being/written', 'w') as example_2:     file_2.write(file_1.read())When it comes to binary operators, PEP 8 encourages to break lines before the binary operators. This accounts for more readable code.Let us understand this by comparing two examples:# Example 1 # Do total = ( variable_1 + variable_2 - variable_3 ) # Example 2 # Don't total = ( variable_1 + variable_2 - variable_3 )In the first example, it is easily understood which variable is added or subtracted, since the operator is just next to the variable to which it is operated. However, in the second example, it is a little difficult to understand which variable is added or subtracted.Indentation with Line BreaksIndentation allows a user to differentiate between multiple lines of code and a single line of code that spans multiple lines. It enhances readability too.The first style of indentation is to adjust the indented block with the delimiter:def function(argument_one, argument_two,               argument_three, argument_four):         return argument_oneYou can also improve readability by adding comments:x = 10 if (x > 5 and     x < 20):     # If Both conditions are satisfied     print(x)Or by adding extra indentation:x = 10 if (x > 5 and       x < 20):     print(x)Another type of indentation is the hanging indentation by which you can symbolize a continuation of a line of code visually:foo = long_function_name(       variable_one, variable_two,       variable_three, variable_four)You can choose any of the methods of indentation, following line breaks, in situations where the 79 character line limit forces you to add line breaks in your code, which will ultimately improve the readability.Closing Braces in Line ContinuationsClosing the braces after line breaks can be easily forgotten, so it is important to put it somewhere where it makes good sense or it can be confusing for a reader.One way provided by PEP 8 is to put the closing braces with the first white-space character of the last line:my_list_of_numbers = [     1, 2, 3,     4, 5, 6,     7, 8, 9     ]Or lining up under the first character of line that initiates the multi-line construct:my_list_of_numbers = [     1, 2, 3,     4, 5, 6,     7, 8, 9 ]Remember, you can use any of the two options keeping in mind the consistency of the code.Blank LinesBlank lines are also called vertical whitespaces. It is a logical line consisting of spaces, tabs, formfeeds or comments that are basically ignored.Using blank lines in top-level-functions and classes:class my_first_class:     pass class my_second_class:     pass def top_level_function():     return NoneAdding two blank lines between the top-level-functions and classes will have a clear separation and will add more sensibility to the code.Using blank lines in defining methods inside classes:class my_class:     def method_1(self):         return None     def method_2(self):         return NoneHere, a single vertical space is enough for a readable code.You can also use blank spaces inside multi-step functions. It helps the reader to gather the logic of your function and understand it efficiently. A single blank line will work in such case.An example to illustrate such:def calculate_average(number_list):     sum_list = 0     for number in number_list:         sum_list = sum_list + number         average = 0     average = sum_list / len(number_list)    return averageAbove is a function to calculate the average. There is a blank line between each step and also before the return statement.The use of blank lines can greatly improve the readability of your code and it also allows the reader to understand the separation of the sections of code and the relation between them.Naming ConventionsChoosing names which are sensible and can be easily understandable, while coding in Python, is very crucial. This will save time and energy of a reader. Inappropriate names might lead to difficulties when debugging.Naming StylesNaming variables, functions, classes or methods must be done very carefully. Here’s a list of the type, naming conventions and examples on how to use them:TypeNaming ConventionsExamplesVariableUsing short names with CapWords.T, AnyString, My_First_VariableFunctionUsing a lowercase word or words with underscores to improve readability.function, my_first_functionClassUsing CapWords and do not use underscores between words.Student, MyFirstClassMethodUsing lowercase words separated by underscores.Student_method, methodConstantsUsing all capital letters with underscores separating wordsTOTAL, MY_CONSTANT, MAX_FLOWExceptionsUsing CapWords without underscores.IndexError, NameErrorModuleUsing short lower-case letters using underscores.module.py, my_first_module.pyPackageUsing short lowercase words and underscores are discouraged.package, my_first_packageChoosing namesTo have readability in your code, choose names which are descriptive and give a clearer sense of what the object represents. A more real-life approach to naming is necessary for a reader to understand the code.Consider a situation where you want to store the name of a person as a string:>>> name = 'John William' >>> first_name, last_name = name.split() >>> print(first_name, last_name, sep='/ ') John/ WilliamHere, you can see, we have chosen variable names like first_name and last_name which are clearer to understand and can be easily remembered. We could have used short names like x, y or z but it is not recommended by PEP 8 since it is difficult to keep track of such short names.Consider another situation where you want to double a single argument. We can choose an abbreviation like db for the function name:# Don't def db(x):     return x * 2However, abbreviations might be difficult in situations where you want to return back to the same code after a couple of days and still be able to read and understand. In such cases, it’s better to use a concise name like double_a_variable:# Do def double_a_value(x):     return x * 2Ultimately, what matters is the readability of your code.CommentsA comment is a piece of code written in simple English which improves the readability of code without changing the outcome of a program. You can understand the aim of the code much faster just by reading the comments instead of the actual code. It is important in analyzing codes, debugging or making a change in logic. Block CommentsBlock comments are used while importing data from files or changing a database entry where multiples lines of code are written to focus on a single action. They help in interpreting the aim and functionality of a given block of code.They start with a hash(#) and a single space and always indent to the same level as the code:for i in range(0, 10):     # Loop iterates 10 times and then prints i     # Newline character     print(i, '\n')You can also use multiple paragraphs in a block comment while working on a more technical program. Block comments are the most suitable type of comments and you can use it anywhere you like.Inline CommentsInline comments are the comments which are placed on the same line as the statement. They are helpful in explaining why a certain line of code is essential.Example of inline comments:x = 10  # An inline comment y = 'JK Rowling' # Author NameInline comments are more specific in nature and can easily be used which might lead to clutter. So, PEP 8 basically recommends using block comments for general-purpose coding.Document StringsDocument strings or docstrings start at the first line of any function, class, file, module or method. These type of comments are enclosed between single quotations ( ''') or double quotations ( """ ).An example of docstring:def quadratic_formula(x, y, z, t):     """Using the quadratic formula"""     t_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)     t_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)     return t_1, t_2Whitespaces in Expressions and StatementsIn computing, whitespace is any character or sequence of characters which are used for spacing and have an ‘empty’ representation. It is helpful in improving the readability of expressions and statements if used properly.Whitespace around Binary OperatorsWhen you’re using assignment operators ( =, +=, -=,and so forth ) or comparisons ( ==, !=, >, =,
Rated 4.5/5 based on 1 customer reviews
8613
How To Write Beautiful Python Code With PEP 8

It gets difficult to understand a messed up handwr... Read More

How to Implement a Python Stack

Whether you want to reverse a string or create a language processing application, stacks are very useful. It can be used to solve a wide variety of problems. In fact most of the programming languages including the operating systems are dependent on stack to function.The name Stack data structure totally resembles a pile of objects, stack of papers, or a tower of blocks, where adding and removing of items occur only at the top of the pile. It is similar to removing a quarter in the middle of a stack of coins without destroying the entire thing. In this article we will understand stack operations and look into the various ways to implement stack in Python. You may also get certified and learn more about Python Programming and apply those skills and knowledge in the real world.What is a Stack?A Stack is an abstract linear data type that serves as a collection of objects. Unlike queues, they use the Last In First Out or LIFO  technique to insert and delete elements. The insert and delete operations are referred to as push and pop in stack.Stacks and Queues are both linear collections of items. However, in a queue, the least recently added item is removed first, following the First In First Out or FIFO  manner. On the other hand, in a stack, the most recently added item is removed in the beginning following the LIFO. Stack stores the data elements in a similar fashion as a bunch of plates that are kept one above the other in a kitchen. It allows operations (push or pop) only from one end, often called as top. You can add or remove elements only from the top of the stack.A real-life example of a stack is a pile of heavy and precious plates, all kept on top of the other. If you wish to add a plate or remove one, you can do that only from the top. However, if you want to remove a lower plate from the stack, you have to remove the topmost plates one by one, in order to remove the desired one. Other examples are a deck of cards or a pile of books etc.What are the basic operations performed in Stack?The basic operations which are performed in the stack are mentioned below:Push: Adds an item in the stack. Once the stack is full, it is said to be in an Overflow condition.Pop: Removes an item from the stack. It follows a reversed order to pop items similar to the way when items are pushed. It is said to be an Underflow condition.Peek or Top: Returns top element of stack.isEmpty: Returns true if stack is empty, else false.Applications of StackStacks are considered as the backbone of Data Structures. Most of the algorithms and applications are implemented using stacks.Some of the key applications of stacks are—They are used to reverse a string. Each of the characters are pushed in and then popped off, which results in a reversed string.It is used in Expression Evaluation and Expression Conversion (infix to postfix, infix to prefix, postfix to infix, prefix to infix).It is used for forward and backward features in web browsers.It is used for recursive parsing in Natural Language Processing.It is used in syntax parsing and parenthesis checking.It is used for Backtracking like finding paths to a maze or exhaustive searching.It is used in Algorithms like Tower of Hanoi, tree traversals, histogram problem and also in graph algorithms like Topological Sorting.Understanding Stack OperationsThere are mainly two types of primitive stack operations:Push: It is performed to insert and store an element in the stack. However, when you try to insert an element in a stack which is full, the Overflow condition occurs.Pop: It is used to remove an element from the stack. However, when the stack is empty, the Underflow condition occurs.PushLet’s consider editing a Python file using the undo feature in your editor so you can have a clear understanding of the stack operations. At first, a new function called Insert is added. The push operation adds the Insert function into the stack:Now, a word Delete is removed from any of the comments. This word also gets added to the stack:The Delete is added to the top of the stack. Finally, let us indent a Comment to align things appropriately which is also inserted into the stack:Note that the commands entered are all stored in the stack just like a pile with each command on top of the other. This operation of adding new elements into the stack is called push.PopNow to perform the pop operations, let us make use of the undo feature. When we first hit the undo, it removes the top-most element of the stack (here, which is Comment):The editor removes the indented Comment and the stack is now left with two commands. When the next undo is hit again, the next command is removed from the stack:Now Delete is also removed and the stack is left with only one operation. When the undo is hit again, the last element remaining in the stack is also popped off and the stack becomes empty as it was in the first place:Since the stack is now empty, if we again hit undo, it will result into an Underflow condition causing no effect.Implementing Stack in PythonPython gives you a lot of options for implementing a Python stack. You can do so by using lists, tuples or by using third-party modules or packages. However, there are some basic implementations of Python stack that will fulfil most of your needs.Some of those implementations are as follows:listcollections.dequequeue.LifoQueueUsing ListList is a built-in structure that can be used as stack in Python. We use lists often to write Python programs. They are implemented as internal dynamic arrays in Python which means whenever elements are added or removed, the storage area is resized every time accordingly.You can use .append() to add elements and .pop() to remove them:>>> my_first_stack = [] >>> my_first_stack.append('Alex') >>> my_first_stack.append('Bob') >>> my_first_stack.append('Charlie') >>> my_first_stack ['Alex', 'Bob', 'Charlie'] >>> my_first_stack.pop() 'Charlie' >>> my_first_stack.pop() 'Bob' >>> my_first_stack.pop() 'Alex' >>> my_first_stack.pop() Traceback (most recent call last):   File "", line 1, in IndexError: pop from empty listNotice that an IndexError is raised. This is because .pop() is called on an empty stack.Though lists work very efficiently in implementing stacks, yet it comes with some drawbacks. There might be situations where your stack might grow bigger than the current block of memory  it holds. Since lists are used for faster access to random elements, in such situations, speed issues occur. Python starts allocating memory implicitly which leads to longer .append() calls.Speed issues also occur when you use .insert() to add elements in your stack.Using ArrayIt is quite easy to implement stack using Python Lists. However, you can implement stack using arrays as well if you assume that lists are like arrays. You can follow the algorithm mentioned below to understand how it works.Algorithm:Declare a list and an integer MaxSize, and denote the maximum size of the StackInitially set the Top to 0.Push operation:Check if the MaxSize of the Stack is greater than TopIf yes, append data to stack and increase top by 1If no, print stack full messagePop operation:Check if Top is greater than 0:If yes, pop the last element from the list and decrement top by 1If no, print stack empty messageSize operation: The size of the Stack is the value of the Top pointer.class Stack:     #Constructor     def __init__(self):         self.stack = list()         self.maxSize = 8         self.top = 0     #Adds element to the Stack     def push(self,data):         if self.top>=self.maxSize:             return ("Stack Full!")         self.stack.append(data)         self.top += 1         return True     #Removes element from the stack     def pop(self):         if self.top>> from collections import deque >>> my_first_stack = deque() >>> my_first_stack.append('Alex') >>> my_first_stack.append('Bob') >>> my_first_stack.append('Charlie') >>> my_first_stack deque(['Alex', 'Bob', 'Charlie']) >>> my_first_stack.pop() 'Charlie' >>> my_first_stack.pop() 'Bob' >>> my_first_stack.pop() 'Alex' >>> myStack.pop() Traceback (most recent call last):   File "", line 1, in IndexError: pop from an empty dequeThe objects of the deque class has a consistent performance because they are implemented in the form of doubly linked lists.Using queue.LifoQueueThe Python Standard Library comprises of another class called queue.LifoQueue class to implement stack. It supports multiple simultaneous producers and consumers.Python Threading is used for executing multiple tasks and function calls at the same time and independently of other codes. If your program involves threads, it is recommended not to use list and deque because they behave very differently in such cases.list is not thread-safe. On the other hand, though, .append() and .pop() are atomic in nature, it is nearly impossible to build a Python stack using deque that is fully thread-safe. This is because of the reason that in a threaded environment, there are other deque class methods that are neither atomic nor they are thread-safe and might lead to race conditions.So the last option we’re left with is the queue.LifoQueue class that is specially designed to be fully thread-free.Adding and removing elements are performed in this class are using .put() and .get():>>> from queue import LifoQueue >>> my_first_stack = LifoQueue() >>>my_first_stack.put('Alex') >>>my_first_stack.put('Bob') >>>my_first_stack.put('Charlie') >>> my_first_stack >>> my_first_stack.get() 'Charlie' >>> my_first_stack.get() 'Bob' >>> my_first_stack.get() 'Alex' >>> my_first_stack.get_nowait() Traceback (most recent call last):   File "", line 1, in     my.get_nowait() _queue.Empty >>> my_first_stack.get()  # Waits foreverThe queue module might be helpful when you are working with multiple threads or with parallel computing. However, for general purpose stack implementation, it is recommended to use lists or deque.deque: An excellent choice for implementing a Python StackIf you’re not interested in handling explicit locking and unlocking and also not looking for parallel processing support, then your choice for choosing the right Python stack implementation narrows down to list and deque. However, they both have different implementations of data structures in their working.Operations like indexing and slicing work very well with lists because it is built upon contiguous blocks of memory. The elements in the list are stored in a dynamic array system making it easier for Python to find any element in the memory.However, this type of layout system raises speed issues in situations like when the contiguous block is full, it needs to get another block which in turn increases the execution time.On the other hand, deque is a doubly linked list in which each entry is linked to both the previous and next entry in the list. This allows adding elements to both the ends of the list. In this type of linked list, each memory has its own memory block. Thus, combining all these reasons, deque is a much better choice than list when implementing stacks in Python.ConclusionLet us sum up what we’ve learnt in this article so far:What is a Stack and what are its applications.What do Stack operations look like.When should a data structure like Stack be used.Different ways of implementing Stack in Python.How to select the right implementation depending upon your problem.Stacks are simple data structures that allows us to store and retrieve data in a sequential fashion. They are very useful in real world cases. Having a clear understanding of stacks would help us in solving data storage problems in an efficient manner.If you wish to know more about data structures and other aspects of Python, you can go through the Python tutorial. You may also join the certification course on Python.
Rated 4.5/5 based on 1 customer reviews
7589
How to Implement a Python Stack

Whether you want to reverse a string or create a l... Read More