Python

Python Data Presistence – Statements

Python Data Presistence – Statements

Python interpreter treats any text (either in interactive mode or in a script) that ends with the Entering key (translated as ‘\n’ and called newline character) as a statement. If it is valid as per syntax rules of Python, it will be executed otherwise a relevant error message is displayed.

Example

>>> “Hello World”
‘Hello World’
>>> Hello world
File “<stdin>”, line 1
Hello world

SyntaxError: invalid syntax

In the first case, the sequence of characters enclosed within quotes is a valid Python string object. However, the second statement is invalid because it doesn’t qualify as a representation of any Python object or identifier or statement, hence the message as SyntaxError is displayed.

Normally one physical line corresponds to one statement. Each statement starts at the first character position in the line, although it may leave certain leading whitespace in some cases (See Indents – next topic). Occasionally you may want to show a long statement spanning multiple lines. The ‘V character works as a continuation symbol in such a case.

Example

>>> zen=”Beautiful is better than ugly. \
… Explicit is better than implicit. \
… Simple is better than complex.”
>>> zen
‘Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex.’

This is applicable for script also. In order to write an expression you would like to use two separate lines for numerator and denominator instead of a single line as shown below:

Example

>>> a=10
>>> b=5
>>> ratio=( pow ( a , 2 ) + ( pow ( b , 2 ) ) ) /  \
. . . ( pow ( a , 2 ) – ( pow ( b , 2 ) ) )
>>>

Here pow ( ) is a built-in function that computes the square of a number. You will learn more built-in functions later in this book.
The use of a backslash symbol (\) is not necessary if items in a list, tuple, or dictionary object spill over multiple lines. (Plenty of new terms, isn’t it? Never mind. Have patience!)

Example

>>> marks=[34,65,92,55,71,
. . . 21,82,39,60,41]
>>> marks
[34, 65, 92, 55, 71, 21, 82, 39, 60, 41]

 

Python Data Presistence – Statements Read More »

Python Data Presistence – Identifiers

Python Data Presistence – Identifiers

Python identifiers are the various programming elements such as keywords, variables, functions/methods, modules, packages, and classes by suitable name. Keywords are reserved words with predefined meanings in Python interpreter. Obviously, keywords can’t be used as the name of other elements as functions etc. Python language currently has 33 keywords. Enter the following statement in Python’s interactive console. The list of keywords gets displayed!

Example

>>> import keyword
>>> print (keyword.kwlist)
[‘False ‘, ‘None’, ‘True’, ‘ and’, ‘as’, ‘assert’, ‘break’ , ‘class’, ‘continue ‘, ‘def’, ‘del’, ‘elif’, ‘ else’ , ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘ if’, 1 import’, ‘in’, ‘is’ , ‘lambda’, ‘nonlocal’, ‘ not’ , ‘while’ ‘or’, ‘pass’, ‘raise ‘return’, ‘try’, ‘with’, ‘yield’]

Apart from keywords, you can choose any name (preferably cryptic but indicative of its purpose) to identify other elements in your program. However, only alphabets (upper or lowercase), digits, and underscore symbols (‘_’) may be used. As a convention, the name of the class starts with an uppercase alphabet, whereas the name of the function/method starts with the lowercase alphabet. The name of a variable normally starts with an alphabet, but in special cases, an underscore symbol (sometimes double underscore ) is seen to be the first character of the variable’s name.

Some examples of valid and invalid identifiers:

Valid identifiers

Invalid identifiers

name, FileName, yrlseml, EMP, roll_no, sum_of_dig,

_price, _salary, _ function_

123, sub-1, yr1.sem1, roll no, ‘price’, *marks*

 

Python Data Presistence – Identifiers Read More »

Selenium Grid Tutorial: Hub & Node (with Example) | What is Selenium Grid?

Selenium Python – Selenium-Grid

Parallel execution of tests is made possible through Seleniumthrough its Grid component. We come across scenarios like executing tests for cross-browser verification or executing a huge test suite by splitting it into smaller suites in parallel to save time. For all these, the Grid component is useful and effective as it allows parallel test execution.

Structure

  • Selenium-Grid
  • Creating hub
  • Creating nodes
  • Executing tests in parallel

Objective

In this chapter, we learn how to s tup Selenium-Grid in our local system. We understand what is a hub and a node, and how we set them up. In this chapter, we will set up a hub that will act as a central server and receive requests. We will have a Chrome node and a
Firefox node to complete the Grid for execution.

Selenium-Grid

An important component of Selenium is the Selenium-Grid. It allows us to run our tests in parallel, which helps in saving time and cost. To set up the Selenium-Grid, we need to first download the Selenium standalone server from: https://www.seleniumhq.org/download/
After we have downloaded the server JAR file, we will store it in a folder. This JAR file can now be invoked in two different modes to set up the Grid:

  • The hub
  • The node

A hub is a central server that receives the request to execute the test. It will send the test to the node in the Grid which matches the description in the test. While anode is a machine and browser combination where the actual execution of the test takes place.
Let us see a Grid setup, with the help of the following diagram:

 

Selenium Python - Selenium-Grid chapter 12 img 1

In the above diagram, we can see that the hub will receive the test execution request, which will get passed on to the matching node for actual execution. As the test is executed at the node, the result is passed back to the hub. The information, about the browser, and the operating system on which the test is to be executed, is present in the test script which the hub receives. Then the test commands are sent to the matched node for the actual execution.

We will now set up a Grid with one hub and two nodes—one for Chrome and another for Firefox. Let us see the commands for it.

Setting up the hub

To set up the hub, we need to open the Command Prompt window and go to the folder where our standalone JAR file is present. There we need to type the following command:

D:\work\jarfile>java . jan selenium.server-standalone-3.141.59.jan-role hub

In the above command, we are executing the standalone JAR file using the role flag that uses the value hub. So it will execute the server in the hub mode. By default, it will start the hub on port 4444.
If we want to change the port, we can use the – port flag and provide a value to it. For example:

D:\work\jarfile>java . jan selenium-server-standalone-3.141.59.jan-role hub-port 6666

If you are working with a different Selenium standalone server version, the version number will change for you in here.
Once the hub has started, you can verify it using the following steps:

  1. Open a browser.
  2. Type this URL:
    http://localhost:4444/grid/console
  3. If all is working fine, you should be able to see the following:

 

Selenium Python - Selenium-Grid chapter 12 img 4

At the Command Prompt, we will see the following:

D:\work\Jarfiles>java - jar selenium-server-standalone-3.141.59.jar - role hub
17:17:17.540 INFO [GridLaunchV3.parse] - selenium server version: 3.141.59, revision: e82
be7d358
17:17:17.540 INFO [GridLaunchV3.lambda$buildLaunchers$5] - Launching selenium Grid hub on port: 4444
2019-05-27 17:17:18.139: INFO: : main : Logging initialized @1218ms to org.seleniumhq.jetty9.util.log.stdErrLog
17:17:18.576 INFO [Hub.start] - selenium Grid hub is up and running
17:17:18.576 INFO [Hub.start] - Nodes should register to http://192.168.0.109:4444/grid/register/
17:17:18.576 INFO [Hub.start] - Clients should connect to http://192.168.0.109:4444/wb/hub

