Search

About SELENIUM WEBDRIVER-3

Why WebDriver-3? In present market we have a tool called IDE. It is a tool which works only on Mozilla firefox. It has many drawbacks and doesn’t generate proper reports. IDE is not a preferred tool because sometimes when the scripts run, it finds the locator and sometimes it doesn’t find it and so the script fails. So, to overcome all these challenges we have a tool called WebDriver. WebDriver works on Multiple browsers like Firefox, IE, Chrome, Safari, Opera etc. It supports multiple languages like Java, C#, Ruby, Python and JavaScript. With WebDriver, we can make dynamic scripts like scripts on Webpages which changes everyday and we can make our scripts run on multiple browsers. Downloading WebDriver-3 Jars and configuring in eclipse To start with WebDriver, the first thing we need to do is to download WebDriver Jars and configure it in Eclipse IDE. We need to download Jar files of WebDriver from the official website of Selenium, which is Selenuimhq.org where we need to go to download section and under the download section, we will see the latest version which is 3.4.0. Click on the link and file will be downloaded in the downloads folder. Also, click on Change log at Selenium website to describe what has changed in the new version. The last 2.x version was 2.53 which is a stable build, meaning it has no major issues. After 2.53, the next build which came up was 3.XX. The changes made in 3.0 is that, minimum java version requires 1.8, where we need to make sure that jdk8 is installed. Installing Java To install java, Go to Google and type download Jdk. Go to first link as shown below Depending upon the system, we need to install either Windows x32 or Windows x64 bit and accept the License Agreement. For downloading Java, we need to click on Download link, where Zip file will be downloaded on our PC. Go to downloaded folder and extract it and double click on exe. Java will be installed in the system and now we need to configure the class path. If we are using v2.53.0 version, then we will be needing Firefox 40 or below. In case, we are using 3.0 then we need to go for latest version of Firefox. Configuring Jar Files in Eclipse Step1: Open Eclipse and make a New Project (ex:Sample) Step2: Right click on the project and select the option Properties as shown below Step3: Go to Java Build Path > Libraries Tab and click on Add External Jars as shown below: Now, go to the location where we saved our Jar Files and add all the jar files. It will appear like below image after adding all Jar files: Once we are done with configuring Jar files in eclipse, we can see a folder called Referenced Libraries under Project folder where we have all our Jar Files. Architecture of selenium webdriver 3 First we need to know a few concepts if we want to understand the working of Selenium WebDriver Architecture. Language Binding or Selenium Client Library Selenium API Remote WebDriver Json Wired Protocol WebDrivers Language Binding or Selenium Client Library : It is nothing but a collection of Jar files, where the language in which we write our selenium framework is present. It means that the language which we used to write the script may be Java, C#, Ruby, Python, perl. Selenium API : API Stands for Application Programming Interface. API is a particular set of rules and specifications that software programs can follow to communicate with each other. API serves as an interface between software program and facilitate their interaction. API is a software to software interaction which means API works between software to software. With the help of APIs, applications talk to each other without any user knowledge. Remote WebDriver : It is an implementation class of the webdriver interface that a test script developer can use to execute their test script through webdriver server on remote machine. JSON:  It stands for JavaScript Object Notation. It is a lightweight data interchange format which helps us to interchange the data. JSON is used to transfer data between client and server on the web. A simple JSON file has .json extension. JSON wired protocol send data in JSON format. Thereafter, the server will firstly parse the data and execute it and after that, response given by the server will be sent back to the client in JSON format. Webdriver: Webdriver is a tool for automating web applications and verifying that     they work as expected.  Architecture: Tester writes script in any language like java, C# etc and selenium client library will communicate with selenium API. Selenium API will send the command taken from language level binding to browser driver with the help of JSON wired protocol and sends the request to Browser Driver, it may be Firefox driver, IE driver, Chrome driver. When we run all the commands we write in the script, it is converted with JSON wired protocol over HTTP and it will convert into URL and the request made by the HTTP and send to the browser. These browser drivers will use the HTTP server for getting HTTP request and these HTTP Server filter out all commands which we need to execute. Drivers for Firefox, IE, Chrome FirefoxDriver: It is an inbuilt class in Selenium. Lets create a New Class in Eclipse Class Name: Drivers_Selenium Inside main function, create an object of FirefoxDriver class like shown below: FirefoxDriver is an inbuilt class inside Referenced Libraries jars, where we can move mouse over the error and import FirefoxDriver class. After creating the object and running the program, we will get an exception like “The path to the driver executable must be set by the webdriver.gecko.driver system property” like shown in below image. import org.openqa.selenium.firefox.FirefoxDriver; public class Drivers_Selenium { public static void main(String[] args) { // TODO Auto-generated method stub new FirefoxDriver(); } } Steps to Download Geckodriver exe file: Step1: Go to seleniumhq.org Step2: Click on Download Tab Step3: Click on Mozilla Geckodriver 0.16.1 version in browsers session Step4: Click on geckodriver-v0.17.0-win64.zip or geckodriver-v0.17.0-win32.zip based upon our operating system. Open the downloaded folder and extract it, after extracting we will get geckodriver.exe file like shown below image. Now there is no need to double click on the geckodriver file, all we need is to set the System property known as “webdriver.gecko.driver” and we have to give the path of  geckodriver exe file. As java is a case sensitive language make sure that “webdriver.gecko.driver” is in lower case. Run the program where we can see a blank firefox getting opened. Now we need to give object reference as “FirefoxDriver fd” so that we can use the features of FirefoxDriver object. Inside the documentation of selenium, we find WebDriver interface. Inside this interface, we see a function get( ) which loads the new webpage in the current browser window. It open up a new URL.We can use the function “fd.get ” and get the URL. Run the above program where we can see the browser launching and it opens yahoo.com ChromeDriver : As the name suggests, it is for chrome. After creating the object and running the program, we will get an exception like “The path to the driver executable must be set by the webdriver.chrome.driver system property”.Now we also need to download an exe file.Go to download session in seleniumhq.org and scroll down where we find Google Chrome Driver link and click on it and it will redirect to the next page. From here we can download based upon our operating system as shown in below image.Whatever be the operating system, whether it is 32xbit or 64xbit, we can download the same file. Open the downloaded folder and extract it, after extracting we will get “chromedriver” file like shown in the below image. Now, there is no need to double click on chromedriver file, all we need to do is set the System property known as “webdriver.chrome.driver” and we have to give the path of chromedriver.exe file. As java is a case sensitive language, make sure that “webdriver.chrome.driver” is in lower case. Run the above program where we can see a blank chrome browser will launch. Now we need to give object reference as “ChromeDriver ” so that we can use the features of ChromeDriver object. Inside the documentation of selenium, we find WebDriver interface.Inside this interface we see a function get( ) which loads the new webpage in the current browser window. It opens up a new URL.We can use the function “cd.get ” and get the URL. Run the above program where we can see the Chrome browser launching and open it on yahoo.com IEDriver: As the name suggests it is for InternetExplorer. After creating the object and running the program, we will get an exception like “The path to the driver executable must be set by the webdriver.ie.driver system property”.Now we also need to download an exe file.Go to download session in seleniumhq.org and scroll down where we find IE Driver link and click on it and it will reside to next page from here we can download based upon our operating system, as shown in the below image.What ever be the operating system, whether it is 32xbit or 64xbit, we can download the same file. Open the downloaded folder and extract it, after extracting we will get “ieDriver” file. Now no need of double click on iedriver file, all we need is to set the System property known as “webdriver.ie.driver” and we have to give the path of  ie exe file. As java is a case sensitive language, make sure that “webdriver.ie.driver” is in lowercase. Now we need to give object reference as “IEDriver ” so that we can use the features of IEDriver object.Inside the documentation of selenium, we find WebDriver interface. Inside this interface, we see a function get( ) which loads the new webpage in the current browser window. It opens up a new URL.We can use the function “ie.get ” and get the URL. Run the above program where we can see the IE browser launching and open it in yahoo.com Launching Browsers Dynamically Let us Create New Class “Launch Browsers” Let us build a Testcase. Now our requirement is that we have a parameter called browser. If we write parameter as “Mozilla”, then the script we write in testcase should run in Mozilla browser. If we write a parameter as “Chrome”, it should run on chrome. Later on, we read this parameter from an excel file (xls) or any other file like property file, xml file. If our browser is Mozilla then below script should execute on Mozilla. If the browser is Mozilla then we want to launch the FirefoxDriver and take this FirefoxDriver to launch our desired website. In the above example, we keep on repeating the line to launch any website like fd.get(“http://gmail.com”). Later on if we want to click on a link in firefox then we need to write the code for each browsers separately. To overcome this, we use a concept called Interface reference points towards the class implementing the interface. WebDriver   d = new FirefoxDriver( ); WebDriver   d1= new ChromeDriver( ); Webdriver is an Interface and FirefoxDriver, ChromeDriver, IEDriver are implementing that Interface. Here d1 is  pointing towards chrome, so we can make d1 point towards FirefoxDriver as well , because the reference of the webdriver interface can point towards any implementing class or we can make d1 point towards InternetExplorerDriver as well, like shown below. d1 = new FirefoxDriver( ); d1 = new InternetExplorerDriver( ); So in the beginning of the program we can write WebDriver driver  =  null; Here Null means that driver is not pointing anywhere. So based on our choice, we can make driver point towards FirefoxDriver (or) ChromeDriver (or) InternetExplorerDriver as shown in the below program. Initially driver is “null”. Based on the options, driver will be initialized and we can give the command driver.get(“http://gmail.com”); All the driver classes will have same set of functions coming from WebDriver Interface, so “get” function will be there in all the driver classes. From the above program, we can launch the browser dynamically and we have to write a single script after launching the browser to interact with the browser. We do not need to write browser specific script. The reasons are : firstly all the drivers have same set of functions and secondly, the driver can point towards any of the driver classes like ChromeDriver, IEDriver. Selenium RC and WebDriver What is Firefox profile Let’s take an example where we have a PC at our place, being shared by two people. If the first person opens the PC and goes to Firefox, then firefox should get opened and it should have 1st person set of settings, his own set of bookmarks, his own set of plugins installed inside it. If a 2nd person opens PC and goes to Firefox, he should have his own set of settings, his own set of bookmarks, his own set of plugins. This concept is know as Firefox Profile. Importance of Firefox profile First where selenium launches Firefox, we write- driver  = new FirefoxDriver( ); Selenium will create its own profile and launch the browser. That profile is created programmatically by selenium and it gets destroyed when the script stops. Creating Profile manually on our PC Go to Firefox browser -> Go to File option and select Exit to close the firefox from the Exit menu, we should not close the firefox from the (x) option on the top as shown in below image. Go to windows session and type “firefox.exe -p profilemanager”. Copy the command and it will open the window as shown below. Click on Create Profile and give name as Selenium_Mod11. Click on the Finish button and click Start Firefox button where a new firefox browser will open up and this firefox browser will be like freshly installed firefox on our machine. It will have no bookmarks, no plugins, no history etc. Go to Firefox browser and bookmark the page as shown below Create a New Class -> Selenium_Profiles Run the program where it will open Firefox browser with Google Bookmark as shown in below image Close and Quit Difference driver.quit( ): It will end selenium session and close all browsers in the current session. Suppose we go to a website and click on a link, that link will open in new pop-up and if we fire driver.quit( ), then selenium will close all the browsers and end the selenuim session. driver.close( ): It won’t end selenuim session, but it closes the browser on which current focus is there. Importing Webdriver documentation in eclipse. Go to seleniumhq.org –> Go to download session and click Javadoc link and copy the URL. “http://seleniumhq.github.io/selenium/docs/api/java/index.html” and go to the project -> Right click and go to Properties->Go to Java Build Path and expand the link and click on the Javadoc location: (None). Click on Edit button and paste the URL and remove index.html and click on validate button and click OK button. Webdriver Desired Capabilities Class It helps us understand Selenium, and under which circumstances the script should run. Below example shows how we should run script on Mozilla with Javascript enabled on a windows platform.  
Rated 4.0/5 based on 20 customer reviews

