Author name: Prasanna

Page Object Model in Selenium Python | POM in Selenium Python

Page Object Model in Selenium Python | POM in Selenium Python

Selenium Python – Page Object Model

Selenium is an open-source test automation tool. Like other commercial tools in the market, it doesn’t come up with an inbuilt feature to manage object information which we use in creating test scripts. So we need to take the help of design patterns like POM to manage these artifacts. In this chapter, we will understand how to create them and what benefits they bring to the table.

Structure

  • Page Object Model (POM)
  • Implementing the POM • Example of login logout scenario

Objective

This chapter will help us understand the concept of a design pattern called Page Object Model (POM), and how to implement it to make our scripts more robust.

Page Object Model (POM)

Page Object Model (POM) is a design pattern that helps us to separate the object information from the business logic of a page from the application. The idea behind this is, if the object information changes from one build release to another, the business logic is not impacted at the code level, and we only make changes at the object information level. To achieve this we need to implement a POM design pattern at our code level.

Creating Selenium test cases can result in an unmaintainable project. One of the reasons is that too much-duplicated code is used. Duplicated code could be caused by duplicated functionality and this will result in duplicated usage of locator information to identify the objects on a page. The disadvantage of duplicated code is that the project is less maintainable. If some locator will change, you have to walk through the whole test code to adjust locators where necessary.

Implementing the POM

By using the POM we can make non-brittle test code and reduce or eliminate duplicate test code. Besides, it improves readability and allows us to create interactive documentation. Last but not least, we can create tests with fewer keystrokes.
The concept of POM says that when we look at a page, we should see as if it has got two components:

  • Objects
  • Business logic

So the page has a business logic, and to achieve that business objective there are objects available on the page. We need to segregate these two entities. The reason for this is, over a period of time as an application undergoes changes the object information can get changed more frequently, making the maintenance of the code a humongous effort. Let us take an example of the My Account Page here from our application: http://practice.bpbonline.com/catalog/login.php
The business logic of the page says:

  • If there exists a new user, allow them to create a new account.
  • If there is a registered user with valid credentials allows them to log in.
  • If there is a registered user, but who has forgotten credentials, allow them to fetch the password.
  • Not allow a user with invalid credentials to log in.

To achieve these business functions, the page is designed with the following objects:

  • Username textbox
  • Password textbox
  • Sign-in button
  • Continue button

Please find the following screenshot explaining the preceding bullet points:

Selenium Python - Page Object Model chapter 11 img 1

By keeping object information separate from business logic, we are able to manage and achieve modularity and robustness at the code level. As we find during build release cycles, the object information may change over a period of time, so only the files where object information is stored need to be changed, whereas the test logic which is consuming these objects will not get affected by it.

In this chapter, we will see how we will implement POM for the login logout scenario of our application.

from selenium.webdriver.common.by import By

# for maintainbility We can seperate web objects by page name

class mainpageLocators(object):
MYACCOUT    = (By.LINK_TEXT, 'My Account')

class LoginpageLocators(object):
Email       = (By.NAME,   'email_address')
PASSWORD    = (By.NAME,   'password')
SIGNIN      = (By.ID,   'tab1')


class LogoutpageLocators(object):
LOGOFF     = (By.LINK_TEXT, 'log off')
continue   = (By.LINK_TEXT, 'continue')

So, if the object information in any of the upcoming builds changes, we can come to this file, and change the information associated with that object. In another file, called as pages. py we call the action associated with each object:

class Mainpage(page):
    def click_myaccount(self):
        self.find_element(*mainpageLocators.MYACCOUNT).click( )
        return self.driver

class Loginpage(page):
     def enter_email(self, email):
        self.find_element(*LoginpageLocators.EMAIL).send_keys(email)

def enter_password (self,pwd):
    self.find_element(*LoginpageLocators.PASSWORD).send_keys(pwd)

def click_login_button(self):
    self.find_element(*LoginpageLocators.SIGNIN).click( )

def login(self, email,pwd):
    self.enter_email(email)
    self.enter_password(pwd)
    self.click_login_button( )
    return self.driver


class Logoutpage(page):
   def click_logoff(self):
       self.find_element(*LogoutpageLocators.LOGOFF).click()

def click_continue(self):
     self.find_element(*LogoutpageLocators.CONTINUE).click( )

def logout(self):
    self.click_logoff( )
    self.click_continue( )

Now, we will create the test scenarios:

def test_sign_in_with_valid_user(self):
mainpage = mainpage(self . driver)
mainpage . Click_myaccount( )
loginpage=loginpage(self.driver)
loginpage . login("[email protected]","bpb@123")
logoutpage=logoutpage(self.driver)
logoutpage . logout ( )

As we can see, our actual test scenario looks clean, easy to read. Since object information is now hidden in the other files, the test can concentrate on actual test logic.

Conclusion

In this chapter, we learned the importance and need for POM to manage and maintain object information in the form of page objects. This is necessary as Selenium by default doesn’t come with any feature like object repository to manage and maintain object information. POM helps us create modular and robust code.
In our next chapter, we will discuss the concept of Selenium Grid, which as a component, allows us to execute scenarios in parallel.

Related Articles:

Page Object Model in Selenium Python | POM in Selenium Python Read More »

Selenium Python – Introduction to Selenium

Selenium Python Tutorial | Introduction to Selenium

Selenium Python -Introduction to Selenium

Software testing refers to a set of processes and procedures which help us identify whether the product at hand is getting built as per expectation or not. If we find any deviations we log them as defects, and in the subsequent releases we perform regression testing, retest the bugs, and eventually, we are able to release a build to the market with an acceptable bug list. These regression tests, which we have to perform with every release cycle, are mandatory as well as monotonous in nature, which makes them an ideal candidate for test automation.

There are many tools available in the market which allows us to automate our web applications, both commercial and open source. We have tools like UFT, RFT, Silk, Watir, Selenium, and others. Of these, Selenium, which is an open-source functional testing tool for web applications, is the most popular. In this chapter, we will introduce it.

Structure

  • History of Selenium
  • Benefits of Selenium
  • Components of Selenium
  • Architecture of Selenium

Objective

In this chapter, we are going to learn about Selenium as a test automation tool the reason for its popularity. We are also going to learn about the architecture of Selenium to understand how it executes tests on browsers.

History of Selenium

Selenium was created by Jason Huggins, while he was working at Thoughtworks in 2004. It was then called JavaScriptTestRunner. It was used to test an internal time and expense application. It was later released to the open-source community as Selenium. It was named Selenium because it overcame the shortcomings of another competitor that was made by the organization Mercury. Selenium is a chemical is used to treat Mercury poisoning. The main website of Selenium is http://seleniumhq.org/, which is shown in the following screenshot. Here, you will find all the information related to the Selenium tool:

Selenium Python - Introduction to Selenium chapter 1 img 1

There are different tabs on this web page, let’s have a look at what each represents:

• Projects: This tab basically lists the four projects, which make the Selenium tool. The Selenium IDE, Selenium RC, Selenium WebDriver, and Selenium Grid. We will talk in detail about these components in the coming chapters.

• Download: This tab, lists the various download that is required while setting up our system for using the tool.

• Documentation: It provides detailed help that may be required to learn Selenium. It also provides code examples, in different programming languages, which Selenium supports. It is very well written and should be a one-stop solution for all Selenium-related queries.

• Support: The support page provides information on chat, user groups, and the organization that is providing commercial support for the Selenium tool.

• About: The about section talks about news, events, the history of Selenium, and how one can get involved in the Selenium activities.

Benefits of Selenium

Selenium is one of the most popular open-source functional test automation tools for web applications. The reason for its popularity is due to the following:

  • It supports multiple programming languages. You can code in Java, C#, Python, Ruby, and Perl.
  • It supports the automation of multiple browsers like IE, Firefox, Chrome, and Safari.
  • It supports multiple operating systems like Windows, Mac, and Linux.
  • It is available free of cost,
  • It has a strong and active user community, which is very helpful.

Selenium Python - Introduction to Selenium chapter 1 img 2

Components of Selenium

Selenium is not a one-test automation tool, but a group of four different tools, which are listed as follows, along with their usage:
• Selenium IDE: It is a tool used for recording and playing back scripts. It currently supports both Firefox and Chrome browsers. You can procure the tool from this link: https:// www.seleniumhq.org/selenium-ide/

• Selenium RC: It was also known as Selenium 1.0. Although no longer supported, it was a combination of a selenium server and a client, which allowed automation of any browser on any operating system.

• SeleniumWebDriver: Also known as Selenium 2.0, whose 3.0 version is now available. It uses the technology of WebDriver API, where every browser has the capability through its API to automate itself. Currently, the Selenium versions are released through the WebDriver technique of browser automation.

• Selenium Grid: It uses a server component from the Selenium RC, and executes it in two different modes as hub and node. This allows the execution of multiple tests simultaneously, which saves time and cost.

Architecture of Selenium

The main component of Selenium which is used in projects for automation is the Selenium WebDriver. We are going to discuss its architecture, which has four main components, as follows:

  • The client libraries available in different programming languages
  • JSON wire protocol over HTTP for communication to send commands from client to server
  • WebDriver for every browser
  • Browsers: Chrome, Firefox, IE, Opera, and more

The following diagram shows the client libraries that are available in different programming languages. We create our scripts using them. These then send commands to the WebDriver server using the JSON wire protocol over HTTP. The WebDriver for each individual browser
receives these commands and automates the browser, performing the action on them, thus achieving the task at hand:

 

Selenium Python - Introduction to Selenium chapter 1 img 3

Conclusion

As we conclude this chapter, we understand the background of the test automation tool Selenium, its importance, and the reason behind its popularity in the test automation world. In our next chapter, we will be discussing a component of Selenium – the Selenium IDE.

Related Articles:

Selenium Python Tutorial | Introduction to Selenium Read More »

Build A Selenium Python Test Suite From Scratch Using Unittest

Build A Selenium Python Test Suite From Scratch Using Unittest

Selenium Python – Unittest in Python

Most of the high-level programming languages have a unit test framework associated with them. Like Java has JUnit, .Net has NUnit. Similarly, Python has PyUnit or unit test associated with it. It was created by Kent Beck and Erich Gamma. The unit test framework supports test automation, with the help of text fixtures. We will learn more about it in this chapter.

Structure

  • What is a unit test?
  • Structure of unit test
  • Writing first unit test
  • Adding assertions in the test

Objective

When we are writing our test scripts, it is important that we structure them with the help of a unit test framework. The Python programming language makes the available unit tests, which is the unit test framework. In this chapter, we will understand how we use it to structure our code and write scripts.

The most unit and their structure

The unit test is the unit testing framework in Python. Its features are inspired by JUnit, which is a unit testing framework for the Java programming language. Applying a unit testing framework at the code level helps us introduce structure to our code. It also ensures
that we can add assertions in the test code, which we require as we are writing test automation scripts.

In a general unit test case, the class which we create is derived from a unit test.TestCase. We can have a set)p() andatearDown()
method there. In the setup () method, we generally write code that helps in preparing the system and test environment. And in the
tearDown () method, we write scripts to clean up the environment. In between these methods, we have our functions which are where the
code to actually test is created. These functions are written using the test_ prefix. We then execute the tests by calling unit tests.main()
the method at the end of the file.

A unit test contains the following important entities:

  • Test fixture: It expresses the process to execute the test, followed by a clean-up action.
  • Test case: It is the basic unit of testing.
  • Test suite: It is a collection of test cases.
  • Test runner: A test runner manages the execution of the test and presents the result to the user.

Let us see an example of a script for login logout, where we will be applying unit test:

from selenium import webdriver
import unittest

class login(unittest.Testcase):
      def setup(self):
      self.driver=webdriver.chrome(executable_path="D:\Eclipse\BPB\seleniumpython\seleniumpython\drivers\chromedriver.exe")
      self.base_url = "http://practice.bpbonline.com/catalog/index.php"