Setting a Chrome node on a Windows machine

To set a Chrome node on a Windows machine, we will have to download the Selenium standalone server on that machine and execute it in the node mode. To do this, we will have to execute this command:

D:\work\JarFiles>java - Dwebdriver.chrome.driver="D:\work\JarFiles\resource\chromedriver.exe" - jar selenium-server-standalone-3.141.59-Jar-role - hub http://localhost:4444/grid/register - browser "browsername-chrome" - post5556

In this command, we are providing a path to the Chrome driver as per the location in our system, that is, Dwebdriver. chrome. driver=”D: \ WORK\DarFiles\nesource\chromedriver.exe”. Then we set the role flag to be the node. Then we provide the hub flag, where we point to the hub location: http://localhost:4444/grid/register. We set the browser flag to chrome and the port flag to 5556.
At the script level, we will be making some changes in the setup method, which is as follows:

def setup(self):
    self.driver = webdriver.Remote(
         command_executor="http://Localhost:4444/wd/hub",
         desired_capabilities={
              "browserName":"chrome",
     })
   self.base_url = "http://practice.bpbonline.com/catalog/index.php"

Here, we create an instance of the remote WebDriver, pass the details of the hub and in desired capabilities variable, we pass information for the browser, on which we want to execute our test, in this case, Chrome. We will discuss more desired capabilities a little later in the chapter. So when we execute the script, the commands are sent to the hub. It fetches the information to find the node on which the actual test is to be executed and sends the commands to it. In this case, it will send the commands to a node that is registered with a Chrome browser.

Please take a look at the following screenshot where we have entered all the details:

 

Selenium Python - Selenium-Grid chapter 12 img 8

Setting a Firefox node on a Windows machine

To set a Firefox node on a Windows machine, we will have to download the Selenium standalone server on that machine and execute it in the node mode. To do this we will have to execute this command:

D:\work\JarFiles>java - Dwebdriver.chrome.driver="D:\work\JarFiles\resource\getkodriver.exe" - jar selenium-server-standalone-3.141.59-Jar-role - hub http://localhost:4444/grid/register - browser "browsername-firebox" - post5557

In this command, we are providing the path to the gecko driver as per the location in our system: Dwebdriver. gecko. driver=”D: \WORK\ DarFiles\resource\geckodriver. exe”. Then we set the role flag to be a node. Then we provide the hub flag, where we point to the hub location: http: //localhost:4444/grid/register. We set the browser flag to firefox and the port flag to 5557.

At the script level, we will be making some changes in the setup method:

def setup(self):
    self.driver = webdriver.Remote(
         command_executor="http://Localhost:4444/wd/hub",
         desired_capabilities={
               "browserName":"firebox",
})
self.base_url = "http://practice.bpbonline.com/catalog/index.php"

Here, we create an instance of the remote WebDriver, pass the details of the hub and in desired capabilities variable, we pass information for the browser, on which we want to execute our test, in this case, the Firefox browser. We will discuss more desired capabilities a little later in the chapter. So when we execute the script, the commands are sent to the hub. It fetches the information to find the node on which the actual test is to be executed and sends the commands to it. In this case, it will send the commands to a node that is registered with a Firefox browser:

 

Selenium Python - Selenium-Grid chapter 12 img 11

Executing tests in parallel

To execute the tests in parallel, on the Chrome and Firefox browser together, we will initiate them. So the test execution commands will reach the hub, and the hub will direct them to their respective nodes. In this case, the tests are directed to Chrome browser machine, and Firefox browser machine:

 

Selenium Python - Selenium-Grid chapter 12 img 12

Desired capabilities

To set the test environment settings at the browser level, we have some properties associated with each browser that we can set. So at the time of execution, whenever the browser instance will be invoked it will be set with those browser properties. Internet Explorer, Chrome, and Firefox come with their own key-value pair.
In our above test scripts, we have used desired capabilities, to set the browser key-value to Firefox or Chrome, respectively:

desired_capabilities={
“browserName”: “firefox”.,}

desired_capabilities={
“browserName”: “chrome”,}

Conclusion

In this chapter, we understood the usage of an important component of Selenium which allows us to run tests in parallel. We understood how we establish the Selenium server in hub mode and node mode, and instantiate the remote Web’’)river at the script level to run our tests in the Grid.

Related Articles:

Selenium Grid Tutorial: Hub & Node (with Example) | What is Selenium Grid? Read More »

Locators in Selenium- How To Locate Elements On Web-page?

Selenium Python – Locators in Selenium

Introduction

When we try to automate a web application, there are two important steps to consider. One is to identify the object uniquely on which we would want to perform the action. The second is to perform the action on the identified object. To identify the object uniquely on the web page, Selenium provides us with some locator strategies. In this chapter, we will discuss and explore them.

Structure

  • What is a locator?
  • Different types of locators
  • Where are locators used?

Objective

When working with open source technology like Selenium, it is crucial for us to understand that as end-user what strategy Selenium uses to identify an object on a page. As we are going to write scripts to automate applications at hand, we will have to provide object information using one of the locator strategies which Selenium will use to identify the object on the page so that the required action can be performed on it.

What is a locator?

Locator is a technique to identify the object on a page uniquely by using different identification methods. Once the object is identified, the action can be performed on it. Selenium provides us with the following locator techniques to identify the object on the page:

  • ID
  • NAME
  • XPATH
  • CSS
  • DOM
  • LINKTEXT
  • PARTIALLINKTEXT

To understand the different strategies of the locators, which Selenium uses to identify the object on the page, we will take the example of an HTML code snippet from our web application: http://practice.bpbonline.com/catalog/index.php my account page, which we see,
when we click the My Account link of the home page. The idea is to explore the HTML code associated with the E-mail Address field,
Password field, and the Sign In button. So let us have a look at it:

Selenium Python - Locators in Selenium chapter 3 img 1

If we right-click the HTML page and select View page source. Refer to the following screenshot:

Selenium Python - Locators in Selenium chapter 3 img 2

We can see the HTML content associated with the web page. It is displayed as follows:

 

    <form name"login" action="http://practice.bpbonline.com/catalog/login.php"action=process" method="post"><input type="hidden"