About SELENIUM WEBDRIVER-3

813
About SELENIUM WEBDRIVER-3

Why WebDriver-3?

In present market we have a tool called IDE. It is a tool which works only on Mozilla firefox. It has many drawbacks and doesn’t generate proper reports. IDE is not a preferred tool because sometimes when the scripts run, it finds the locator and sometimes it doesn’t find it and so the script fails. So, to overcome all these challenges we have a tool called WebDriver.

WebDriver works on Multiple browsers like Firefox, IE, Chrome, Safari, Opera etc. It supports multiple languages like Java, C#, Ruby, Python and JavaScript. With WebDriver, we can make dynamic scripts like scripts on Webpages which changes everyday and we can make our scripts run on multiple browsers.

Downloading WebDriver-3 Jars and configuring in eclipse

To start with WebDriver, the first thing we need to do is to download WebDriver Jars and configure it in Eclipse IDE. We need to download Jar files of WebDriver from the official website of Selenium, which is Selenuimhq.org where we need to go to download section and under the download section, we will see the latest version which is 3.4.0. Click on the link and file will be downloaded in the downloads folder.

Also, click on Change log at Selenium website to describe what has changed in the new version. The last 2.x version was 2.53 which is a stable build, meaning it has no major issues. After 2.53, the next build which came up was 3.XX. The changes made in 3.0 is that, minimum java version requires 1.8, where we need to make sure that jdk8 is installed.