def test_login(self):
    driver = self.driver
    driver.get(self.base_url)
    driver.find_element_by_link_text("My Account").click( )
    driver.find_element_by_name("email_address").clear( )
    driver.find_element_by_name("email_address").send_keys("[email protected]")
    driver.find_element_by_name("password").clear( )
    driver.find_element_by_name("password").send_keys("bpb@123")
    driver.find_element_by_id("tab1").click( )
    driver.find_element_by_link_text("log off").click( )
    driver.find_element_by_link_text("continue").click( )

def tearDown(self):
    self.driver.quit( )

if_name_=="_main_":
    unittest>main( )

So in the preceding script, we see the automation test is structured in different sections.

• set up ( ): In this, we generally put statements to initialize the browser. Invoke the WebDriver object with the URL we would like to launch.

• test_login( ): In this method, we have written the steps to perform the actual test on the application. Please note that we have not added any assertion action yet. We will see that in the next section.

• tearDown( ): This is the cleanup method. In this, we generally put action to clean up the environment. So here, we have written the statement to close the browser.

Once the structure is complete, we execute the tests by calling the unit test.main( ) method.

Assertions

Assertions are ways to validate our actions. The PyUnit provides us the following set:

Assert methodExplanation
assertEqual(a, b)a == b
assertNotEqual(a, b)a != b
assertTrue(x)bool(x) is True
assertFalse(x)bool(x) is False
assertls(a,b)a is b
assertlsNot(a, b)a is not b
assertlsNone(x)x is None
assertlsNotNone(x)x is not None
assertln(a, b)a in b
assertNotln(a, b)a not in b
assertlslnstance(a, b)isinstancefa, b)
assertNotlsInstance(a, b)not isinstnacefa, b)
assertRaisesfexc, fun, args, *kwds)fun(*args, **kwds) raises exc
assertRaisesRegexpfexc, r, fun, args, *kwds)round(a-b, 7) == 0
assertAlmostEqual(a, b)round(a-b, 7) == 0
assertNotAlmostEqual(a, b)round(a-b, 7) != 0
assertGreater(a, b)a > b
assertGreaterEqual(a, b)a >= b
assertLessfa, b)a < b
assertLessEqual(a, b)a <= b
assertRegexpMatches(s, r)r.search(s)
assertNotRegexpMatchesfab)not r.search(s)
assertltemsEqual(a, b)sorted(a) == sorted(b) Works with unhashable objects
assertDictContains Subset(a, b)All the key-value pairs in a exist in b

We will now see a test automation script of login logout where we will use assertion to validate- valid user login, by checking the presence of text My Account Information.

def test_login(self):
    driver=self.driver
    driver.get(self.base_url)
    driver.find_element_by_link_text("My Account").click( )
    driver.find_element_by_name("email_address").clear( )
    driver.find_element_by_name("email_address").send_keys("[email protected]")
    driver.find_element_by_name("password").clear( )
    driver.find_element_by_name("password").send_keys("bpb123")
    driver.find_element_by_id("tab1").click( )
    pgsrc=driver.page_source
    if(pgsrc.index("My Account Information")>-1):
       print("user is valid")
       driver.find_element_by_link_text("log off").click( )
       driver.find_element_by_link_text("continue").click( )
       self.assertTrue(True,"User is valid")
else:
    print("User is Invaild")
    self.assertFalse(False, "User is invalid")

In the preceding script, we can see usage of self .assertTrue() and self .assentFalse() statement to mark the test pass or fail depending on the presence of the text My Account Information.

Conclusion

So in this chapter, we have seen how can we use the unit test framework to structure our test in setUp(), test_method(), and teardown() methods. We have also seen, how we can use assertions to mark our test as pass and fail. You can follow this link if you want to read more about it- https://docs.python.0rg/3/library/unittest.html.

In the next chapter, we will be discussing the concept of waits. We will see how we can synchronize our tests using static and dynamic waits and why is that important.

Related Articles:

Build A Selenium Python Test Suite From Scratch Using Unittest Read More »

Selenium Webdriver Tutorial with Examples | Understanding WebDriver, WebElement

Selenium Python – Understanding WebDriver, WebElement

In this chapter, we will introduce the entities WebDriver, WebElement, and By of the Selenium module. The WebDriver refers to the browser object. The WebElement refers to the HTML elements on the page. The By helps us create the locator objects on the page. So let us understand how are they used, and what all methods are associated with them.

Structure

  • WebDriver
  • WebElement
  • By

Objective

The Selenium module of Python programming language contains three crucial entities—WebDriver, WebElement, and By. The WebDriver helps us automate the browser object and has methods for it. The WebElement helps us automate the HTML element on the page, and has methods to perform an action on them. The By class helps us locate objects using different locator strategies supported by Selenium, like ID, name, XPATH, and others.

Introduction to Selenium module

The Selenium module in Python contains three important entities, WebDriver, WebElement, and By. In the following table, it shows us the relation of these entities with our objects of automation

The following table shows their relation to the web entity:

WebDriverBrowser
WebElementHTML element
ByLocator to identify the element on the page

Let us understand these entities in more detail.

WebDriver

The WebDriver object refers to the browser. It controls the browser by sending commands to the browser via the JSONWireProtocol. The details of this protocol are available here: https://github.com/Se- leniumHQ/Selenium/wiki/JsonWireProtocol. Any implementation of WebDriver for automating any browser will have to abide by this. Let us have a look at the few methods available which help in browser actions:

MethodsDescription
get(url)Opens a web page with the given URL.
findElement(By)This method takes a By object as an argument and finds the object on the web page which matches that locator. It returns the first found match.

In Python we have find_element_by_id, find_ element_by_name,                                                    find_element_by_xpath methods to locate elements.

findElements(By)This method returns a list of all elements which match the locator value provided by the By object on the web page.
Forward( )This command will take you to the next page.
back()This command will take you to the previous page.
page_sourceThis command will return the entire HTML content of the page.
TitleReturns the current title of the page.
current_urlReturns the current URL of the page.
CloseClose the current instance of the browser.
QuitClose the current instance of the browser and all the associated windows.

WebElement

The WebElement object refers to the HTML element on the web page. All methods that interact with the DOM will work through this interface. Before the implementation of any method, it does a freshness check to ensure if the element is still valid, and only then it acts. If the element reference is not valid it throws StaleElementReferenceException. Let us have a look at some of the methods available with this interface:

MethodsActions
click()It performs click operation on a web element.
clear()It performs a clear operation on a web element.
get_attribute()This method returns the data associated with the property of the HTML element at the time of execution. For example, you can fetch the href attribute with an anchor element.
is_displayed()Returns true, if the element is visible to the user.
is_enabled()Returns true, if the element is enabled.
is_selected()Returns true, if the element is selected, for example, a radio button is selected.
send_keys()It allows typing of text on an element, generally a textbox.
TextIt fetches the text associated with the HTML element.

By

The By class of Selenium allows us to locate the web element on the page. It uses the following strategies:

  • ID
  • NAME
  • XPATH
  • CSS_SELECTOR
  • TAG_NAME
  • LINK_TEXT
  • PARTIAL_LINK_TEXT
  • CLASS_NAME

To locate the element on a web page we use the find_element_by_* method, where the * replaces any of the preceding locator strategies to find the element on the web page.

Now let us try to write down the script for the scenario of login-logout using the methods we have learned above for these entities. The steps for the login-logout for our application are as follows:

  1. Open the application with URL: http://practice.bpbonline. com/catalog/index.php
  2. Click on the My Account link.
  3. Type email address and password.
  4. Click the Sign In button.
  5. Click the Log Off link.
  6. Click the Continue link.

We have learned in earlier chapters that a link is to be identified by its link text which we see on the screen. To identify the username, we can use the name property having the value email_address, the password field has the name property password, and the sign-in button has an id property table, as you can see in the HTML of its page:

<table border="0" cellspacings="0" cellpadding="2" width="1001">
 <tr>
  <td class="fieldkey"> E-mail Address:</td>
  <td class="fieldvalue"><input type="text" name="email_address"/></td>
 </tr>
 <tr>
  <td class="fieldkey">password:</td>
  <td class="fieldvalue"><input type="password" name="password" maxlenght="40" /></td>
 </tr>
</table>
<p><a href="http://practice.bpbonline.com/catalog/password_forgotten.php">password forgotten? click here.</a></p>
<p align="right"><span class="tablink"><button id="tab1" type="sbmit">sign Inc/button></span><script>

Let us now write the steps to automate the above scenario.

So in the following code, we are clicking on the MyAccount link, then typing the email address and password. Then we click on the Sign In button, and if our credentials are valid we should be able to login into the application. Then we click on the Log Off link and click on the Continue link to complete the process.

from selenium import webdriver

browser = webdriver.chrome(executble_path='D:\Ecl.ipse\BPB\seleniumpython\seleniumpython\drivers\chromedriver.exe')
browser.get('http://practice.bpbonline.com/catalog/index.php')
browser.find_element_by_link_text("My Account").click()
browser.find_element_by_name("email_address").send_keys("[email protected]")
browser.find_element_by_name("password").send_keys("bpb@123")
browser.find_element_by_id("tab1").click( )
browser.find_element_by_link_text("tab off").click( )
browser.find_element_by_link_text("continue").click( )
browser.quit( )

Conclusion

In this chapter, we learned how Selenium WebDriver helps automate the browser, identify the element on a web page and perform actions on it. The above test script can be executed on Firefox and Internet Explorer browsers by changing the executable path to their respective WebDrivers. The rest of the test script looks exactly the same. We understood the different methods associated with the WebDriver object, WebElement object, and the By locator object, which allows objects to be identified using different locator strategies.

In the next chapter, we will see how we can structure our Selenium scripts using PyUnit tests. We will study the unittest framework, which has derived its features from the JUnit and NUnit framework.

Related Articles:

Selenium Webdriver Tutorial with Examples | Understanding WebDriver, WebElement Read More »

How To Locate Different Web Elements in Selenium Using Python?

Selenium Python – Working with Different WebElements

An HTML page is made up of various HTML elements. When we automate a web page using Selenium, we first have to identify the HTML element uniquely on the web page and then perform an action on it. An HTML page can have HTML elements like a form, frame, table, dropdown, link, image, alerts, divs, spans, and many more. In this chapter, we will learn how to automate these elements through Selenium.

Structure

  • Working with form elements
  • Working with HTML table
  • Working with dropdown list

Objective

An HTML page is made up of different HTML elements, for example, we see a form element, which contains a lot of input elements. The input elements could be a textbox, radio button, or checkbox. We can then have a table element, a dropdown element. In this chapter, we will see how we can automate these HTML elements.

Working with form elements

An HTML form generally contains text boxes, buttons, links, images, radio buttons, and checkboxes type of elements. The HTML of the input elements in the form is represented as follows:
<input type= “text/checkbox/radio/password property=value../>

The following table shows the different actions we generally perform on these elements using Selenium:

Web Element

Selenium action

Description

Text boxClearClears the content of the text box.
Text boxSend_keysTypes content sent in the method in the text box.
CheckboxClickTo select a given check box.
Radio buttonClickTo select a given radio button.
AnchorclickTo click on the link element.
ButtonclickTo click on the button in the form.
ButtonsubmitIf the button provided is a submit button, then we can perform the submit action on it.
Radio buttonTo verify if the radio button is selected,
HTML elementThis method will work for any HTML element, and it checks if the element is displayed on the page or not.
HTML elementIs EnabledThis method will work for any HTML element, and it checks if the element is enabled on the page or not.

TableExarapli

An example of working on the form elements described above can be seen on the registration page of the application: http://practice. bpbonline.com/catalog/create_account.php

On this page, we can see the checkbox, radio button, text boxes, buttons, links on which we can work. The following program displays the process of user registration by performing actions on the different web elements on this page:

def text_login(self):
browser=self.driver
browser.find_element_by_link_text("My Account").click()
browser.find_element_by_link_text("continue").click( )
browser.find_element_by_name("gender").click( )
browser.find_element_by_name("firstname").send_keys("BPB")
browser.find_element_by_name("lastname").send_keys("BPB")
browser.find_element_by_id("dob").send_keys("01/01/1987")
#change	email id with each iteration
browser.find_element_by_name("email_address").send_keys("[email protected]")
browser.find_element_by_name("company").send_keys("5Elements learning")
browser.find_element_by_name("strret_address").send_keys("second Address")
browser.find_element_by_name("suburb").send_keys("second Address")
browser.find_element_by_name("postcode").send_keys("110001")
browser.find_element_by_name("city").send_keys("new delhi")
browser.find_element_by_name("state").send_keys("delhi")
sel=select(browser.find_element_by_name("country"))
sel.select_by_visible_text("India")
browser.find_element_by_name("country")
browser.find_element_by_name("telephone").send_keys("1234567890")
browser.find_element_by_name("fax").send_keys("0123456789")
browser.find_element_by_name("newsletter").click( )
browser.find_element_by_name("password").send_keys("123456")
browser.find_element_by_name("confirmation").send_keys("123456")
browser.find_element_by_xpath("//span[contains(text(),'continue')]").click( )
browser.find_element_by_xpath("//span[contains(text(),'continue')]").click( )
browser.find_element_by_link_text("log off").click( )
browser.find_element_by_link_text("continue").click( )

So in the preceding code, we are registering a new user in the application by handling actions on all the mandatory fields. So wherever there are textboxes, we have ensured they are cleared first, and then we type the text on them. For links, buttons, and radio buttons, we have used the click method for selecting them.

Working with HTML tables

The HTML tables are container elements, which mean they contain other HTML elements inside them. A general representation of HTML table is as follows:

<table>
<tbody>
<tr>
<td> text/HTML element</td>
<td> … </td>
</tr>
<tr>…</tr>
</tbody>
</table>

So we have the first node as a table, which contains a body, which contains table row[tr]. The tr node contains table data[td] which represents the table cell. The table cell can contain text or any HTML element within it. In our application, the home page displays the products listed in a web table:

 

Selenium Python - Working with Different WebElements chapter 9 img 2

Let us look at the backend HTML available:

<table border="0" width="100%" cellspacing="0" cellpadding=2">
  <tbody>
    <tr>
     <td width="33%" align="center" valign="top">
       <a href="http://practice.bpbonline.com/catalog/product info.php?
       products id=20">...</a>
        <br>
        <a href="http://practice.bpbonline.com/catalog/product info.php?
        products id=20">Beloved</a>
        <br>
       "$54.99"
      </td>
      <td width="33%" align="center" valign="top">...</td>
      <td width="33%" align="center" valign="top">...</td>
   </tr>
   <tr>...</tr>
   <tr>...</tr>

 

As we see in the preceding HTML snippet, the table has three tr tags, and each tr tag has three td tags. Each td tag has two anchor tags and a text, which we see on the page. One of the scenarios we pick for HTML web table automation is to find the rows and columns available in the table at run time. Here, we will be doing that, and printing the content available in every table cell as we iterate the table row by row and cell by cell.

from selenium import webdriver
import unittest