name="formid" value="46fedd827e8b83241e4cebff3c6046ae"/>
   <table border="0" cellspecing="e" cellpadding="2" width"100%">
   <tr>
    <td class="filedkey">E-mail Address:</td>
    <td class="filedvalue"><input type="text" name="email..address"/><td>
 </tr>
 <tr>
   <td class="filedkey"password:</td>
   <td class="filedvalue"><input type="password" name="password" maxlength="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="tdblink"><button id="tdb1" type="submit">sign In</button></span><script type="text/javascript $("#tdb1").button({icons:{primary::ui.icon-key"}}).addclass("ui-priority-primary").parent( ).removeClass("tdblink"):
</script></p>

</form>

As we have seen, the above HTML content is associated with three objects – username and password fields, and sign-in button, let us try to understand the different locator strategies Selenium can use to identify them so that an action can be performed on them as our automation script executes. So, the following is explained below:

• ID: The ID locator is fetched from the ID attribute of an HTML element. If the HTML element of interest has an ID attribute, we use it to identify the object uniquely. The example of this is the Sign In button, which has the id = tdblxbutton id=”tdbl” type=”submit”>Sign In</button>

• NAME: This attribute is fetched from the NAME attribute of the HTML element. The data associated with this property of the HTML element is used to identify the object uniquely on the web page. Examples of this property username, and password fields:
<input type=”text” name=”email_address” />
<input type=”password” name=”password” maxlength=”40″ />

• XPATH: The path traversed to reach the node of interest in an XML document is known as XPATH. To create the XPATH locator for an element, we look at an HTML document as if it is an XML document, and then traverse the path to reach it. The XPATH can either be a relative or an absolute one:

  • A relative XPATH will be in relation to a landmark node. A node that has a strong identifier like an ID or NAME. It uses / / in its path creation. Example: // input[@name=”email_addpess”]
  • An absolute XPATH starts from the root node HTML. It uses a single slash /. It is more prone to changes if the document structure undergoes changes during the development of the application, so it is generally avoided.
    Example:/HTML/body/div[2] / f orm[0] /table/ tbody/tr[2]/input

• CSS: It stands for Cascading Style Sheets. We can use this as well to identify the objects uniquely on the web page. The syntax is as follows:

  • If the HTML of the object has an ID attribute then, css=#ID, for example, css=#tdbl
  • Else, css=HTMLtag[prop=value], for example, css=input [namie^ email_address’ ]

• DOM: It stands for Document Object Model. It allows object identification by using the HTML tag name associated with the object.

• LINKTEXT: Generally, whenever we encounter a link in the application we can use it to identify the object on the page. For example, the My Account link can be identified using the same link text as seen on the web page

• PARTIAL LINK TEXT: We can also use a subpart of a complete text of the link to identify it on the web page and then perform actions on it.

It is important to use an appropriate locator to identify the object on the page, which is unique, helps in quick identification of the object, and is robust to application changes during the development process. Generally, if the object HTML has IDor NAME we use it to identify the object on the page. Then we use XPATH, followed by CSS and the last option is DOM. If it is a link, we always use LINKTEXT or PARTIAL LINK TEXT to identify the element on the page. So ideally, this should be the approach we need to take.

Conclusion

In this chapter we discussed the concept of locators; we understood its various types. We also saw where and how they would be needed. These locator strategies are standard in Selenium. They are not going to get modified in any version, and have been consistent with old versions as well. Lastly, we need to keep in mind that the locator strategy we are choosing to identify the object has to be robust and help to locate the object quickly on the page. In the next chapter, we will learn the steps to set up Selenium and Eclipse IDE on Windows OS.

Related Articles:

Locators in Selenium- How To Locate Elements On Web-page? Read More »

Selenium IDE Tutorial For Beginners | What Is Selenium IDE

Selenium Python – Selenium IDE

In this chapter, we will discuss the Selenium IDE component. This component allows us to record and playback our tests. It is an integral component of the Selenium project and has been recently upgraded and brought back into function with the help of the organization Appiitools.

Selenium IDE, also known as SIDE stands for Selenium Integrated Development Environment. It is one of the four projects of the Selenium ecosystem. The earlier version of Selenium IDE worked only on the Firefox browser. But the changes in the Firefox browser from version 55 didn’t allow Selenium IDE integration. At this juncture, Appiitools helped the Selenium community with a group of dedicated engineers (https://github.com/seleniumHQ/selenium-ide/graphs/ contributors) and brought back Selenium IDE. The current version supports both Firefox and Chrome browsers.

Structure

  • Installing Selenium IDE • Walkthrough of the demo application
  • Creating our first test
  • Selenium IDE commands

Objective

The Selenium IDE component is used to record and play backtests. The current version, which supports both Firefox and Chrome browsers, has a rich feature list. It now allows running tests in parallel, supports JavaScript execution, allows usage of if conditions, and many such cool things. To know more about it, read the article available here:

https://applitools.com/blog/why-Selenium-ide-20197utm_referrer=https://www.google.com/

Installation of Selenium IDE

To install Selenium IDE, we have to follow the below-mentioned instructions:
1. Open the Chrome browser and follow this link:
https://www.seleniumhq.org/selenium-ide/
2. Here, we need to select the choice, Chrome or Firefox download.
3. It will open a new browser window, with the option asking Add to Chrome as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 1

4. You need to select it.
5. It will launch a popup, asking permission. Select Add extension as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 2

6. You will now be able to see the Selenium IDE icon in your browser menu bar. N

After installing the Selenium IDE, we need to have a look at a demo web application. We will need this application to understand a few concepts of test automation using Selenium. So let us get introduced to it.

Introduction to demo web application

We will consider a demo web application, which is an e-commerce website. As we learn the concepts of test automation with Selenium using Python as a programming language, we will use functional flows from the web application. We will also look at a few other web applications as we learn to handle some specific Html elements and deal with some specific scenarios.

The URL of the demo application is http://practice.bpbonline.com/ catalog/index.php
As you follow the URL, you will see the following screen:

Selenium Python - Selenium IDE chapter 2 img 3

Following are some of the specific functional flows in the application:

  • Register the user
  • Login and logout of the user
  • Change profile of the user
  • Change the password of the user
  • Buy product
  • Search product

From the previous list of application business scenarios, we will take the login-logout business scenario as a sample one for our first record and playback script in Selenium IDE. Record script basically means with the help of Selenium IDE, we will capture the user actions as we perform the steps to login and then log out from the application. These will be captured by the Selenium IDE, as commands. It will then be played back, where Selenium IDE will launch the browser and will be able to perform the exact steps to log in and log out of the application without any user intervention.

Let’s perform the following steps for login-logout:
1. Open the application using the URL: http://practice. bpbonline.com/catalog/index.php
2. Click on the My Account link.
3. Fill in the user details; you can use the following user credentials:

Or you can also create your own account, by registering yourself and then using those credentials.
4. Click on the Sign-in button
5. Click on the Log Off link
6. Click on the Continue link
Please note the above scenario is not a test case, as we have added no steps for the validation. There are only test steps.

Record and playback in Selenium IDE

The following are the steps we need to perform for recording and playing back in Selenium IDE:
1. Open Chrome browser.
2. On it, click on the Selenium IDE icon. It will popup Selenium IDE window as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 4

3. Here, we will select Record a new test in a new project.
4. Provide a project name on the next screen.
5. Then in the next screen, provide the base URL for recording:

Selenium Python - Selenium IDE chapter 2 img 5

6. Click here on START RECORDING.
7. This will launch the browser with the application URL, and a message Selenium IDE is recording… Now, whatever steps we perform on the browser, will all be captured by the IDE. Check the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 6

7. After performing all the steps, close the browser, and on the Selenium IDE, click the OP (stop button).
8. Provide a name to the test, and save the project at a location in your system.
9. After the login logout steps are captured, your text should look as follows:

Selenium Python - Selenium IDE chapter 2 img 7

It could be possible that Selenium IDE may capture some other locator value for the same object which you see in the target field, which is absolutely fine, as long as you are able to replay the test successfully.

There could be some other extra steps captured as Selenium IDE captures every mouse action, we need to delete those extra steps and only have those steps that match our manual action.

Structure of Selenium IDE Test

If we look at the above image, there are three columns that form a Selenium IDE test:
• Command, which provides information of the action being performed.
• Target, which talks about the object on which the action is to be performed.
• Value, which talks about the data which will be used in the test.
The commands of Selenium IDE fall under three categories, as follows:
• Action: Those commands, which change the state of the application.
• Assertion: Those commands which verify the state of the application after it is performed. There are two types of assertion commands that are as follows:

  1. Verify: These commands, if they fail, still allow execution of the next step in the test case.
  2. Assert: These commands, if they fail, don’t allow the execution of the next step in the test case.

• Accessor: Those commands which allow storage of value, or creation of variables to be used in the test.

Let us write the login-logout scenario, this time with the validation steps:

  1. Open the application.
  2. Click the My Account link.
  3. Type the E-mail address and Password.
  4. Click the Sign In button.
  5. Verify the My Account Information text on the screen.
  6. Click on the Log Off link.
  7. Click on the Continue link.
  8. Verify Welcome to BPB Online text on the screen.

To record the above scenario, we will perform the same steps as we did for the login-logout one, except for steps 5 and 8, where we will perform the following.
9. Add the Command verify text during the recording after you have logged in. Refer to the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 8

10. Now we will select the Target for that we click on the icon
[↵]and highlight and click the element, whose text we need to capture for verification. Refer to the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 9

11. We copy the text from here and put it in the Value field. So finally, our command would look like the following:

Selenium Python - Selenium IDE chapter 2 img 10

12. We will perform a similar action for step 8.
13. Complete the steps of recording, and save the test for playback. As you playback the test, you will see all the steps in green. Now let us try to see the action of failure by changing the text of My Account Information to Dunk. We will find out that although the test gets executed, reports failure on the verification step. The following screenshot shows the behavior:

Selenium Python - Selenium IDE chapter 2 img 11

14. Now, for the same test, if we change the command from verifying the text, to assert text We will see that the execution will get halted at the step of failure. This is shown as follows:
in green. Now let us try to see the action of failure by changing the text of My Account Information to Dunk. We will find out that although the test gets executed, reports failure on the verification step. The following screenshot shows the behavior:

Selenium Python - Selenium IDE chapter 2 img 12

14. Now, for the same test, if we change the Command from verifying ‘ text, to assert text we will see that the execution will get halted at the step of failure. This is shown as follows:

Selenium Python - Selenium IDE chapter 2 img 13

So there are three states of execution here:

  • Green: All pass
  • Red: Fail
  • White: Not executed

Conclusion

In this chapter, we discussed the Selenium IDE component. We saw how we could use it for recording and playing backtests. We could use Selenium IDE for proofing concepts, to see if our application supports Selenium or not. Sometimes we struggle to find a locator for an object, in such cases recording the scenario in Selenium IDE is also helpful. In our next chapter, we will discuss the concept of locators, what techniques Selenium uses to recognize objects on web applications.

Related Articles:

Selenium IDE Tutorial For Beginners | What Is Selenium IDE Read More »

Python Interview Questions on HR Questions

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

Python Interview Questions on HR Questions

Question 1:
Tell me about a time when you worked additional hours to finish a project.
Answer:
It’s important for your employer to see that you are dedicated to your work, and willing to put in extra hours when required or when a job calls for it. However, be careful when explaining. why you were called to work additional hours – for instance, did you have to stay late because you set goals poorly earlier in the process? Or on a more positive note, were you working additional hours because a client requested for a deadline to be moved up on short notice? Stress your competence and willingness to give 110% every time.

Question 2:
Tell me about a time when your performance exceeded the duties and requirements of your job.
Answer:
If you’re a great candidate for the position, this should be an easy question to answer – choose a time when you truly went above and beyond the call of duty, and put in additional work or voluntarily took on new responsibilities. Remain humble, and express gratitude for the learning opportunity, as well as confidence in your ability to give a repeat performance.

Question 3:
What is your driving attitude about work?
Answer:
There are many possible good answers to this question, and the interviewer primarily wants to see that you have a great passion for the job and that you will remain motivated in your career if hired. Some specific driving forces behind your success may include hard work, opportunity, growth potential, or success.

Question 4:
Do you take work home with you?
Answer:
It is important to first clarify that you are always willing to take work home when necessary, but you want to emphasize as well that it has not been an issue for you in the past. Highlight skills such as time management, goal-setting, and multitasking, which can all ensure that work is completed at work.

Question 5:
Describe a typical workday to me.
Answer:
There are several important components in your typical workday, and an interviewer may derive meaning from any or all of them, as well as from your ability to systematically lead him or her through the day. Start at the beginning of your day and proceed chronologically, making sure to emphasize steady productivity, time for review, goal-setting, and prioritizing, as well as some additional time to account for unexpected things that may arise.

Question 6:
Tell me about a time when you went out of your way at your previous job.
Answer:
Here it is best to use a specific example of the situation that required you to go out of your way, what your specific position would have required that you did, and how you went above that. Use concrete details, and be sure to include the results, as well as reflect on what you learned in the process.

Question 7:
Are you open to receiving feedback and criticisms on your job performance, and adjusting as necessary?
Answer:
This question has a pretty clear answer – yes – but you’ll need to display knowledge as to why this is important. Receiving feedback and criticism is one thing, but the most important part of that process is to then implement it into your daily work. Keep a good attitude, and express that you always appreciate constructive feedback.

Question 8:
What inspires you?
Answer:
You may find inspiration in nature, reading success stories, or mastering a difficult task, but it’s important that your inspiration is positively based and that you’re able to listen and tune into it when it appears. Keep this answer generally based in the professional world, but where applicable, it may stretch a bit into creative exercises in your personal life that, in turn, help you in achieving career objectives.

Question 9:
How do you inspire others?
Answer:
This may be a difficult question, as it is often hard to discern the effects of inspiration on others. Instead of offering a specific example of a time when you inspired someone, focus on general principles such as leading by example that you employ in your professional life. If possible, relate this to a quality that someone who inspired you possessed, and discuss the way you have modified or modeled it in your own work.

Question 10:
How do you make decisions?
Answer:
This is a great opportunity for you to wow your interviewer with your decisiveness, confidence, and organizational skills. Make sure that you outline a process for decision-making, and that you stress the importance of weighing your options, as well as in trusting intuition. If you answer this question skillfully and with ease, your interviewer will trust in your capability as a worker.

Question 11:
What are the most difficult decisions for you to make?
Answer:
Explain your relationship to decision-making, and a general synopsis of the process you take in making choices. If there is a particular type of decision that you often struggle with, such as those that involve other people, make sure to explain why that type of decision is tough for you, and how you are currently engaged in improving your skills.

Question 12:
When making a tough decision, how do you gather information?
Answer:
If you’re making a tough choice, it’s best to gather information from as many sources as possible. Lead the interviewer through your process of taking information from people in different areas, starting first with advice from experts in your field, feedback from coworkers or other clients, and looking analytically at your own past experiences.

Question 13:
Tell me about a decision you made that did not turn out well.
Answer:
Honesty and transparency are great values that your interviewer will appreciate – outline the choice you made, why you made it, the results of your poor decision – and finally (and most importantly!) what you learned from the decision. Give the interviewer reason to trust that you wouldn’t make a decision like that again in the future.

Question 14:
Are you able to make decisions quickly?
Answer:
You may be able to make decisions quickly, but be sure to communicate your skill in making sound, thorough decisions as well. Discuss the importance of making a decision quickly, and how you do so, as well as the necessity for each decision to first be well-informed.

Question 15:
Ten years ago, what were your career goals?
Answer:
In reflecting back on what your career goals were ten years ago, it’s important to show the ways in which you’ve made progress in that time. Draw distinct links between specific objectives that you’ve achieved, and speak candidly about how it felt to reach those goals. Remain positive, upbeat, and growth-oriented, even if you haven’t yet achieved all of the goals you set out to reach.

Question 16:
Tell me about a weakness you used to have, and how you changed it.
Answer:
Choose a non-professional weakness that you used to have, and outline the process you went through in order to grow past it. Explain the weakness itself, why it was problematic, the action steps you planned, how you achieved them, and the end result.

Question 17:
Tell me about your goal-setting process.
Answer:
When describing your goal-setting process, clearly outline the way that you create an outline for yourself. It may be helpful to offer an example of a particular goal you’ve set in the past, and use this as a starting point to guide the way you created action steps, check-in points, and how the goal was eventually achieved.

Question 18:
Tell me about a time when you solved a problem by creating actionable steps to follow.
Answer:
This question will help the interviewer to see how talented you are in outlining, problem resolution, and goal-setting. Explain thoroughly the procedure of outlining the problem, establishing steps to take, and then how you followed the steps (such as through check-in points along the way, or intermediary goals).

Question 19:
Where do you see yourself five years from now?
Answer:
Have some idea of where you would like to have advanced to in the position you’re applying for, over the next several years. Make sure that your future plans line up with you still working for the company, and stay positive about potential advancement. Focus on future opportunities, and what you’re looking forward to – but make sure your reasons for advancement are admirable, such as greater experience and the chance to learn, rather than simply being out for a higher salary.

Question 20:
When in a position, do you look for opportunities to promote?
Answer:
There’s a fine balance in this question – you want to show the interviewer that you have the initiative and motivation to advance in your career, but not at the expense of appearing opportunistic or selfishly motivated. Explain that you are always open to growth opportunities, and very willing to take on new responsibilities as your career advances.

Question 21:
On a scale of 1 to 10, how successful has your life been?
Answer:
Though you may still have a long list of goals to achieve, it’s important to keep this answer positively focused. Choose a high number between 7 and 9, and explain that you feel your life has been largely successful and satisfactory as a result of several specific achievements or experiences. Don’t go as high as a 10, as the interviewer may not believe your response or in your ability to reason critically.

Question 22:
What is your greatest goal in life?
Answer:
It’s okay for this answer to stray a bit into your personal life, but best if you can keep it professionally focused. While specific goals are great, if your personal goal doesn’t match up exactly with one of the company’s objectives, you’re better off keeping your goal a little more generic and encompassing, such as “success in my career” or “leading a happy and fulfilling life.” Keep your answer brief, and show a decisive nature – most importantly, make it clear that you’ve already thought about this question and know what you want.

Question 23:
Tell me about a time when you set a goal in your personal life and achieved it.
Answer:
The interviewer can see that you excel at setting goals in your professional life, but he or she also wants to know that you are consistent in your life and capable of setting goals outside of the office as well. Use an example such as making a goal to eat more healthily or to drink more water, and discuss what steps you outlined to achieve your goal, the process of taking action, and the final results as well.

Question 24:
What is your greatest goal in your career?
Answer:
Have a very specific goal of something you want to achieve in your career in mind, and be sure that it’s something the position clearly puts you in line to accomplish. Offer the goal as well as your plans to get there, and emphasize clear ways in which this position will be an opportunity to work toward the goal.

Question 25:
Tell me about a time when you achieved a goal.
Answer:
Start out with how you set the goal, and why you chose it. Then, take the interviewer through the process of outlining the goal, taking steps to achieve it, the outcome, and finally, how you felt after achieving it or the recognition you received. The most important part of this question includes the planning and implementation of strategies, so focus most of your time on explaining these aspects. However, the preliminary decisions and end results are also important, so make sure to include them as well.

Question 26:
What areas of your work would you still like to improve in? What are your plans to do this?
Answer:
While you may not want the interviewer to focus on things you could improve on, it’s important to be self-aware of your own growth opportunities. More importantly, you can impress an interviewer by having specific goals and actions outlined in order to facilitate your growth, even if your area of improvement is something as simple as increasing sales or finding new ways to create greater efficiency.

Question 27:
Tell me about your favorite book or newspaper.
Answer:
The interviewer will look at your answer to this question in order to determine your ability to analyze and review critically. Additionally, try to choose something that is on a topic related to your field or that embodies a theme important to your work, and be able to explain how it relates. Stay away from the controversial subjects matter, such as politics or religion.

Question 28:
If you could be rich or famous, which would you choose?
Answer:
This question speaks to your ability to think creatively, but your answer may also give great insight into your character. If you answer rich, your interviewer may interpret that you are self-confident and don’t seek approval from others and that you like to be rewarded for your work. If you choose famously, your interviewer may gather that you like to be well-known and to deal with people, and have the platform to deliver your message to others. Either way, it’s important to back up your answer with sound reasoning.

Question 29:
If you could trade places with anyone for a week, who would it be and why?
Answer:
This question is largely designed to test your ability to think on your feet, and to come up with a reasonable answer to an outside-the-box question. Whoever you choose, explain your S. answer in a logical manner, and offer specific professional reasons that led you to choose the individual.

Question 30:
What would you say if I told you that just from glancing over your resume, I can already see three spelling mistakes?
Answer:
Clearly, your resume should be absolutely spotless – and you should be confident that it is. If your interviewer tries to make you second-guess yourself here, remain calm and poised and assert with a polite smile that you would be quite surprised as you are positive that your resume is error-free.

Question 31:
Tell me about your worldview.
Answer:
This question is designed to offer insight into your personality, so be aware of how the interviewer will interpret your answer.
Speak openly and directly, and try to incorporate your own job skills into your outlook on life. For example, discuss your
beliefs on the ways that hard work and dedication can always bring success, or in how learning new things is one of life’s greatest gifts. It’s okay to expand into general life principles here, but try to keep your thoughts related to the professional field as well.

Question 32:
What is the biggest mistake someone could make in an interview?
Answer:
The biggest mistake that could be made in an interview is to be caught off guard! Make sure that you don’t commit whatever you answer here, and additionally be prepared for all questions. Other common mistakes include asking too early in the hiring process about job benefits, not having questions prepared when the interviewer asks if you have questions, arriving late, dressing casually or sloppily, or showing ignorance of the position.

Question 33:
If you won the $50m lotteries, what would you do with the money?
Answer:
While a question such as this may seem out of place in a job interview, it’s important to display your creative thinking and your ability to think on the spot. It’s also helpful if you choose something admirable, yet believable, to do with the money such as donate the first seventy percent to a charitable cause, and divide the remainder among gifts for friends, family, and of course, yourself.

Question 34:
Is there ever a time when honesty isn’t appropriate in the workplace?
Answer:
This may be a difficult question, but the only time that honesty isn’t appropriate in the workplace is perhaps when you’re feeling anger or another emotion that is best kept to yourself. If this is the case, explain simply that it is best to put some thoughts aside, and clarify that the process of keeping some thoughts quiet is often enough to smooth over any unsettled emotions, thus eliminating the problem.

35: If you could travel anywhere in the world, where would it – be?
Answer:
This question is meant to allow you to be creative – so go ahead s and stretch your thoughts to come up with a unique answer. However, be sure to keep your answer professionally-minded. For example, choose somewhere rich with culture or that would expose you to a new experience, rather than going on an. expensive cruise through the Bahamas.

Question 36:
What would I find in your refrigerator right now?
Answer:
An interviewer may ask a creative question such as this in order to discern your ability to answer unexpected questions calmly, or, to try to gain some insight into your personality. For example, candidates with a refrigerator full of junk food or \ take-out may be more likely to be under stress or have health issues, while a candidate with a balanced refrigerator full of nutritious staples may be more likely to lead a balanced mental life, as well.

Question 37:
If you could play any sport professionally, what would it be and what aspect draws you to it?
Answer:
Even if you don’t know much about professional sports, this question might be a great opportunity to highlight some of your greatest professional working skills. For example, you may choose to play professional basketball, because you admire the teamwork and coordination that goes into creating a solid play. Or, you may choose to play professional tennis, because you consider yourself to be a go-getter with a solid work ethic and great dedication to perfecting your craft. Explain your choice simply to the interviewer without elaborating on drawn-out sports metaphors, and be sure to point out specific areas or skills in which you excel.

Question 38:
Who were the presidential and vice-presidential candidates in the 2008 elections?
Answer:
This question, plain and simple, is intended as a gauge of your intelligence and awareness. If you miss this question, you may well fail the interview. Offer your response with a polite smile, because you understand that there are some individuals who probably miss this question.

Question 39:
Explain X task in a few short sentences as you would to a second-grader.
Answer:
An interviewer may ask you to break down a normal job task that you would complete in a manner that a child could understand, in part to test your knowledge of the task’s inner workings – but in larger part, to test your ability to explain a process in simple, basic terms. While you and your coworkers may be able to converse using highly technical language, being able to simplify a process is an important skill for any employee to have.

Question 40:
If you could compare yourself to any animal, what would it be?
Answer:
Many interviewers ask this question, and it’s not to determine which character traits you think you embody – instead, the interviewer wants to see that you can think outside the box and that you’re able to reason your way through any situation. Regardless of what animal you answer, be sure that you provide a thorough reason for your choice.

Question 41:
Who is your hero?
Answer:
Your hero may be your mother or father, an old professor, someone successful in your field, or perhaps even Wonder Woman – but keep your reasoning for your chosen profession, and be prepared to offer a logical train of thought. Choose someone who embodies values that are important in your chosen career field, and answer the question with a smile and a sense of passion.

Question 42:
Who would play you in the movie about your life?
Answer:
As with many creative questions that challenge an interviewee to think outside the box, the answer to this question is not as important as how you answer it. Choose a professional, and relatively non-controversial actor or actress, and then be prepared to offer specific reasoning for your choice, employing important skills or traits you possess.

Question 43:
Name five people, alive or dead, that would be at your ideal dinner party.
Answer:
Smile and sound excited at the opportunity to think outside the box when asked this question, even if it seems to come from left field. Choose dynamic, inspiring individuals who you could truly learn from, and explain what each of them would have to offer to the conversation. Don’t forget to include yourself, and to talk about what you would bring to the conversation as well!

Question 44:
What is customer service?
Answer:
Customer service can be many things – and the most important consideration in this question is that you have a creative
answer. Demonstrate your ability to think outside the box by offering a confident answer that goes past a basic definition, and that shows you have truly considered your own individual view of what it means to take care of your customers. The thoughtful consideration you hold for customers will speak for, itself.

Question 45:
Tell me about a time when you went out of your way for a customer.
Answer:
It’s important that you offer an example of a time you truly went out of your way – be careful not to confuse something that felt like a big effort on your part, with something your employer would expect you to do anyway. Offer an example of the customer’s problems, what you did to solve them, and the way the customer responded after you took care of the situation.

Question 46:
How do you gain confidence from customers?
Answer:
This is a very open-ended question that allows you to show your customer service skills to the interviewer. There are many possible answers, and it is best to choose something that you’ve had a great experience with, such as “by handling situations with transparency,” “offering rewards,” or “focusing on great communication.” Offer specific examples of successes you’ve had.

Question 47:
Tell me about a time when a customer was upset or agitated – how did you handle the situation?
Answer:
Similarly to handling a dispute with another employee, the most important part to answering this question is to first set up the scenario, offer a step-by-step guide to your particular conflict resolution style, and end by describing the way the conflict was resolved. Be sure that in answering questions about your own conflict resolution style, that you emphasize the importance of open communication and understanding from both parties, as well as a willingness to reach a compromise or other solution.

Question 48:
When can you make an exception for a customer?
Answer:
Exceptions for customers can generally be made when in accordance with company policy or when directed by a supervisor. Display an understanding of the types of situations in which an exception should be considered, such as when a customer has endured a particular hardship, had a complication with an order, or at a request.

Question 49:
What would you do in a situation where you were needed by both a customer and your boss?
Answer:
While both your customer and your boss have different needs of you and are very important to your success as a worker, it is always best to try to attend to your customer first – however, the key is explaining to your boss why you are needed urgently. by the customer, and then to assure your boss that you will attend to his or her needs as soon as possible (unless it’s absolutely an urgent matter).

Question 50:
What is the most important aspect of customer service?
Answer:
While many people would simply state that customer satisfaction is the most important aspect of customer service, it’s important to be able to elaborate on other important techniques in customer service situations. Explain why customer service is such a key part of business, and be sure to expand on the aspect that you deem to be the most important in a way that is reasoned and well-thought-out.

Question 51:
Is it best to create low or high expectations for a customer?
Answer:
You may answer this question either way (after, of course, determining that the company does not have a clear opinion on the matter). However, no matter which way you answer the question, you must display a thorough thought process and very clear reasoning for the option you chose. Offer pros and cons of each, and include the ultimate point that tips the scale in favor of your chosen answer.
And Finally Good Luck!

Python Interview Questions on HR Questions Read More »

Python Interview Questions on HTML/XML in Python

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

Python Interview Questions on HTML/XML in Python

Question 1:
What module is used to handle URLs?
Answer:
urlparse.

Question 2:
Illustrate parsing a URL into a tuple.
Answer:
Import urlparse
myTuple = urlparse.urlparse( “http://wivzv.example.com/mydirectory/ myfile.html”)

Question 3:
What modules does Python provide for opening and fetching data from URLs?
Answer:
urllib and urllib2.

Question 4:
What is the main difference between the urllib and urllib2 modules?
Answer:
The urllib2 module can accept a Request object, which allows the specification of headers.

Question 5:
Illustrate opening and printing a web-based URL.
Answer:
import urllib ,
myURL =urllib.urlopen(“http:/lwww.example.org/myfile.html”)
myBuffer = myURL.read( )
print myBuffer

Question 6:
How is the request information retrieved?
Answer:
Using the .info( ) method on an open URL.

Question 7:
To process the contents of an HTML file, what module is used?
Answer:
HTMLParser.

Question 8:
How is the HTMLParser used?
Answer:
By subclassing the HTMLParser.HTMLParser class, and inserting processing for the tags of interest, instantiating it, then by calling the .feed method of the resulting object.

Question 9:
What modules are used to manage cookies?
Answer:
The urllib and cookielib modules.

Question 10:
Illustrate retrieving a cookies from a URL.
Answer:
Import urllib2
Import cookielib
myjar= cookielib.LWPCookieJar( )
myOpener = urllib2.build_opener(
urllib2.HTTPCookieProcessor(myJar))
urllib2. ins tall_opener( myOpener)
myRequest =urllib2. RequestC’http:!/www.example.org/”)
myHTML = urllib2.urlopen(my Request)
for cookie in enumerate(myjar)
print cookie

Question 11:
In managing XML documents, what is the module most often used?
Answer:
xml.dom Also, the minidom class within xml.dom

Question 12:
Illustrate opening an xml document.
Answer:
from xml.dom import minidom myTree = minidom.parse(‘myXML.xml’) print myTree.toxmlO

Question 13:
What tools are available to determine if an xml file is well formed?
Answer:
Using a try, except block, and attempting to parse the xml file through the generic parser available in xml.sax

Question 14:
How are xml element attributes accessed?
Answer:
Using the minidom parser, then the .getAttribute method on returned child nodes.

Question 15:
What method is used to determine if a child node includes a particular attribute?
Answer:
Using the .hasAttribute method which will return true if the attribute is defined.

Question 16:
What is the difference between the .toxml and .toprettyxml methods?
Answer:
The .toprettyxml method will indent the node contents appropriately.

Question 17:
What is expat module and what is it used for?
Answer:
The expat module is a non-validating XML parser. It is used to process XML very quickly, with minimal regard for the formal correctness of the XML being parsed.

Question 18:
What does the .dom stand for in the xml.dom module?
Answer:
Document Object Model.

Question 19:
What parsers are available for XML?
Answer:
Sax, expat, and minidom

Question 20:
Illustrate direct node access in an XML file.
Answer:
from xml.dom import minidom myXML = minidom.parse(”myXML.xml”)
myNodes = myXML.childNode s print childNodes[0].toprettyxml()

Python Interview Questions on HTML/XML in Python Read More »

Python Interview Questions on Python Internet Communication

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

Python Interview Questions on Python Internet Communication

Question 1:
What are some supported socket communications protocol families?
Answer:
AF_INET (IPV4, TCP, UDP), AF_INET6 (IPV6, TCP, UDP), AF_UNIX

Question 2:
What are some socket types in Python?
Answer:
SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET

Question 3:
Illustrate opening a server side socket for incoming packets.
Answer:
import socket
mySock = socket.socket.(AFJNET, SOCK_STREAM)
mySock.bind((interfaceName, portNumber))
mySock.listen(3)

Question 4:
Illustrate opening a client-side socket for sending data.
Answer:
import socket
mySock = socket.socket.(AFJNET, SOCK_STREAM)
my Sock ,connect((interfaceName, portNumber))
mySock.send(data)

Question 5:
What module is used to send email?
Answer:
smtplib.

Question 6:
Illustrate connecting to a mail server, in preparation for sending an email.
Answer:
import smtplib
mySMTP = smtplib.SMTP(‘mail.example.org’)

Question 7:
Illustrate sending an email, then closing the connection.
Answer:
import smtplib
mySMTP = smtplib.SMTP(‘mail.example.org’)
myResult = mySMTP.sendmail(‘[email protected]’,
[email protected]’, message)
mySMTP.quit( )

Question 8:
What module is used to retrieve email from a server?
Answer:
poplib.

Question 9:
Illustrate retrieving the number of messages available on a mail server.
Answer:
Import poplib .
myPOP = poplib.POP3(‘mail.example.org’)
mPOP.user(“[email protected]’)
mPOP.pass_(“myPassword”)
myMessageCount = len(mPOP.list()[l])

Question 10:
What module is used to support file transfers?
Answer:
ftplib.

Question 11:
Illustrate opening a FTP connection.
Answer:
import ftplib
myFTP = ftplib.FTP(/ftp.example.org,/ ‘anonymous’, ‘[email protected]’)

Question 12:
What method is used to retrieve a list of files on an active FTP connection?
Answer:
•dir( )

Question 13:
Illustrate using FTP to retrieve a file and write it to the local disk.
Answer:
import ftplib
myFTP = ftplib.FTP(‘ftp.example.org’, ‘anonymous’,
[email protected]’)
myFile = openC’localfile.txt”, “wb”)
myFTP.retbinaryCRETR remotefile.txt’, myFile.write)
myFTP.quit( ) .
myFile.close( )

Question 14:
What happens if the .quit() method is not called on FTP connections.
Answer:
A resource leak can occur if multiple FTP connections are opened but never closed.

Question 15:
Illustrate retrieving a list of files from an FTP server
Answer:
import ftplib
myFTP = ftplib.FTP(ftp.example.org’, ‘anonymous’,
‘myemail@example. org’)
myFileList = myFTP.dirO
print myFileList
myFTP.quit()

Question 16:
What does the SOCK_STREAM socket type signify?
Answer:
This is a TCP Socket type.

Question 17:
What does the SOCK_DGRAM signify?
Answer:
This is a UDP socket type.

Question 18:
How is the .shutdown method used?
Answer:
.shutdownO is called before .close to flush buffers and ensure a timely shutdown of the connection. It can be called using SHUTRD, SHUT_WR or SHUT_RDWR to end receiving, sending, or both.

Question 19:
What does socket.accept() return?
Answer:
The conn and address objects. Conn is a new socket object able to send or receive data, and the address object is the address of the remote host.

Question 20:
How is the remote address of a socket returned?
Answer:
Using the .getpeernameQ method of the connected socket.

Python Interview Questions on Python Internet Communication Read More »

Python Interview Questions on Python Database Interface

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

Python Interview Questions on Python Database Interface

Question 1:
What is the generic Python “built-in” database module called?
Answer:
DBM

Question 2:
What are some advantages of using DBM?
Answer:
No back-end database is required. The files are portable and work with the pickle and shelve modules to store Python objects.

Question 3:
What does it mean to pickle and unpickle a Python object?
Answer:
Using the pickle module, allows the writing of Python objects to a file. Unpickling is the reverse, reading a file containing a pickled Python object and re-instantiating it in the running program.

Question 4:
What is the difference between the pickle and cPickle Python modules?
Answer:
cPickle is much faster, but it cannot be subclassed like pickle can.

Question 5:
What is the shelve module, and how is it different from pickle?
Answer:
Shelving an object is a higher-level operation that pickles, in that the shelve module provides its own open method and pickles objects behind the scene. Shelve also allows the storage of more complex Python objects.

Question 6:
Illustrate creating a DBM file.
Answer:
import anydbm
myDB = anydbm.open(“newDBFile.dbm”, ‘n’)

Question 7:
Illustrate writing a list to a DBM file.
Answer:
import anydbm
my List = [“This”, “That”, “Something Else”]
myDB = anydbm.open(“newDBFile.dbm”, ‘w’)
mylndex = 0
for myltem in myList:
myDB[my!tem] = myList[myIndex]
mylndex += 1 myDB.close( )

Question 8:
Illustrate pickling a list.
Answer:
import cPickle .
myList = [“This”, “That”, “Something Else”]
myFile = open(“myPickleFile.dat”, “w”)
myPickler = cPickle.Pickler(myFile)
myPickler.dump(myList)
myFile.close( )

Question 9:
Illustrate shelving a dictionary.
Answer:
import shelve
myDict = {“name”: “John Doe”, “Address” : “1234 Main street”}
my Shelf = shelve.open(” my ShelveFile.dat”, “n”)
my Shelfl” Dictionary”] = myDict
my Shelf. close( )

Question 10:
Illustrate retrieving a dictionary from a shelf file Answer:
import shelve
myShelf= shelve.open(” my ShelveFile.dat”, “r”)
myDict = my Shelfl “Dictionary”]
myShelf.close( )