Installing Java

  1. To install java, Go to Google and type download Jdk.
  2. Go to first link as shown below

Depending upon the system, we need to install either Windows x32 or Windows x64 bit and accept the License Agreement. For downloading Java, we need to click on Download link, where Zip file will be downloaded on our PC. Go to downloaded folder and extract it and double click on exe. Java will be installed in the system and now we need to configure the class path.

If we are using v2.53.0 version, then we will be needing Firefox 40 or below. In case, we are using 3.0 then we need to go for latest version of Firefox.

Configuring Jar Files in Eclipse

  • Step1: Open Eclipse and make a New Project (ex:Sample)
  • Step2: Right click on the project and select the option Properties as shown below

  • Step3: Go to Java Build Path > Libraries Tab and click on Add External Jars as shown below:

Now, go to the location where we saved our Jar Files and add all the jar files. It will appear like below image after adding all Jar files:

Once we are done with configuring Jar files in eclipse, we can see a folder called Referenced Libraries under Project folder where we have all our Jar Files.

Architecture of selenium webdriver 3

First we need to know a few concepts if we want to understand the working of Selenium WebDriver Architecture.

  1. Language Binding or Selenium Client Library
  2. Selenium API
  3. Remote WebDriver
  4. Json Wired Protocol
  5. WebDrivers
  1. Language Binding or Selenium Client Library : It is nothing but a collection of Jar files, where the language in which we write our selenium framework is present. It means that the language which we used to write the script may be Java, C#, Ruby, Python, perl.
  2. Selenium API : API Stands for Application Programming Interface. API is a particular set of rules and specifications that software programs can follow to communicate with each other. API serves as an interface between software program and facilitate their interaction. API is a software to software interaction which means API works between software to software. With the help of APIs, applications talk to each other without any user knowledge.
  3. Remote WebDriver : It is an implementation class of the webdriver interface that a test script developer can use to execute their test script through webdriver server on remote machine.
  4. JSON:  It stands for JavaScript Object Notation. It is a lightweight data interchange format which helps us to interchange the data. JSON is used to transfer data between client and server on the web. A simple JSON file has .json extension. JSON wired protocol send data in JSON format. Thereafter, the server will firstly parse the data and execute it and after that, response given by the server will be sent back to the client in JSON format.
  5. Webdriver: Webdriver is a tool for automating web applications and verifying that     they work as expected.

 Architecture:

Tester writes script in any language like java, C# etc and selenium client library will communicate with selenium API. Selenium API will send the command taken from language level binding to browser driver with the help of JSON wired protocol and sends the request to Browser Driver, it may be Firefox driver, IE driver, Chrome driver. When we run all the commands we write in the script, it is converted with JSON wired protocol over HTTP and it will convert into URL and the request made by the HTTP and send to the browser. These browser drivers will use the HTTP server for getting HTTP request and these HTTP Server filter out all commands which we need to execute.

Drivers for Firefox, IE, Chrome

  • FirefoxDriver: It is an inbuilt class in Selenium. Lets create a New Class in Eclipse

Class Name: Drivers_Selenium

Inside main function, create an object of FirefoxDriver class like shown below:

FirefoxDriver is an inbuilt class inside Referenced Libraries jars, where we can move mouse over the error and import FirefoxDriver class. After creating the object and running the program, we will get an exception like “The path to the driver executable must be set by the webdriver.gecko.driver system property” like shown in below image.

import org.openqa.selenium.firefox.FirefoxDriver;

public class Drivers_Selenium {

public static void main(String[] args) {

// TODO Auto-generated method stub

new FirefoxDriver();

}

}

Steps to Download Geckodriver exe file:

Step1: Go to seleniumhq.org