class TableExample(unittest.Testcase):
    def setup(self):
        self.driver = webdriver.chrome(executable_path='D:\Eclipse\BPB\seleniumpython\seleniumpython\drivers\chromedriver.exe')
        self.driver.implicitly_wait(30)
        self.base_url = "http://practice.bpbonline.com/catalog/index.php"
   def test_table(self):
       driver = self.driver
       driver.get(self.base_url)
       prodTable= driver.find_element_by_tag_name("table")
       #Fetch rows
       rows=prodTable.find_elements_by_xpath("//"/tbody/tr")
       i=1
       for r in rows:
           #Fetch colc for each row
           cols=r.find_elements_by_xpath("td")
           #print(for(path))
           j=1
           for cd in cols:
               print("row ", i, "col", j, ",", cd.text)
               j=j+1
          i=i+1
   def tearDown(self):
       self.driver.quit()        
if_name_=="_main_";
unittest.main()

 

So in the preceding code, we first fetch the table object, then in that table object, we fetch all the table rows. Then we iterate each table row and fetch all table columns from each row. Then we iterate each table column, and fetch the text associated with each table cell, and print that information on the screen.

As we run the test, the output is as follows: col: 1 – Fire Down Below

 

Selenium Python - Working with Different WebElements chapter 9 img 5

Working with dropdown list

The dropdown list in HTML is known as the < select > element. It is also a container element. It contains <option> elements. The option element displays the different choices of the dropdown which can be selected from it. The HTML code of dropdown looks as follows:

<select>
(option value = data> Visible text </option>
. .
</select>

In our application, dropdowns are available on various pages. The dropdown element which we will see in the example is the country dropdown which we see on the registration page of the application:

 

Selenium Python - Working with Different WebElements chapter 9 img 6

If we look at the backend HTML of this dropdown, we will see the following:

<select name="country">
  <option value selected="selected">please select</option>
  <option value="1">Afghanistan</option>
  <option value="2">Albania</option>
  <option value="3">Algeria</option>
  <option value="4">American</option>
  <option value="5">Andorra</option>
  <option value="6">Angola</option>
  <option value="7">Anguilla</option>
  <option value="8">Antarctica</option>
  <option value="9">Antigua and Barbuda</option>
  <option value="10">Argentina</option>
  <option value="11">Armenia</option>
  <option value="12">Aruba</option>

 

The number of options in the list will be the same as we see on the screen.

To work with a dropdown element, Selenium provides a separate class called Select. More details on this class can be found on this link:

https://seleniumhq.github.io/selenium/docs/api/py/
webdriver_support/selenium.web driver.support.select.
HTML?highlight=select#selenium.web driver.support.select

The Select class allows us to select an element from the list using the following three methods:

• select_by_value: In this method, we select an option
bypassing the data associated with the value attribute. For example in the previous list, if we say select_by_ value(” 5″), Andorra as a country will get selected.

• select^Y-Visi-ble^ext: In this method, we select an
option bypassing the data which we see on the screen. For example, if we want to select the country Angola, we can say select_by_visible_text(“Angola”).

• select_by_index: In this method, we select an option from the list, bypassing an index value. The index value associated with the options in the list ranges from 0 to the total number of options -1. So if we say select_by_index(2), Albania will get selected.

Similar to the preceding set of methods, we have select by value, visible text, and index. In the following program:

def text_dropdown(self):
    browser=self.driver
    browser.get(self.base_url)
    browser.maximize_window()
    browser.find_element_by_link_text("My Account").click( )
    browser.find_element_by_link_text("Account").click( )
    sel=select(browser.find_element_by_name("country"))
    #select by visible text
    sel.select_by_visible_text("India")
    print(sel.first_selected_option.text)
    time.sleep(1)
    #select by index
    sel.select_by_index(1)
    print(sel.first_selected_option.text)
    time.sleep(1)
    #select by value
    sel.select_by_value("5")
    print(sel.first_selected_option.text)
    time.sleep(1)

#find an option in the list
for country in sel.options:
    if(country.text=="India"):
       print("country found")

 

In the preceding program, we try different methods to select options from the dropdown element. We use a method called first_ selected_option, which returns the option that was selected first and foremost in the list.

Conclusion

So in this chapter, we have seen how to handle different types of form elements, web table elements, and the dropdown element. We saw the different methods that are available with these entities. We also saw the different actions which can be performed on the HTML elements during test automation runs. In the next chapter, we will discuss the switch To method, and see how we can handle frames, alerts with it. We will also see the action class which allows us to handle various keyboard, mouse actions, and also automate composite actions.

Related Articles:

How To Locate Different Web Elements in Selenium Using Python? Read More »

How to install Selenium in Python | Installing Selenium WebDriver Using Python and Chrome

Selenium Python – Installation and Setup

In this chapter, we will learn how to prepare our system with the required software so that we are able to write our test automation scripts and execute them. We will note to have Python, Java Runtime Engine (JRE), Eclipse IDE, PyDev. After setting up this software for creating scripts, we will need to set up Selenium in the system and download the browser drivers for execution on the individual drivers.

Structure

  • Installation and setting up
  • Installing Selenium Python module
  • Installing JRE
  • Installing Eclipse IDE
  • Setting up PyDev
  • Installing different drivers for Chrome, Firefox, and IE browser
  • Running the very first program on three browsers

Objective

This chapter will help us to understand the steps to setup Selenium and Eclipse IDE on the Windows system

Installation and setting up

Before we start to learn to write scripts to automate browsers using Selenium WebDriver, we have to prepare our system with a few software. We will require the following:

  • Python setup: https://www.python.org/downloads/
    [download the latest version] [3.7]
  • Java JRE: https://www.oracle.com/technetwork/Java/Javase/ downloads/jre8-downloads-2133155.html, and install it on the system.
  • Eclipse IDE: https://www.eclipse.org/downloads/

After we have installed and set up the above software in our system, we need to install PyDev in the Eclipse environment. To setup PyDev in the Eclipse environment, we have to perform the following actions:

  1. Open Eclipse.
  2. Click on Help | Install New Software. ;
  3. Provide in there, URL: http://pydev.org/updates

The following screenshot shows the same:

Selenium Python - Installation and Setup chapter 4 img 1

Now the Eclipse environment is ready to create Python projects and understand Python syntax as well. The next step is to install the Selenium Python module.

Installing Selenium Python module

The modules of Python are available on the website (http://www. pypi.org). From here, we will search the module for Selenium and use the pip install command.
1. Open the URL: https://pypi.org/project/selenium/
The above URL provides information about the Selenium module of Python, the command to install it, and the documentation available with it.
2. To install the module, open the Command Prompt and type pip install selenium, shown as follows:
SSI Command Prompt

Microsoft Windows [version 10.0.17134.706]
(c) 2018 Microsoft corporation. All rights reserved.

C:\users\write>pip install selenium

3. The preceding command will install the Selenium Python module, and the environment will now be ready to accept Selenium commands to automate the browser.

Creating Python project in Eclipse

We will now perform the steps to create a Python project in Eclipse and write down our first script to open the browser with the URL of our demo site application and close it. We will perform it for all three browsers: Internet Explorer, Firefox, and Chrome.
Let’s see in a step-by-step manner:
1. Go to File | Create New Project. In that window, select PyDev project. Refer to the following screenshot:

Selenium Python - Installation and Setup chapter 4 img 3

2. Provide a name to the project, select Python interpreter, it is advisable to choose Quick Auto Config. Refer to the following screenshot:

Selenium Python - Installation and Setup chapter 4 img 4

3. Click on Next, and then Finish. Eclipse may ask you to open the Python perspective, select Yes.

We are now ready to write down scripts in Python to automate the browsers.

Automating Chrome browser

To automate the Chrome browser, we first need to download the Chrome driver. Depending on the Chrome browser version we have on our system, and the operating system we are using, we need to download the suitable driver. It is advisable to ensure that you have the latest version of the browser.
1. To download Chrome driver, visit the link:
http://chromedriver.chromium.org/downloads
2. Drivers are available as per the operating system type for download:

Selenium Python - Installation and Setup chapter 4 img 5

3. Here, we are taking an example of the Win32 system. So we download the Win32 ChromedriverZIP folder and extract the. exe file from it.
4. In Eclipse, where we create our project, we create a folder there, called drivers. We copy this chrome driver. exe file into that folder. So finally our project would look as follows:
I MG

Writing the first script

We will now write our very first script to automate the Chrome browser, where we will launch the browser, open the application, and then close the browser.

Selenium Python - Installation and Setup chapter 4 img 6

Let us understand the above script. The first statement from the Selenium import web driver will import Selenium classes in the file. This will allow usage of the Selenium commands in the script. So basically, we can create an object of WebDriver, and call different methods associated with it to handle the browser. It will fail if the Selenium module is not imported. The next statement initializes the browser object by creating an instance of the Chrome object and passing the path of the executable driver. With the Selenium WebDriver, every browser requires its own WebDriver to automate them.

The get method allows the browser to be launched with the URL that has been provided, and the quit method closes all the instances of the browser opened from this script.

Automating Firefox browser

To automate the Firefox browser, we need to download the gecko driver. The geckodriver is the API which allows us to automate the Firefox browser. It acts as a bridge between Selenium and the browser. Flere as well, we need to select the driver version based on the operating system and the Firefox version. To download the driver, we need to visit the link: https://github.com/mozilla/ geckodriver/releases

Select the driver according to your system; here we select for win64 from the following list:

Refer to the following script:

from selenium import web-driver

browser =webdriver.Chrome (executable_path=r \Ectipse\BPB\seleniumpython\Selenim&thPython\drivers\chromedriver.exe}
browser.get{'http://practice. bpbonline,com/catolog/index.php'}
browser.quit()

Once we download the geckodriver for win64, we extract the geckodriver. exe file from the zip folder and put it in the driver’s folder in the Python project of Eclipse. Now we are ready to create the script which will open the application on the Firefox browser and close it:

Selenium Python - Installation and Setup chapter 4 img 8

Automating Internet Explorer

To automate the Internet Explorer browser, we have to download the IEdriverserver. exe file. This file is available on the https://www. seIeniumhq.org/download/ website.

Depending upon the operating system we are using, we will download that particular IE driver. Once the. exe file is downloaded, we will save it in the driver’s folder of our project, and write the following script to open the application in the IE browser:

The Internet Explorer Driver Server

This is required if you want to make use of the latest and greatest features of the WebDriver IntemetExplorerDriver, Please make sure that this is available on your $PATH (or %PATH% on Windows} in order for the IE Driver to work as expected.

Download version 3.14.0 for (recommended) 32 bit Windows IE or 64 bit Windows IE CHANGELOG

Conclusion

So, in this chapter, we have learned how to set up our system, create projects and automate the three browsers. The official documentation of Selenium Python bindings is available here: https://seleniumhq. github.io/selenium/docs/api/py/index.html
Now our system is ready for us to write down our Selenium tests for the multi-browser support available with Python programming languages, aiding the manual testers by automation and reducing the workload. In our next chapter, we will learn how to work with different types of WebElements, understand the concept of synchronization, and parameterization, which forms the basic building blocks for automation.

Related Articles:

How to install Selenium in Python | Installing Selenium WebDriver Using Python and Chrome Read More »

Selenium Python – Frames, Alerts, and Action Class

Selenium Python – Frames, Alerts, and Action Class

In this chapter, we will learn about the concept of the switch to( ) command associated with the driver object. Many times we come across applications that have a frame in them, if we have to handle the objects in a frame we need to first switch to the frame, and only then can we work on the objects of the page in the frame. Another usage of the switch is seen in handling alerts, JavaScript pop windows, which come up to ask for yes or no / ok and cancel decisions, to proceed. And lastly, we are going to talk about the action class, which allows us to automate various mouse and keyboard movements. It also allows us to automate composite action class.

Structure

  • Working with frame
  • Working with alerts
  • Action class

Objective

The WebDriver element has a method called switch to( ). This method allows switching the focus to a frame, an alert, or a new window. In this chapter, we will see its usage. Another entity we will see is the Action class. This is used to automate keyboard and mouse actions. Sometimes, we may come across composite actions, and in those situations, actions class is helpful.

Working with frame

A frame HTML element allows us to break an HTML window into multiple sections, where each section can contain its own HTML page. A frame tag is represented inside a frameset tag and looks like the following:

<frameset>
<frame name=”topframe” src=”topframe.htm”>
<frame name^’hot-frame” src=”botframe.htm”>
</frameset>

If we have to work with the HTML element which is available in the web page that lies inside a frame, we need to switch to the frame first, and only then we can interact with the HTML elements of the page inside the frame. To perform this task we need to use the switch_ to() command, using some attribute to identify the frame which contains the element. Let us take the following example of a page that contains nested frames: http://the-internet.herokuapp.com/ nested_frames.

If we look at the backend HTML of the page, we will find that the page contains a top frame and a bottom frame. The top frame further contains three frames: left, middle, and right. The following screenshot shows the frames HTML:

<frameset frameborder="1" rows="50%,50%">
  <frame src="/frame top" scrolling="no" name="frame-top">
   #document
    <html>
       <script src="chrome-extention://cdmedbnojkdahhdbjnemegb1hbaa1kbc/page/prompt.is">
       </script>
       <script src="chrome-extention://cdmedbnojkdahhdbjnemegb1hbaa1kbc/page/prompt.is"
       </script>
       <head>...</head>
       <frameset frameborder="1" name="frameset.middle" cols=*33%,33%,33%">
         <frame src="/frame left" scrolling="no" name = "frame=left">...</frame>
         <frame src="/frame middle" scrolling="no" name = "frame=middle">...</frame>==$o
         <frame src="/frame right" scrolling="no" name = "frame=right">...</frame>
    </frameset>
   </html>
  </frame>
<frame src="/frame bottom" scrolling="n0" name="frame-bottom">...</frame>

Now, let us suppose that in the preceding example we need to fetch the text associated with the page inside the middle frame, so how will we do that? To achieve this we will first need to switch to the top frame, and then from it, switch to the middle frame. Once we have switched to the middle frame we can fetch the text associated with it. The following program shows the working of the same.

from selenium import webdriver
import unittest

class FrameExample(unittest.TestCase):
     def setup(self):
         self.driver=webdriver.chrome(executable_path="D:\Eclipse\workspace\seleniumpython\seleniumpython\drivers\chromedriver.exe")
         self.driver.implicity_wait(30)
        self.base_url="http.ss//the.internet.herocomp.com/test_frame(self):

def test_frame(self):
    driver = self.driver
    driver.get(self.base_url)
    driver.switch_to_frame(driver.find_element_by_name("frame.top"))
    driver.switch_to_frame(driver.find_element_by_name("frame.middle"))
    print(driver.page_source)

def tearDown(self):
    self.driver.quit( )

if_name_ =="_main_":
   unittest.main( )

In the preceding program, we switch our focus to the first frame which is recognized by the name property frame-top, and then we switch our focus to another frame inside it which is recognized by the name property frame-middle. Once we have switched focus to the inner frame, we print the page source of it.

The output which we get when we run the program is as follows:

<html xmlns="http://www.w3.org/1999/xhtml"><head>
     </head>
     <body>
        <div id="content">MIDDLE</div>


</body></html>

Working with alerts

Alerts are JavaScript popup windows that prompt the user for an action or decision based on which an event is performed, or it displays some information to the user. For example, in our web i application http://practice.bpbonline.com/catalog/index.php, when we try to register the user, and while filling in the registration form, if we forget to fill in some mandatory field and we try to proceed with the process, we will see an alert prompting us to correct our entries.

Selenium Python - Frames, Alerts, and Action Class chapter 10 img 4

Now to handle the preceding alert we have to click on the OK button. To perform the action we have a class available in Selenium called the Alert class. The details of it are available here: https://seleniumhq. github.io/selenium/docs/api/py/webdriver/selenium.webdriver. common.alert.html. This Alert class has four methods:

  • accept (): It accepts the alert by clicking on the OK button.
  • dismiss( ): It cancels the alert by clicking on the cancel button.
  • Send_keys: It sends keys to the alert.
  • Text: It fetches the text associated with the alert.

In the scenario from our application which we try to automate the user registration process. Here, we will first pass a bad combination of passwords and confirm passwords. This will cause the alert to popup:

Selenium Python - Frames, Alerts, and Action Class chapter 10 img 5

So, we use the Alert class here, and its method accepts to handle it, as can be seen in the following code snippet:

#bad password and confirm password
browser.find_element_by_name("password").send_keys("123456")
browser.find_element_by_name("confirmation").send_keys("1234")
browser.find_element_by_xpath("//span[@class='ul-button-text'][contains(	text(), 'continue')]").click( )
time.sleep(3)
alert=browser.switch_to_alert( )
print(alert.text)
alert.accept( )#press ok button
time.sleep (3)
#provide correct owd and confirm owd
browser.find_element_by_name("password").clear( )
browser.find_element_by_name("password").send_keys("123456")
browser.find_element_by_name("confirmation").clear( )

The complete code of the preceding snippet is available in the codebase.

Action class

Selenium provides us with an action class, inits Python implementation is known as action chains. This class helps us to handle low-level keyboard and mouse actions as well as complex actions like drag and drop, mouse hover, and more. Using the Action class, you can either call one action at a time, or you can queue up the actions one after another and then use a method called as perform() to call them in order. We will take an example here for a website to perform drag and drop action. This example will also showcase the usage of frames.

So the website we will be using here is: http://jqueiyui.com/ droppable/
There are two objects, where the left one has to be dropped on right. Refer to the following diagram:

Selenium Python - Frames, Alerts, and Action Class chapter 10 img 7

As we inspect the element, we will find that these elements are inside the iframe tag. Let us have a look:

<iframe src="/resource/demos/droppable/default.html" class="demo-frame">
  #document
    <!doctype html>
    <html lang="en">
      <head>...</head>
      <body>
       <div id="draggable" class="ui-widget-content ui-draggable ui-draggable-handle" style="position: relative;">...</div>
       <div id="droppable" class="ui-widget-header ui-droppable">...</div>
     </body>
   </html>
 </iframe>

We want to drag the left object and drop it on the right object. The following code shows how we can do that:

driver=self.driver
driver.get(self.base_url)
actions = ActionChains(driver)
driver . switch_to_frame(driver.find_element_by_class_name("demo-frame"))
draggable=driver.find_element_by_id("draggable");
draggable=driver.find_element_by_id("draggable");
actions.drag_and_drop(draggable, droppable).perform( ):
time.sleep(3)

In the preceding program, we first switch to the iframe which contains the draggable and droppable objects. We then recognize the objects using their ID properties. Once the objects are created, we use the method available with the Action class, drag_and_drop(), which performs the required action and solves the scenario.

So to use the ActionChains class, we have to import it as well, so the following would be our import modules:

from selenium.web driver. common.action_chains import ActionChains

Conclusion

In this chapter, we saw how we will handle the frame HTML element, by using the switch command. Also, if we come across the JavaScript popups, how do we handle them using the alert interface available in Selenium. If we come across scenarios in applications that require composite actions like click and hold, drag and drop, double click, context-click, we have with us Action class, which we can use to handle mouse actions, keyboard actions, and composite actions as well.

In our next chapter, we will learn about the concept of Page Object Model (POM), where we will learn how we handle object information. The management of object information is important and is required for our test automation scripts.

Related Articles:

Selenium Python – Frames, Alerts, and Action Class Read More »

Python Interview Questions on Classes and Inheritance

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Classes and Inheritance

Modules

  • Modules are used to create a group of functions that can be used by anyone on various projects.
  • Any file that has python code in it can be thought of as a Module.
  • Whenever we have to use a module we have to import it into the code.
  • Syntax:

import module_name

Object Orientation

  • Object Orientation programming helps in maintaining the concept of reusability of code.
  • Object-Oriented Programming languages are required to create readable and reusable code for complex programs.

Classes

  • A class is a blueprint for the object.
  • To create a class we use the Keyword class.
  • The class definition is followed by the function definitions, class class_name:

def function_name(self):

Components of a class
A class would consist of the following components:

  1. class Keyword
  2. instance and class attributes
  3. self keyword
  4. __init__function

Instance and class attribute

Class attributes remain the same for all objects of the class whereas instance variables are parameters of__init__( ) method. These values are different for different objects.

The self

  • It is similar to this in Java or pointers in C++.
  • All functions in Python have one extra first parameter (the ‘self’) in the function definition, even when any function is invoked no value is passed for this parameter.
  • If there a function that takes no arguments, we will have to still mention one parameter – the “self’ in the function definition.
    The__init__( ) method:
  • Similar to the constructor in Java
  • __init__( ) is called as soon as an object is instantiated. It is used to
    initialize an object.

Question:
What will be the output of the following code?

class BirthdayWishes:
   def__init__(self, name):
        self.name = name
   def bday_wishes(self):
        print("Happy Birthday ", self.name,"!!")
bdaywishes = BirthdayWishes("Christopher")
bdaywishes.bday_wishes( )

Answer:

The output will be as follows:
Happy Birthday, Christopher !!

Question:
What are class variables and instance variables?
Answer:

Class and instance variables are defined as follows:

 class Class_name:
     class_variable_name = static_value

     def__init__(instance_variable_val):
           Instance_variable_name = instance_ variable val

Class variables have the following features:

  • They are defined within class construction
  • They are owned by the class itself
  • They are shared by all instances in class
  • Generally have the same value for every instance
  • They are defined right under the class header
  • Class variables can be accessed using the dot operator along with the class name as shown below:

Class name. class_variable_name

The instance variables on the other hand:

  • Are owned by instances.
  • Different instances will have different values for instance variables.
  • To access the instance variable it is important to create an instance of the class:

instance_name = Class_name( )
instance_name. Instance variable name

Question:
What would be the output of the following code:

class sum_total:
      def calculation(self, number1,number2 = 8,):
         return number1 + number2
st = sum_total( )
print(st.calculation(10,2))

Answer:

12

Question:
When is__init__( ) function called ?
Answer.
The__init__( ) function is called when the new object is instantiated.

Question:
What will be the output of the following code?

class Point:
   def__init__(self, x=0,y=10,z=0):
        self.x = x + 2
        self.y = y + 6
        self.z = z + 4
p = Point(10, 20,30)
print (p.x, p.y, p.z)

Answer:

12 26 34

Question:
What will be the output for the following code?

class StudentData:
    def__init__(self, name, score, subject):
         self.name = name
         self.score = score
         self.subject = subject
    def getData(self):
         print("the result is {0}, {1}, {2}".
format(self.name, self.score, self.subject))
sd = StudentData("Alice",90,"Maths")
sd.getData( )

Answer:

the result is Alice, 90, Maths

Question:
What will be the output for the following code?

class Number__Value:
    def init (self, num):
      self.num = num 
      num = 500
num = Number_Value(78.6)
print(num.num)

Answer:

78.6

Inheritance

Object-Oriented languages allow us to reuse the code. Inheritance is one such way that takes code reusability to another level altogether. In an inheritance, we have a superclass and a subclass. The subclass will have attributes that are not present in the superclass. So, imagine that we are making a software program for a Dog Kennel. For this, we can have a dog class that has features that are common in all dogs. However, when we move on to specific breeds there will be differences in each breed.

So, we can now create classes for each breed. These classes will inherit common features of the dog class and to those features, it will add its own attributes that make one breed different from the other. Now, let’s try something. Let’s go step by step. Create a class and then create a subclass to see how things work. Let’s use a simple example so that it is easy for you to understand the mechanism behind it.

Step 1:
Let’s first define a class using the “Class” Keyword as shown below:

class dog( ):

Step 2:
Now that a class has been created, we can create a method for it. For this example, we create one simple method which when invoked prints a simple message I belong to a family of Dogs.

def family(self):
      print("I belong to the family of Dogs")

The code so far looks like the following:

class dog( ):
      def family(self):
            print("I belong to the family of Dogs")

Step 3:
In this step we create an object of the class dog as shown in the following code:

c = dog( )

Step 4:
The object of the class can be used to invoke the method family( ) using the dot ‘.’ operator as shown in the following code:

c.family( )

At the end of step 4 the code would look like the following:

class dog( ):
   def family(self):
       print("I belong to the family of Dogs")

c = dog( )
c.family( )

When we execute the program we get the following output:

I belong to the family of Dogs

From here we move on to the implementation of the concept of inheritance. It is widely used in object-oriented programming. By using the concept of inheritance you can create a new class without making any modification to the existing class. The existing class is called the base and the new class that inherits it will be called the derived class. The features of the base class will be accessible to the derived class.
We can now create a class german shepherd that inherits the class dog as shown in the following code:

class germanShepherd(dog):
     def breed(self):
         print ("I am a German Shepherd")

The object of a class german shepherd can be used to invoke methods of the class dog as shown in the following code:

Final program
class dog():
     def family(self):
           print ("I belong to the family of Dogs")
class german shepherd(dog):
    def breed(self) :
           print ("I am a German Shepherd")
c = germanShepherd!)
c.family( )
c.breed( )

Output

I belong to the family of Dogs 
I am a German Shepherd

If you look at the code above, you can see that object of class germanShepherd can be used to invoke the method of the class.
Here are few things that you need to know about inheritance.
Any number of classes can be derived from a class using inheritance.
In the following code, we create another derived class Husky. Both the classes germaShepherd and husky call the family method of dog class and breed method of their own class.

class dog( ):
   def family(self):
       print("I belong to the family of Dogs")

class germanShepherd(dog):
    def breed(self):
         print("I am a German Shepherd")

class husky(dog):
   def breed(self):
       print("I am a husky")
g = germanShepherd()
g.family()
g. breed()
h = husky ()
h. family()
h .breed()

Output

I belong to family of Dogs 
I am a German Shepherd 
I belong to family of Dogs 
I am a husky

A derived class can override any method of its base class.

class dog( ):
   def family(self):
       print ("I belong to family of Dogs")

class germanShepherd(dog):
    def breed(self):
        print("I am a German Shepherd")
class husky(dog):
    def breed(self):

print("I am a husky")
def family(self):
print ("I am class apart")
g = germanShepherd()
g.family()
g. breed()
h = husky ()
h. family() h.breed()

Output

I belong to the family of Dogs 
I am a German Shepherd 
I am class apart 
I am a husky

A method can call a method of the base class with the same name.

Look at the following code, the class husky has a method family( ) which call the family( ) method of the base class and adds its own code after that.

class dog( ):
  def family(self):
        print("I belong to family of Dogs")

class germanShepherd(dog):
   def breed(self) :
      print ("I am a German Shepherd")

class husky(dog):
   def breed(self):
       print("I am a husky")
   def family(self):
        super().family()
       print("but I am class apart")

g = germanShepherd( )
g.family( )
g. breed( )
h = husky( )
h. family( ) h.breed( )

 

Output

I belong to the family of Dogs 
I am a German Shepherd 
I belong to the family of Dogs 
but I am class apart 
I am a husky

Question:
What are multiple inheritances?
Answer:
If a class is derived from more than one class, it is called multiple inheritances.

Question:
A is a subclass of B. How can one invoke the__init__function in B from A?
Answer:
The__init__function in B can be invoked from A by any of the two methods:

  • super( ).__init__( )
  • __init__(self)

Question:
How in Python can you define a relationship between a bird and a parrot.
Answer:
Inheritance. Parrot is a subclass of birds.

Question:
What would be the relationship between a train and a window?
Answer:
Composition

Question:
What is the relationship between a student and a subject?
Answer:
Association

Question:
What would be the relationship between a school and a teacher?
Answer:
Composition

Question:
What will be the output for the following code:

class Twice_multiply:
def __init__(self):
self.calculate (500)

def calculate(self, num):
self.num = 2 * num;
class Thrice_multiply(Twice_multiply):
def__init__(self):
super ( ) .__init__( )
print("num from Thrice_multiply is", self. num)

def calculate(self, num):
self.num = 3 * num;
tm = Thrice_multiply()

Answer:

num from Thrice_multiply is 1500
>>>

Question:
For the following code is there any method to verify whether tm is an object of Thrice_multiply class?

class Twice_multiply:
   def__init__(self) :
       self.calculate(500)
   def calculate(self, num) :
        self.num = 2 * num;
class Thrice_multiply(Twice_multiply):
    def __init__(self) :
      super () .__init__()
      print("num from Thrice_multiply is", self. num)
def calculate(self, num):
     self.num = 3 * num;
tm = Thrice_multiply( )

Answer:
Yes, one can check whether an instance belongs to a class or not using isinstance( ) function.

isinstance(tm,Thrice_multiply)

Python Interview Questions on Classes and Inheritance Read More »

Python Interview Questions on Stacks, Queues, and Deque

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Stacks, Queues, and Deque

Stack, Queues, and Deque are linear structures in Python.

Stack

Stack is an ordered collection of items where the addition and removal of items take place at the same end which is also known as the TOP. The other end of the stack is known as the BASE. The base of the stack is significant because the items that are closer to the base represent those that have been in the stack, for the longest time.

The most recently added item is the one that is in the top position so that it can bebe removed first.

This principle of order is known as LIFO-that stands for Last -in-first- out, where the newer items are near the top, while older items are near the base.

Python Interview Questions on Stacks, Queues, and Deque chapter 10 img 1

Stacks are important because they are required whenever there is a need to reverse the order of items as the order of removal is reverse of the order of insertion.

Example:

1. Pushing the back button on the browser while surfing on the internet.
2. Ctrl+Z (undo) in Microsoft applications.
3. Remove recently used objects from the cache.

Stacks are commonly used by software programmers; it may not be quite noticeable while using a program as these operations generally take place in the background. However, many times you may come across a Stack overflow error. This happens when a stack actually runs out of memory.

Stacks seem to be very simple. Yet they are one of the most important data structures as you will see very soon. Stacks serve as a very important element of several data structures and algorithms.

Question 1.
Explain, how would you implement a stack in Python.
Answer:
We will implement Stack using lists.

Step 1:

Define the Stack Class

#Define Stack Class
class Stack:

Step 2:

Create constructor

Create a constructor that takes self and size (n) of the stack. In the method, we declare that self. stack is an empty list([ ]) and self. size is equal to n i.e. the size provided.

#Define Stack Class
          def__init__(self, n):
             self.stack = [ ]
                     self.size = n

 

Step 3:

Define Push Function

A push function will have two arguments self and the element that we want to push in the list. In this function, we first check if the length of the stack is equal to the size provided as input (n). If yes, then it means that the stack is full and prints the message that no more elements can be appended as the stack is full. However, if that is not the case then we can call the append method to push the element to the stack.

def push(self,element):
if(len(self.stack)== self.size):
print("no more elements can be appended as the stack is full")
else:
self.stack.append(element)

Step 4:

Define POP Function

Check the stack. If it is empty, then print: Stack is empty. Nothing to POP!!. If it is not empty pop the last item from the stack.

def pop(self):
      if self.stack == [ ]:
          print("Stack is empty. Nothing to POP!!")

else:
     return self.stack.pop( )

The complete code will be as follows:

Code

#Define Stack 
Class class Stack:
     #declare constructor

def__init__(self, n):
    self.stack = [ ]
    self.size = n

#push operation

def push(self,element):
if(len(self.stack)== self.size):
print("no more elements can be appended as the stack is full")

else:

       self.stack.append(element)

#pop operation
def pop(self):
   if self.stack == [ ]:
       print("Stack is empty. Nothing to POP!!")
 
     else:
          self.stack.pop( )

Execution

s = Stack(3) 
s.push(6)
s.push(2) 
print(s.stack)
s.pop( )
print(s.stack)

Output

[6, 2]
[6]
>>>

Question 2.
Write a program to check if a given string has a balanced set of parenthesis or not.
Balanced parenthesis: ( ), { }, [ ], {[( )]}, [ ][ ], etc.
Answer:
Here we have to check if pairs of brackets exist in the right format in a string. Expressions such as “[ ]{( )}” are correct. However, if the opening bracket does not find the corresponding closing bracket then the parenthesis is a mismatch. For example: “[ }”or “{ }[ ))”• To solve this problem we will follow the following steps:

Step 1

Define class paranthesis_match

class paranthesis_match:

Step 2

Defining lists for opening and closing brackets

We now define two lists such that the index of an opening bracket matches with the index of the corresponding closing bracket:

1. List opening_brackets will have all types of opening brackets as elements -[“(“,{“,”[“]
2. List closing_brackets will have all types of closing brackets as elements – [“(“,”{“,”[“]
Here is how we define the lists:

opening_brackets = ["(",{","["]
closing_brackets = [")","}"/"]"]

Step 3

Defining Constructor, Push, and Pop functions

Constructor:

The constructor takes an expression as a parameter which is the string provided for validation of parameters.
We also initialize the list for stacking purposes. The push( ) and pop( ) functions will be applied on this list.

def__init__(self, expression):
self-expression = expression
self.stack = [ ]

Push( ) and Pop( ) Functions

Since we are implementing this using a stack it is quite obvious that we would require push( ) and pop functions.

The push( ) function when called, will add an element to the stack.

def push(self,element):
self.stack.append(element)

The pop( ) element on the other hand will pop the last element from the stack.

#pop operation
def pop(self):
if self.stack == [ ]:
print("Unbalanced Paranthesis")
else:
self.stack.pop( )

Step 4

Defining the function to do the analysis

We will now write the code to analyze the string.
In this function we will perform the following steps:

  • First, we check the length of the expression. A string of balanced parenthesis will always have even number of characters. So, if the length of the expression is divisible by two only then we would move ahead with the analysis. So, an if.. .else loop forms the outer structure of this function.
if len(self.expression)%2 == 0:
             ---- we analyse .......... .
else:
            print("Unbalanced Paranthesis")
  • Now, considering that we have received a length of even number. We can move ahead with analysis and we can write our code in the “if’ block. We will now traverse through the list element by element. If we encounter an opening bracket we will push it onto the stack, if it is not an opening bracket then we check if the element is in the closing bracket list. If yes then we pop the last element from the stack and see if the index of the elements in the opening_brackets and closing_brackets list is of the same bracket. If yes, then there is a match else the list is unbalanced.

Python Interview Questions on Stacks, Queues, and Deque chapter 10 img 2

if element in self.opening_brackets:
                          self.push(element)
elif element in self.closing_brackets:
    x = self.stack.pop( )
        if self.opening_brackets.index(x)== self. 
closing_brackets.index(element):
                print("Match Found")
       else:
               print("Match not found -check prarnthesis")
return;
  • So, the final code will be as follows, to make things easier for the end user, print commands have been added:
class paranthesis_match:
           opening_brackets = ["(","{","["]


closing_orackets = [")","}","]"}


#declare constructor
def__init__(self, expression):
    self-expression = expression
    self.stack = [ ]


#push operation
def push(self,element):
          self.stack.append(element)


#pop operation
def pop(self):
       if self.stack == [ ]:
                  print ("Unbalanced Paranthesis")
    else:
         self.stack.pop( )
def is_match(self):
       print ("expression is = ", self.expression)
       if len (self.expression)%2 == 0:
            for element in self-expression:
                       print("evaluating ", element)
                      if element in self.opening_brackets:
                     print("it is an opening bracket - ", element, "pushing to stack")

                     self.push(element)
                     print("pushed", element, " on to stack the stack is ", self.stack)
                  elif element in self. closing_brackets:
                 x = self.stack.pop( )
                print("time to pop element is ", x)
                       if self.opening_brackets.
index(x)== self.closing_brackets.index(element):
                       print("Match Found")
              else:
print("Match not found - check prarnthesis")
return;
else :
print("Unbalanced Paranthesis")

Execution

pm = paranthesis match("( [{ }])") 
pm.is_match( )

Output

expression is = ([{ }])
evaluating (
it is an opening bracket - ( pushing to stack pushed ( on evaluating to stack the [ stack is [ ' ( ' ]
evaluating [
it is an opening bracket - [ pushing to stack pushed [ on to stack the stack is [ ' ( ' , ' [ ']
evaluating {
it is an opening bracket - { pushing to stack pushed { on to stack the stack is [ ' ( ' , ' ] ' , ' { ' ]
evaluating }
time to pop element is {
Match Found
evaluating ]
time to pop element is [
Match Found
evaluating )
time to pop element is (
Match Found

Queue

A queue is a sequence of objects where elements are added from one end and removed from the other. The queues follow the principle of first in first out. The removal of items is done from one end called the Front and the items are removed from another end that’s referred to as the rear. So, just as in the case of any queue in real life, the items enter the queue from the rear and start moving towards the front as the items are removed one by one.

So, in Queue the item at the front is the one that has been in the sequence for the longest and the most recently added item must wait at the end. The insert and delete operations are also called en queue and de queue.

Basic Queue functions are as follows:

  • enqueue(i): Add element “i” to the queue.
  • dequeue( ): Removes the first element from the queue and returns its value.
  • isEmpty( ): Boolean function that returns “true” if the queue is empty else it will return false.
  • size( ): Returns length of the queue.

Python Interview Questions on Stacks, Queues, and Deque chapter 10 img 3

Question 3.
Write a code for implementation of Queue.
Answer:
The implementation of the queue is as follows: Step1
Define the class
class Queue:
Step 2
Define the constructor
Here, we initialize an empty list queue:

def__init__(self):
self.queue =[ ]

Step 3
Define isEmpty( ) function

As the name suggests, this method is called to check if the queue is empty or not. The function check the queue. If it is empty, it prints a message – Queue is Empty or else it will print a message – Queue is not Empty

def isEmpty(self):
          if self.queue ==[ ]:
               print("Queue is Empty")
       else:
           print("Queue is not Empty")

Step 4

Define enqueue( ) function

This function takes an element as parameter and inserts it at index “0”. All elements in the queue shift by one position.

def enqueue(self,element):
self.queue.insert(0, element)

Step 5

Define dequeue( ) function
This function pops the oldest element from the queue.

def dequeue(self):
self.queue.pop( )

Step 6

Define size ( ) function

This function returns the length of the queue.

def size (self) :
print ("size of queue is",len(self.queue))

Code

class Queue:
      def__init__(self):
          self.queue =[ ]
      def isEmpty(self):
          if self.queue ==[ ]:
             print ("Queue is Empty")
      else :
          print("Queue is not empty")
    def enqueue(self,element):
           self.queue.insert(0,element)
    def dequeue(self) :
           self.queue.pop( )
    def size(self):
        print("size of queue is",len(self.queue))

Code Execution

q = Queue ( )
q.isEmpty( )
print("inserting element no.1")
q.enqueue("apple")
print("inserting element no.2")
q.enqueue("banana")
print("inserting element no.3")
q.enqueue("orange")
print("The queue elements are as follows:")
print(q.queue)
print("check if queue is empty?")
q.isEmpty()
print ("remove first element")
q.dequeue()
print("what is the size of the queue?")
q.size ()
print("print contents of the queue")
print(q.queue)

Output

Queue is Empty
inserting element no.1
inserting element no.2
inserting element no.3
The queue elements are as follows:
['orange', 'banana', 'apple'] 
check if queue is empty?
Queue is not empty 
remove first element 
what is the size of the queue? 
size of queue is 2 
print contents of the queue 
['orange', 'banana']

Question 4.
Write a code to implement a stack using a single queue. What is the time complexity for pushful and pop( ) functions?
Answer:
Before implementing the code it is important to understand the logic behind it. The question demands that you make a queue work like a stack. A queue works on the principle of First-In-First-Out whereas a stack works on the principle of Last In First Out.

Python Interview Questions on Stacks, Queues, and Deque chapter 10 img 4

Code

class Stack from Queue:
     def__init__(self):
         
       self.queue =[ ]
def isEmpty(self):
       if self.queue ==[ ]:
           print("Queue is Empty")
      else :
         print("Queue is not empty")
def enqueue(self,element):
         self.queue.insert(0,element)
def dequeue(self):
      return self.queue.pop( )
def size(self):
       print("size of queue is ",len(self.queue))
def pop(self):

for i in range(len(seif.queue)-1):
     x = self.dequeue( )
     print(x)
     self.enqueue(x)
print("element removed is",self.dequeue( ))

Execution -1

sq = Stack_from_Queue( )
sq.isEmpty( )
print("inserting element apple")
sq.enqueue("apple")
print("inserting element banana")
sq.enqueue("banana")
print("inserting element orange")
sq.enqueue("orange" )
print("inserting element 0")
sq.enqueue("0")
print("The queue elements are as follows:")
print (sq. queue)
print ("check if queue is empty?")
sq.isEmpty( )
print("remove the last in element")
sq.pop( )
print(sq.queue)

Output -1

Queue is Empty 
inserting element apple 
inserting element banana 
inserting element orange 
inserting element 0 
The queue elements are as follows: 
['O', 'orange', 'banana', 'apple'] 
check if queue is empty?
Queue is not empty
remove the last in element
apple
banana
orange
element removed is 0 
['orange', 'banana', 'apple']

Execution – II

sq = Stack_from_Queue ( )
sq.isEmpty ( )
print("inserting element apple")
sq.enqueue("apple")
print("inserting element banana")
sq.enqueue("banana")
print("inserting element orange")
sq.enqueue("orange")
print("inserting element 0")
sq.enqueue("0")
for i in range(len(sq.queue)):
     print("The queue elements are as follows:") 
     print(sq.queue)
     print("check if queue is empty?")
     sq.isEmpty()
     print("remove the last in element")

print(sq.queue)

Output -II

Queue is Empty
inserting element apple
inserting element banana
inserting element orange
inserting element 0
The queue elements are as follows:
['O', 'orange', 'banana', 'apple']
check if queue is empty?
Queue is not empty
remove the last in element
apple
banana
orange
element removed is 0
['orange', 'banana', 'apple']
The queue elements are as follows:
['orange', 'banana', 'apple']
check if queue is empty?
Queue is not empty
remove the last in element
apple
banana
element removed is orange
[ 'banana', 'apple']
The queue elements are as follows:
[ 'banana', 'apple']
check if queue is empty?
Queue is not empty
remove the last in element
apple
element removed is banana
['apple']
The queue elements are as follows:
['apple']
check if queue is empty?
Queue is not empty
remove the last in element
element removed is apple
[ ]
>>>

Time complexity for push( ) and pop( ) function is O(1)
Time complexity for push is O(1).
Time complexity for pop is O(n) because we have to iterate through the
loop and rearrange elements before retrieving the element.

Question 5.
How can a queue be implemented using two stacks?
Answer:
Step 1:
Create a basic Stack( ) class with push( ), pop( ), and isEmpty( ) functions.

class Stack:
    def__init__(self) :
self.stack = [ ]

def push(self,element):
     self.stack.append(element)

def pop(self):
      return self.stack.pop( )
def isEmpty(self):
      return self.stack == [ ]

Step 2:

Define the Queue class

class Queue:

Step 3:

Define the constructor

Since the requirement here is of two stacks, we initialize two stack objects.

def__init__(self) :
self.inputStack = Stack( )
self.outputStack = Stack( )

Step 4:

Define the enqueue function

This function will push the elements into the first stack.

def enqueue(self,element):
self.inputStack.push(element)

Step 5:

Define the dequeue( ) function

This function checks if the output stack is empty or not. If it is empty then elements will be popped out from the input stack one by one and pushed into the output stack, so that the last element is the first one to be out. However, if the output stack is not empty, then the elements can be popped directly from it.

Now suppose we insert 4 values: 1,2,3,4 calling the en queue function. Then the input stack would be like this:

Python Interview Questions on Stacks, Queues, and Deque chapter 10 img 5

When we call the dequeue function, the elements from the input stack are popped and pushed one by one onto the output stack till we reach the last element and that last element is popped from the input stack and returned. If the output stack is not empty then it means that it already has elements in the right order and they can be popped in that order.

Python Interview Questions on Stacks, Queues, and Deque chapter 10 img 6

def dequeue(self):
      #if not self.inputStack.isEmpty( ):
      if self.outputStack.isEmpty( ):
              for i in range(len(self.inputStack.
stack)-1):
             x = self.inputStack.pop( )
             self.outputStack.push(x)
          print("popping out value =", self. inputStack.pop( ))
      else:
          print("popping out value =", self. 
outputStack.pop( ))

Code

class Queue:
    def__init__(self):
      self . inputStack = Stack( )
      self . outputStack = Stack( )
   def enqueue(self,element):
         self.inputStack.push(element)
   def dequeue(self):
           if self.outputStack.isEmpty( ):
                 for i in range(len(self.inputStack.stack)-1):
        x = self.inputStack.pop( )
        self.outputStack.push(x)
      print("popping out value , self. inputStack.pop( ))
   else:
          print("popping out value =", self. 
outputStack.pop( ))

#Define Stack Class
class Stack:
   def__init__(self):
       self.stack = [ ]
def push(self,element):
   
self.stack.append(element)

   def pop(self):

  return self.stack.pop( )

def isEmpty(self):
    return self.stack == [ ]

Execution

Q = Queue( )
print("insert value 1")
Q.enqueue(1)
print("insert value 2")
Q.enqueue(2)
print("insert value 3")
Q.enqueue(3)
print("insert value 4")
Q.enqueue(4)
print("dequeue operation")
Q.dequeue( )
Q.dequeue( )
print("insert value 1")
Q.enqueue(7)
Q.enqueue(8)
Q.dequeue( )
Q.dequeue( )
Q.dequeue( )
Q.dequeue( )

Output

Q = Queue( )
print("insert value 1")
Q.enqueue(1)
print ("insert value 2")
Q.enqueue(2)
print ("insert value 3")
Q.enqueue(3)
print("insert valu? 4")
Q.enqueue(4)
print("dequeue operation")
Q.dequeue()
Q.dequeue()
print("insert value 1")
Q.enqueue(7)
Q.enqueue(8)
Q.dequeue( )
Q.dequeue( )
Q.dequeue( )
Q.dequeue( )

Deques

A deque is more like a queue only that it is double-ended. It has items positioned in the ordered collection and has two ends, the front, and the rear. A deque is more flexible in nature in the sense that the elements can be added or removed from the front or rear. So you get the qualities of both stack and queue in this one linear data structure.

Python Interview Questions on Stacks, Queues, and Deque chapter 10 img 7

Question:
Write a code to implement a deque.
Answer.
Implementation of the deque is easy. If you have to add an element from the rear, you will have to add it at index 0 the same way if you have to add it from the front, call the append( ) function. Similarly, if you have to remove the front call pop( ) function and if you want to pop it from the rear call pop(o).

Code

class Deque:
   def__init__(self):
       self.deque =[ ]
   def addFront(self,element):
       self.deque.append(element)
       print("After adding from front the deque value is : ", self.deque)
   def addRear(self,element):
        self.deque.insert(0,element)

           print("After adding from end the deque value is : ", self.deque)
   def removeFront(self):
     self.deque.pop( )
print("After removing from the front the deque value is : ", self.deque)
     def removeRear(self):
self.deque.pop(0)
            print("After removing from the end the deque value is : ", self.deque)

Execution

D = Deque()
print("Adding from front")
D.addFront(1)
print("Adding from front")
D.addFront(2)
print("Adding from Rear")
D.addRear(3)
print("Adding from Rear")
D.addRear(4)
print("Removing from Front")
D.removeFront()
print("Removing from Rear")
D.removeRear( )

Output

After adding from front the deque value is : [1]
After adding from the front the deque value is : [1, 2]
After adding from the end the deque value is : [3, 1,2]
After adding from the end the deque value is : [4, 3,1, 2]
After removing from the front the deque value is : [4, 3, 1] 
After removing from the end the deque value is : [3, 1]
>>>

Python Interview Questions on Stacks, Queues, and Deque Read More »

Python Interview Questions on Linked List

We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Linked List

A linked list is a linear structure that consists of elements such that each element is an individual object and contains information regarding:

  1. Data
  2. Reference to next element

In the linked list, each element is called a node.

Python Interview Questions on Linked List chapter 11 img 3

You can see in the diagram, the reference to the first node is called Head. It is the entry point of the linked list. If the list is empty then the head points to null. The last node of the linked list refers to null.

As the number of nodes can be increased or decreased as per requirement, linked lists are considered to be dynamic data structures. However, in a linked list direct access to data is not possible. Search for any item that starts from- the head and you will have to go through each reference to get that item. A linked list occupies more memory.

The linked list described above is called a singly linked list. There is one more type of linked list known as a doubly-linked list. A double-linked list has a reference to the next node and the previous node.

Python Interview Questions on Linked List chapter 11 img 4

Question 1.
Write a code to implement a Node class such that a Node contains data as well as a reference to the next node.
Answer:
To create a node object we pass data value to the constructor. The constructor assigns the data value to data and sets the node’s reference to None. Once we create all the objects we assign the memory address of the second object as the reference to the first node object, the memory address of the third object is assigned as a reference to the second object, and so on. The last object, thus have no(or none as) reference.

The code for the Node class will be as follows:

Code

class Node:
        def__init__(self,data = None):
            self . data = data
            self . reference = None
objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
objNode1 . reference = objNode2
objNode2 . reference = objNode3
objNode3 . reference = objNode4
objNode4 . reference = None

Execution

print("DATA VALUE = ",objNodel.data,"REFERENCE = ",objNodel.reference)
print("DATA VALUE = ",objNode2.data,"REFERENCE = ",objNode2.reference)
print("DATA VALUE = ",objNode3.data,"REFERENCE = ",objNode3.reference)
print("DATA VALUE = ",objNode4.data,"REFERENCE = ”,objNode4.reference)

Output

DATA VALUE = 1 REFERENCE = <_main_. Node object
at 0x000000595E0CC6A0>
DATA VALUE = 2 REFERENCE =<_main_ .Node object
at 0x000000595E329978>
DATA VALUE = 3 REFERENCE = <_main_ .Node object
at 0x000000595E3299B0>
DATA VALUE = 4 REFERENCE = None
>>>

Question 2.
Write code to traverse through a linked list.
Answer:
Method I
We have already written the code for the Node class:

class Node:
      def _init_ (self,data = None):
          self.data = data
          self.reference = None

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)

We will now see how to traverse through the linked list:

Step 1
We create a variable presentNode and assign the first object to it.

presentNode = objNode1

On doing this presentNode gets the data and reference values of objectNode1.
Step 2
The reference value points to objNode2.
So, we can write a while loop:

while presentNode:
print("DATA VALUE = ",presentNode.data)
presentNode = presentNode.reference

Once the presentNode is assigned, the reference value contained in objNode4 it will come out of the while loop because the value of reference is None.

Code

class Node:
       def_init_(self,data = None):
           self.data = data
           self.reference = None

Execution

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
objNodel.reference = objNode2
objNode2.reference = objNode3
objNode3.reference = objNode4
objNode4.reference = None
presentNode = objNode1
while presentNode:
    print("DATA VALUE = ",presentNode.data)
    presentNode = presentNode.reference

Output

DATA VALUE = 1
DATA VALUE = 2
DATA VALUE = 3
DATA VALUE = 4

Method II
Another method to do this by creating two classes: Node and Linked list
Code

class Node:
      def_init_(self,data = None):
          self.data = data
          self.reference = None
class Linked_list:
     def_init_(self):
        self.head = None 
     def traverse(self) :
           presentNode = self.head
           while presentNode:
                  print("DATA VALUE = ",presentNode.data)
                  presentNode = presentNode.reference

Execution

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
linkObj = Linked_list( )
#head of the linked list to first object
linkObj.head = objNodel
# reference of the first node object to second object

linkObj.head.reference = objNode2
objNode2.reference = objNode3
objNode3.reference = objNode4
linkObj.traverse ( )

Output

DATA VALUE = 1
DATA VALUE = 2
DATA VALUE = 3
DATA VALUE = 4

Question 3.
Write a code to add a node at the beginning of a linked list.
Answer:
To solve this question, we will just add a new method to insert the node in the same code that is mentioned in the last example:
In the last example, we pointed the head of the linked list object to the first node object.

linkObj.head = objNode1

When we add the node at the beginning we just have to make the linkObj.
head = new_node and new node.reference = obj_Node1.

For this, we write a code where the value of the linkObj.head is first passed on to the new node. reference and then linkObj.head is set to the new node object.

def insert_at_Beginning(self, data) :
new_data = Node(data)
new_data.reference = self.head
self.head = new_data

So, the full code would be like the following:

Code

class Node:
     def_init_(self,data = None):
          self.data = data
          self.reference = None
class Linked_list:
   def_init_(self) :
         self.head = None
  def traverse(self):
       presentNode = self.head
       while presentNode:
            print("DATA VALUE = ",presentNode.data)
            presentNode = presentNode.reference
 def insert_at_Beginning(self, data) :
       new_data = Node(data)
       new_data.reference = self.head
       self.head = new data

Execution

objNode1 = Node(l1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
linkObj = Linked_list( )
#head of the linked list to first object
linkObj.head = objNode1
# reference of the first node object to second object
linkObj.head.reference = objNode2
objNode2.reference = objNode3
objNode3.reference = objNode4
linkObj.insert_at_Beginning(5)
linkObj.traverse ( )

Output

DATA VALUE = 5
DATA VALUE = 1
DATA VALUE = 2
DATA VALUE = 3
DATA VALUE = 4

Question 4.
Write a code to add a node at the end of a linked list.
Answer.
In order to add a node at the end of the linked list, it is important that you point the reference of the last node to the new node that you create.
Step 1:

Define the function

def insert_at_end(self,data):

Step 2:

Create a new Node object

new_data = Node(data)

Step 3:

Traverse through the linked list to reach the last node
Remember that you cannot directly access the last node in the linked list. You will have to traverse through all the nodes and reach the last node in order to take the next step.

presentNode = self.head
             while presentNode.reference != None:
                   presentNode = presentNode.reference

Step 4:

Add the new node at the end

After traversing through the linked list, you know that you have reached the last node whenpresentNode.reference = None. Since this won’t remain the last node anymore, you need to:

presentNode.reference = new_data

With this, we have added a new node at the end of a linked list.

Code

class Node:
    def_init_(self,data = None):
          self.data = data
          self.reference = None
class Linked_list:
   def_init_(self):
         self.head = None
   def traverse(self):
       presentNode = self.head
       while presentNode:
             print("DATA VALUE = ",presentNode.data)
             presentNode = presentNode.reference
  def insert_at_end(self,data):
      new_data = Node(data)
      presentNode = self.head
      while presentNode.reference != None:
          presentNode = presentNode.reference
      presentNode.reference = new_data

Execution

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
linkObj = Linked_list( )
#head of the linked list to first object
linkObj.head = objNode1
# reference of the first node object to second object
linkObj.head.reference = objNode2
objNode2.reference = objNode3
objNode3.reference = objNode4
linkObj.insert_at_end(5)
linkObj.insert_at_end(6)
linkObj.insert_at_end(7)
linkObj.traverse( )

Output

DATA VALUE = 1
DATA VALUE = 2
DATA VALUE = 3
DATA VALUE = 4
DATA VALUE = 5
DATA VALUE = 6
DATA VALUE = 7

Question 5.
Write a code to insert a node between two nodes in a linked list.
Answer:
The solution for this problem is very similar to adding a node to the beginning. The only difference is that when we add a node at the beginning we point the head value to the new node whereas in this case, the function will take two parameters. First will be the node object after which the new object will be inserted and the second would be the data for the new object. Once the new node is created, we pass on the reference value stored in the existing node object to it and the existing node is then made to point at the new node object

Step 1:

Define the function

This function will take two parameters:

  1. The node object after which the data is to be inserted.
  2. Data for the new node object.
def insert_in_middle(self,insert_data,new_data):

Step 2:
Assign references

new_node = Node(new_data)
new_node.reference = insert_data.reference insert_data.reference = new_node

Code

class Node:
      def_init_(self,data = None):
               self.data = data
               self.reference = None
class Linked_list:
def_init_(self):
self.head = None
def traverse(self):
presentNode = self.head
while presentNode:
                    print("DATA VALUE = ",presentNode.data)
                    presentNode = presentNode.reference


def insert_in_middle(self,insert_data,new_data):
                 new_node = Node(new_data)
                new_node.reference = insert_data.reference insert_data.reference = new_node

Execution

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
linkObj = Linked_list()
#head of the linked list to first object
linkObj.head = objNodel
# reference of the first node object to second object
linkObj.head.reference = objNcde2

objNode2.reference = objNode3
objNode3.reference = objNode4
linkObj.insert_in_middle(objNode3,8)
linkObj.traverse ( )

Output

DATA VALUE = 1
DATA VALUE = 2
DATA VALUE = 3
DATA VALUE = 8
DATA VALUE = 4
>>>

Question 6.
Write code to remove a node from a linked list.
Answer:
Suppose we have a linked list as shown below:
A -> B -> C
A. reference = B
B. reference = C
C. reference = A.
To remove B, we traverse through the linked list. When we reach node A that has a reference pointing to B, we replace that value with the reference value stored in B(that points to C). So that will make A point to C and B is removed from the chain.
The function code will be as follows:

def remove(self,removeObj):
 presentNode = self.head
  while presentNode:
    if(presentNode.reference == removeObj):
       presentNode.reference = removeObj.reference
           presentNode = presentNode.reference

The function takes the Node object as a parameter and traverses through the linked list, till it reaches the object that needs to be removed. Once we reach the node that has reference to the node that has to be removed, we simply change the reference value to reference value stored in object removeobj. Thus, the node now points directly to the node after the removeObj.

Code

class Node:
  def_init_(self,data = None):
           self.data = data
           self.reference = None
class Linked_list:
  def_init_(self) :
         self.head = None
  def traverse(self):
          presentNode = self.head
          while presentNode:
             print("DATA VALUE = ",presentNode.data)
             presentNode = presentNode.reference


def remove(self,removeObj):
      presentNode = self.head
       while presentNode:
             if(presentNode.reference == removeObj):
             presentNode.reference = removeObj.
reference
             presentNode = presentNode.reference

Execution

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
linkObj = Linked_list( )
#head of the linked list to first object
linkObj.head = objNode1
# reference of the first node object to second object
linkObj.head.reference = objNode2
objNode2.reference = objNode3
objNode3.reference = objNode4
linkObj.remove(objNode2)
linkObj.traverse( )

Question 7.
Print the values of the node in the center of the linked list.
Answer:
This involves counting the number of nodes in the object. If the length is even then the data of two nodes in the middle should be printed else only the data of the node in the center should be printed.

Step 1:

Define the function

def find_middle (self, 1list) :

Step 2:

Find the length of the counter

Here, we set a variable counter = 0. As we traverse through the linked list we increment the counter. At the end of the while loop we get the count of the number of nodes in the linked list. This is also the length of the linked list.

counter = 0
          presentNode = self.head
          while presentNode:
                 presentNode = presentNode.reference
                  counter = counter + 1 .
          print("size of linked list = ", counter)

Step 3:

Reach the middle of the linked list

The reference to the node in the middle is stored in the node before that. So, in the for loop instead of iterating (counter/2) times, we iterate (counter-1)/2 times. This brings us to the node which is placed just before the centre value.

presentNode = self.head
for i in range((counter-1)112) :
presentNode = presentNode.reference

Step 4:

Display the result depending on whether the number of nodes in the linked list

If the linked list has an even number of nodes then print the value of reference stored in the present node and the next node.

if (counter%2 == 0):
                nextNode = presentNode.reference
                print ("Since the length of linked list is an even number the two midle elements are:")
                print(presentNode.data,nextNode.data)

Else, print the value of the present node.

else: 
                print("Since the length of the linked list is an odd number, the middle element is: ")
             print(presentNode.data)

Code

class Node:
     def_init_(self,data = None):
           self.data = data
           self.reference = None
class Linked_list:
    def_init_(self):
          self.head = None
def find_middle (self, Hist) :
     counter = 0
     presentNode = self.head
    while presentNode:
         presentNode = presentNode.reference
         counter = counter + 1
    print ("size of linked list = ", counter)
    presentNode = self.head
    for i in range((counter-1)112) :
        presentNode = presentNode.reference
   if (counter%2 == 0) : 
          nextNode = presentNode.reference
          print("Since the length of linked list is an even number the two midle elements are:")
         print(presentNode.data,nextNode.data)


     else:
            print("Since the length of the linked list is an odd number, the middle element is: ")
           print(presentNode.data)

Execution (Odd Number of Nodes)

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
objNode5 = Node(5)
linkObj = Linked_list( )
#head of the linked list to first object
linkObj.head = objNode1
# reference of the first node object to second object
linkObj.head.reference = objNode2
objNode2.reference = objNode3
objNode3.reference = objNode4
objNode4.reference = objNode5
linkObj .find_middle (linkObj )

Output

size of linked list = 5
Since the length of the linked list is an odd 
number, the middle element is:
3

Execution (Even Numbers)

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4) 
linkObj = Linked_list( )
#head of the linked list to first object
linkObj.head = objNodel
# reference of the first node object to second object
linkObj.head.reference = objNode2
objNode2.reference = objNode3
objNode3.reference = objNode4
linkObj .find_middle (linkObj )

Output

size of linked list = 4
Since the length of the linked list is an even number the two middle elements are:
2  3

Question 8.
Implement a doubly linked list.
Answer:
A doubly linked list has three parts:

  1. Pointer to the previous node
  2. Data
  3. Pointer to the next node

Implementation of a doubly linked list is easy. We just need to take care of one thing that each node is connected to the next and the previous data.

Step 1:

Create a Node Class

The node class will have a constructor that initializes three parameters: data, reference to next node – refNext and reference to previous node – refPrev.

class Node:
          def_init_(self,data = None):
              self.data = data
              self.refNext = None
              self.refPrev = None

Step 2:

Create functions to traverse through the double linked list

I. Traverse Forward

To: traverse forward with the help of refNext that points to next value of the linked list. We start with the head and move on to the next node using
refNext.

def traverse(self):
presentNode = self.head
while presentNode:
print("DATA VALUE = ",presentNode.data)
presentNode = presentNode.refNext

II. Traverse Reverse

The traverse reverse is the opposite of the traverse forward. We are able to traverse backward with the help of the value of refPrev because it points to the previous node. We start from the tail and move on to the previous node using
refPrev.

def traverseReverse(self):
presentNode = self.tail
while presentNode:
        print("DATA VALUE = ",presentNode.data)
         presentNode = presentNode.refPrev

Step 3:

Write a function to add a node at the end

Appending a node at the end of the doubly linked list is the same as appending in the linked list the only difference is that we have to ensure that the node that is appended has its refPrev pointing to the node after which it has been added.

def append(self,data):
new_data = Node(data)
presentNode = self.head
while presentNode.refNext != None:
presentNode = presentNode.refNext
presentNode.refNext = new_data
new_data.refPrev = presentNode

Step 4:

Write a function to remove a node

This function takes the node object that needs to be removed as a parameter. In order to remove a node, we iterate through the doubly linked list twice. We first start with the head and move forward using refNext and when we encounter the object that needs to be removed we change the refNext value of the present node (which is presently pointing to the object that needs to be removed) to the node that comes after the object that needs to be removed. We then traverse through the linked list backward starting from the tail and when we encounter the object to be removed again we change the refPrev value of the present node to the node that is placed before it.

def remove(self,removeObj):
presentNode = self.head
presentNodeTail = self.tail
while presentNode.refNext != None:
     if(presentNode.refNext == removeObj):
          presentNode.refNext = removeObj.refNext
     presentNode = presentNode.refNext
 while presentNodeTail.refPrev != None:
    if(presentNodeTail.refPrev == removeObj):
        presentNodeTail.refPrev = removeObj.
refPrev
      presentNodeTail = presentNodeTail.refPrev

Code

class Node:
  def_init_(self,data = None):
      self.data = data
      self.refNext = None
      self.refPrev = None
class dLinked_list:
 def_init_(self)':
      self.head = None
      self.tail = None
def append(self, data) :
    new_data = Node(data)
    presentNode = self.head
    while presentNode.refNext != None:
         presentNode = presentNode.refNext
        presentNode.refNext = new_data
        new_data.refPrev = presentNode
       self.tail = new data


def traverse(self):
     presentNode = self.head
     while presentNode:
        print("DATA VALUE = ",presentNode.data)
        presentNode = presentNode.refNext


def traverseReverse(self):
    presentNode = self.tail
    while presentNode:
          print("DATA VALUE = ",presentNode.data)
          presentNode = presentNode.refPrev
def remove(self,removeObj):
    presentNode = self.head
    presentNodeTail = self.tail
    while presentNode.refNext != None:
       if (presentNode.refNext == removeObj):
           presentNode.refNext = removeObj.
refNext
          presentNode = presentNode.refNext
   while presentNodeTail.refPrev != None:
          if (presentNodeTail.refPrev ==
removeObj):
         presentNodeTail.refPrev = removeObj.
refPrev
        presentNodeTail = presentNodeTail.
refPrev

Execution

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
ObjNode4 = Node(4)
dlinkObj = dLinked_list( )
#head of the linked list to first object
dlinkObj.head = objNode1
dlinkObj.tail = objNode4
# reference of the first node object to second object
dlinkObj.head.refNext = objNode2
dlinkObj.tail.refPrev = objNode3
objNode2.refNext = objNode3
objNode3.refNext = objNode4
objNode4.refPrev = objNode3
objNode3.refPrev = objNode2
objNode2.refPrev = objNode1
print("Appending Values")
dlinkObj.append(8)
dlinkObj.append(9)
print("traversing forward after Append")
dlinkObj.traverse( )
print("traversing reverse after Append")
dlinkObj.traverseReverse( )
print("Removing Values")
dlinkObj.remove(objNode2)
print("traversing forward after Remove")
dlinkObj.traverse( )
print("traversing reverse after Remove")
dlinkObj.traverseReverse( )

Output

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
dlinkObj = dLinked_list( )
#head of the linked list to first object
dlinkObj.head = objNode1
dlinkObj.tail = objNode4
# reference of the first node object to second object
dlinkObj.head.refNext = objNode2
dlinkObj.tail.refPrev = objNode3
objNode2.refNext = objNode3
objNode3.refNext = objNode4
objNode4.refPrev = objNode3
objNode3.refPrev = objNode2
objNode2.refPrev = objNode1
print("Appending Values")
dlinkObj.append(8)
dlinkObj.append(9)
print("traversing forward after Append")
dlinkObj.traverse( )
print("traversing reverse after Append")
dlinkObj.traverseReverse( )
print("Removing Values")
dlinkObj.remove(objNode2)
print("traversing forward after Remove")
dlinkObj.traverse( )
print("traversing reverse after Remove")
dlinkObj.traverseReverse( )

Question 9.
Write code to reverse a linked list.
Answer:
To reverse a linked list we have to reverse the pointers. Look at the figure shown below. The first table shows how information is stored in the linked list. The second table shows how the parameters are initialized in the reverse( ) function before beginning to traverse through the list and reversing the elements.

Python Interview Questions on Linked List chapter 11 img 1

We then use the following while loop:

while nextval != None:
presentNode.refNext = previous
previous = presentNode
presentNode = nextval
nextval = nextval.refNext
presentNode.refNext = previous
self.head = presentNode

This is how the while loop works:

Python Interview Questions on Linked List chapter 11 img 2

You can see as we iterate through the while loop how the values of presentnode.refNext change. Node1 that was earlier pointing to node2 changes its pointer to none. Same way node2 changes its pointer value to node1, and so on.
Code

class Node:
def_init_(self,data = None):
      self.data = data
      self.refNext = None
class Linked_list:
     def init (self) :
     self.head = None


def reverse(self):
     previous = None
     presentNode = self.head
     nextval = presentNode.refNext
     while nextval != None:
           presentNode.refNext = previous
           previous = presentNode
           presentNode = nextval
           nextval = nextval.refNext
    presentNode.refNext = previous
    self.head = presentNode
def traverse(self) :
    presentNode = self.head
   while presentNode:
     print("DATA VALUE = ",presentNode.data)
     presentNode = presentNode.refNext

Execution

objNode1 = Node(1)
objNode2 = Node(2)
objNode3 = Node(3)
objNode4 = Node(4)
linkObj = Linked_list( )
#head of the linked list to first object
linkObj.head = objNode1
# reference of the first node object to second object
linkObj.head.refNext = objNode2
obj'Node2 . refNext = objNode3
objNode3.refNext = objNode4
print("traverse before reversing")
linkObj.traverse( )
linkObj.reverse( )
print("traverse after reversing")
linkObj.traverse( )

Output

traverse before reversing
DATA VALUE = 1
DATA VALUE = 2
DATA VALUE = 3
DATA VALUE = 4
traverse after reversing
DATA VALUE = 4
DATA VALUE = 3
DATA VALUE = 2
DATA VALUE = 1

 

 

Python Interview Questions on Linked List Read More »