Question 11:
What Python module is used to work with a MySQL database?
Answer:
MySQLdb.

Question 12:
Illustrate connecting to a MySQL database on the local host, with a username and a password.
Answer:
import MySQLdb
myDB = MySQLdb.connect(host=”127.0.0.1″, user=”username”, passwd=”password”)

Question 13:
What is a MySQLdb cursor?
Answer:
It is a handle that lets you send SQL commands to MySQL and retrieve the result.

Question 14:
Illustrate creating a cursor, then sending a select
command to MySQL
Answer:
import MySQLdb
myDB = MySQLdb.connect(host=” 127.0.0.1″, usem”username”,
passwd= “password “)
my Cursor = myDB.cursorO
myCursor.execute(” select * from tablename”)
myResults = myCursor.fetchall( )

Question 15:
How are databases and tables created in MySQL from Python?
Answer:
Using a database connection and cursor to execute the appropriate CREATE DATABASE and CREATE TABLE SQL commands.

Question 6:
How is the currently selected database name retrieved?
Answer:
Using a database connection and cursor to execute a SELECT DATABASE() SQL command.

Question 17:
What is the .fetchall( ) method of the cursor object?
Answer:
It is used to retrieve all of the results of the executed SQL command. It returns a series of one or more lists depending on the results available.