Step2: Click on Download Tab

Step3: Click on Mozilla Geckodriver 0.16.1 version in browsers session

Step4: Click on geckodriver-v0.17.0-win64.zip or geckodriver-v0.17.0-win32.zip based upon our operating system.

Open the downloaded folder and extract it, after extracting we will get geckodriver.exe

file like shown below image.

Now there is no need to double click on the geckodriver file, all we need is to set the System property known as “webdriver.gecko.driver” and we have to give the path of  geckodriver exe file. As java is a case sensitive language make sure that “webdriver.gecko.driver” is in lower case.

Run the program where we can see a blank firefox getting opened.

Now we need to give object reference as “FirefoxDriver fd” so that we can use the features of FirefoxDriver object. Inside the documentation of selenium, we find WebDriver interface. Inside this interface, we see a function get( ) which loads the new webpage in the current browser window. It open up a new URL.We can use the function “fd.get ” and get the URL.

Run the above program where we can see the browser launching and it opens yahoo.com

  • ChromeDriver : As the name suggests, it is for chrome. After creating the object and running the program, we will get an exception like “The path to the driver executable must be set by the webdriver.chrome.driver system property”.Now we also need to download an exe file.Go to download session in seleniumhq.org and scroll down where we find Google Chrome Driver link and click on it and it will redirect to the next page. From here we can download based upon our operating system as shown in below image.Whatever be the operating system, whether it is 32xbit or 64xbit, we can download the same file.

Open the downloaded folder and extract it, after extracting we will get “chromedriver” file like shown in the below image.

Now, there is no need to double click on chromedriver file, all we need to do is set the System property known as “webdriver.chrome.driver” and we have to give the path of chromedriver.exe file. As java is a case sensitive language, make sure that “webdriver.chrome.driver” is in lower case.

Run the above program where we can see a blank chrome browser will launch.

Now we need to give object reference as “ChromeDriver ” so that we can use the features of ChromeDriver object. Inside the documentation of selenium, we find WebDriver interface.Inside this interface we see a function get( ) which loads the new webpage in the current browser window. It opens up a new URL.We can use the function “cd.get ” and get the URL.

Run the above program where we can see the Chrome browser launching and open it on yahoo.com

  • IEDriver: As the name suggests it is for InternetExplorer. After creating the object and running the program, we will get an exception like “The path to the driver executable must be set by the webdriver.ie.driver system property”.Now we also need to download an exe file.Go to download session in seleniumhq.org and scroll down where we find IE Driver link and click on it and it will reside to next page from here we can download based upon our operating system, as shown in the below image.What ever be the operating system, whether it is 32xbit or 64xbit, we can download the same file.

Open the downloaded folder and extract it, after extracting we will get “ieDriver” file.

Now no need of double click on iedriver file, all we need is to set the System property known as “webdriver.ie.driver” and we have to give the path of  ie exe file. As java is a case sensitive language, make sure that “webdriver.ie.driver” is in lowercase.

Now we need to give object reference as “IEDriver ” so that we can use the features of IEDriver object.Inside the documentation of selenium, we find WebDriver interface. Inside this interface, we see a function get( ) which loads the new webpage in the current browser window. It opens up a new URL.We can use the function “ie.get ” and get the URL.

Run the above program where we can see the IE browser launching and open it in yahoo.com

  • Launching Browsers Dynamically

Let us Create New Class “Launch Browsers”

Let us build a Testcase. Now our requirement is that we have a parameter called browser. If we write parameter as “Mozilla”, then the script we write in testcase should run in Mozilla browser. If we write a parameter as “Chrome”, it should run on chrome. Later on, we read this parameter from an excel file (xls) or any other file like property file, xml file.

If our browser is Mozilla then below script should execute on Mozilla. If the browser is Mozilla then we want to launch the FirefoxDriver and take this FirefoxDriver to launch our desired website.