Question 18:
Illustrate adding a row to a MySQL database
Answer:
import MySQLdb
myDB = MySQLdb.connect(host=”127.0.0.1”, user=”username”, passwd= “password “)
myCursor = myDB.cursor( )
my Cursor. execute(” INSERT INTO tablename VALUES ‘Vail’, ‘Val2’, ‘etc.'”)
myDB. commit( )

Question 19:
What does the .commit method of the database object do?
Answer:
It flushes the pending request buffer and ensures that the transactions are all written to disk.

Question 20:
Illustrate retrieving a list of available tables in a MySQL database.
Answer: „
import MySQLdb
myDB = MySQLdb.connect(host=” 127.0.0.1″, user=”username”, passwd= “password “)
myCursor = myDB.cursor ( )
myCursor.executeC’SHOW TABLES “)
myResults = myCursor.fetchall( )

Python Interview Questions on Python Database Interface Read More »

Python Interview Questions on String Manipulation

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

Python Interview Questions on String Manipulation

Question 1.
Is .len( ) a valid string method?
Answer:
No. To get the length of a string using the function len( ), as in len(string)

Question 2.
What does the .title( ) method do?
Answer:
It returns a title-cased string, words start with upper case and everything else is lower case.

Question 3:
Given a string with leading and trailing spaces, illustrate how to return a string without the leading and trailing spaces.
Answer:
string.strip(”)