In the above example, we keep on repeating the line to launch any website like fd.get(“http://gmail.com”). Later on if we want to click on a link in firefox then we need to write the code for each browsers separately. To overcome this, we use a concept called Interface reference points towards the class implementing the interface.

WebDriver   d = new FirefoxDriver( );

WebDriver   d1= new ChromeDriver( );

Webdriver is an Interface and FirefoxDriver, ChromeDriver, IEDriver are implementing that Interface. Here d1 is  pointing towards chrome, so we can make d1 point towards FirefoxDriver as well , because the reference of the webdriver interface can point towards any implementing class or we can make d1 point towards InternetExplorerDriver as well, like shown below.

d1 = new FirefoxDriver( );

d1 = new InternetExplorerDriver( );

So in the beginning of the program we can write

WebDriver driver  =  null;

Here Null means that driver is not pointing anywhere. So based on our choice, we can make driver point towards FirefoxDriver (or) ChromeDriver (or) InternetExplorerDriver as shown in the below program. Initially driver is “null”. Based on the options, driver will be initialized and we can give the command driver.get(“http://gmail.com”);

All the driver classes will have same set of functions coming from WebDriver Interface,

so “get” function will be there in all the driver classes.

From the above program, we can launch the browser dynamically and we have to write a single script after launching the browser to interact with the browser. We do not need to write browser specific script. The reasons are : firstly all the drivers have same set of functions and secondly, the driver can point towards any of the driver classes like ChromeDriver, IEDriver.

  • Selenium RC and WebDriver

  • What is Firefox profile

Let’s take an example where we have a PC at our place, being shared by two people. If the first person opens the PC and goes to Firefox, then firefox should get opened and it should have 1st person set of settings, his own set of bookmarks, his own set of plugins installed inside it. If a 2nd person opens PC and goes to Firefox, he should have his own set of settings, his own set of bookmarks, his own set of plugins. This concept is know as Firefox Profile.

  • Importance of Firefox profile

First where selenium launches Firefox, we write-

driver  = new FirefoxDriver( );

Selenium will create its own profile and launch the browser. That profile is created programmatically by selenium and it gets destroyed when the script stops.

  • Creating Profile manually on our PC

Go to Firefox browser -> Go to File option and select Exit to close the firefox from the Exit menu, we should not close the firefox from the (x) option on the top as shown in below image.

Go to windows session and type “firefox.exe -p profilemanager”. Copy the command and it will open the window as shown below.

Click on Create Profile and give name as Selenium_Mod11. Click on the Finish button and click Start Firefox button where a new firefox browser will open up and this firefox browser will be like freshly installed firefox on our machine. It will have no bookmarks, no plugins, no history etc.

Go to Firefox browser and bookmark the page as shown below

Create a New Class -> Selenium_Profiles

Run the program where it will open Firefox browser with Google Bookmark as shown in below image

  • Close and Quit Difference

driver.quit( ): It will end selenium session and close all browsers in the current session.

Suppose we go to a website and click on a link, that link will open in new pop-up and if we fire driver.quit( ), then selenium will close all the browsers and end the selenuim session.

driver.close( ): It won’t end selenuim session, but it closes the browser on which current focus is there.

  • Importing Webdriver documentation in eclipse.

Go to seleniumhq.org –> Go to download session and click Javadoc link and copy the URL.

http://seleniumhq.github.io/selenium/docs/api/java/index.html” and go to the project -> Right click and go to Properties->Go to Java Build Path and expand the link and click on the Javadoc location: (None).

Click on Edit button and paste the URL and remove index.html and click on validate button and click OK button.

  • Webdriver Desired Capabilities Class

It helps us understand Selenium, and under which circumstances the script should run. Below example shows how we should run script on Mozilla with Javascript enabled on a windows platform.

 

Raghav

Raghav Globalservices

Blog Author

Raghav has 8+ years of experience with 7+ years of experience in Automation Testing using Selenium, Appium, Ranorex tools etc. in multiple project domains. He is a Consultant &amp; Trainer has trained more than 6000+ US, UK, Russian &amp; Indian students &amp; is a corporate Trainer for several MNCs. <a href="https://www.linkedin.com/in/aroraraghav/" rel="no follow">linkedin.com</a>

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

Useful links