Question 4:
What is the difference between the find( ) and index( ) string methods?
Answer:
If the substring is not found, find( ) will return -1, and index( ) will raise a ValueError.

Question 5:
Illustrate breaking a comma-separated string into a list of individual tokens.
Answer:
string.split(‘/)

Question 6:
How is a slice of a string specified?
Answer:
Using the colon in the form of start: end index. 2:5 would specify the third through sixth characters in a string.

Question 7:
Given a multiple-line string, how is a list of individual lines obtained?
Answer:
string. splitlines( ) Line breaks are removed unless split lines are called with (True).

Question 8:
What method is used to determine if a string contains any special characters or punctuation?
Answer:
string.alnum( ) If it returns true, there are no special characters in the string.

Question 9:
What method is used to determine if a string contains only numbers?
Answer:
string.isdigit( ) Any other values in the string will cause this to return False.

Question 10:
What is the purpose of the count!) string method?
Answer:
The count method counts the number of occurrences of a substring within the string. Not the number of characters in the string.

Question 11:
What does the partition( ) string method do?
Answer:
Partition breaks a string into two parts and returns a tuple containing the substring before the separator, the separator itself, and the substring after the separator.

Question 12:
In the string “Fred Flintstone drinks at a foo. A fluorometer measures pressure.” How would you change every occurrence of foo with bar?
Answer:
string.replace^foo’/bar’)

Question 13:
Illustrate converting tabs to 12 spaces each in a string.
Answer:
string.expand tabs(12)

Question 14:
Given a list of words, combine them into one string.
Answer:
myString = “.join(wordlist)

Question 15:
How is the center string method used?
Answer:
It positions a string centered in a field of a specified width, padded by spaces on either side.

Question 16:
How can code inside a string be executed?
Answer:
exec(string) The string is interpreted as Python code.

Question 17:
How are string templates created?
Answer:
By using the $ prefix on variable names within the template string.

Question 18:
Illustrate creating a template string, and then printing it with a variable substituted.
Answer:
import string
myTemp late = string.Template! “A template… The variable = $v”)
print myTemplate.substitute(v=”my variable”)

Question 19:
How is a Unicode string specified?
Answer:
By adding a ‘u’ before the string definition

Question 20:
How is Unicode converted to a local string?
Answer:
Using the string’s encode method. An example might be string.encode(‘utf-8′)

Python Interview Questions on String Manipulation Read More »