Selenium Python Tutorial | Introduction to Selenium

Selenium Python – 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:

Data Persistence Python Database DBAPI

Python Data Persistence – Python DB-API

The previous chapter was an overview of SQL fundamentals with the help of the SQLite database. However, as mentioned therein short, there are several equally popular RDBMS in use worldwide. Some of them are open-source and others for enterprise use. Although all of them use SQL underneath them, there are a lot of differences in the implementation of SQL standards by each of them. This also reflected in Python’s interface modules written by individuals for interaction with databases. Since each module defined its own functionality for interaction with the respective database product, its major fallout is a lack of compatibility. If for some reason, a user is required to switch to a different database product, almost the entire code that handles the back-end processing had to be rewritten.

To find a solution for this incompatibility issue, a ‘Special Interest Group’ was formed in 1996. This group (db-sig) recommended a set of specifications by raising ‘Python Enhancement Proposal (PEP 248)’ for a consistent interface to relational databases known as DB-API. The specifications have since been modified by subsequent enhancement proposals (PEP 249). Its recommendations are called DB-API Version 2.0.

As various Python database modules have been made DB-API compliant, most of the functionality required to interact with any database is uniform. Hence, even if the database itself is switched, only a couple of changes in the code should be sufficient.

Oracle, the world’s most popular relational database can be interface with Python with more than one module. cx_OracIe is a Python extension module that enables access to Oracle Database with some features of its owrt in addition to DB-API. It can be used with Oracle 11.2,12.1, and 12.2, and 18.3 client libraries. There is pyodbc module that acts as a Python- ODBC bridge driver that can be used for Python-Oracle interaction as well.

To use Microsoft’s SQL Server database with Python also, there are a couple of alternatives. The pymysql module is there in addition to pyodbc module.

As far as PostgreSQL is concerned, psycopg2 module is the most popular PostgreSQL adapter for the Python programming language.
MySQL is also a very popular relational database, especially in the open-source domain. MySQL Connector/Python is a standardized database driver provided by MySQL itself. There is a mysqldb module for the Python interface but is not still compatible with Python 3.x. You can use pymysql module as a drop-in replacement for mysqldb module while using the Python 3.x version.

As mentioned in the previous chapter, Python’s standard library consists of the sqlite3 module which is a DB-AP1 compliant module for handling the SQLite database through Python program. While other modules mentioned above should be installed in the current Python installation – either by pip utility or by using a customized installer (as in case of MySQL Connector/ Python), the sqlite3 module needs no such installation.

sqlite3 Module

SQLite is often used as a prototyping tool for larger databases. The fact that SQLite is extremely lightweight and doesn’t require any server but still is a fully-featured implementation of SQL, it is a common choice in the developmental stage of an application and is eventually replaced by enterprise RDBMS products such as Oracle. Likewise, you can think of the sqlite3 module as a prototype DB-API module. We shall explore the DB-API specifications with the help of the sqlite3 module. We will soon discover how easy it is to switch to other databases just by modifying a couple of statements.

Let us start by importing the sqlite3 module. Note that, its target SQLite library version may be different from the SQLite binary downloaded by you as shown in the previous chapter.

Example

>>> import sqlite3 
>>> sqlite3.sqlite_version 
'3.21..0'

Connection Object

The all-important connection object is set up by the module level connect ( ) function. The first positional argument to this function is a string representing path (relative or absolute) to an SQLite database file. The function returns a connection object referring to the database file – either existing or new. Assuming that, ‘newdb. sqlite’ doesn’t already exist, the following statement opens it:

>>> conn=sqlite3.connect('newdb.sqlite') 
>>> type(conn)
<class 'sqlite3.Connection'>

As we’ve seen in the previous chapter, SQLite supports an in-memory database. To open the same programmatically use “:memory: ” as its path.

>>> conn=sqlite3.connect(":memory:")

The connection object has access to various methods in the connection class. One of them is a cursor () method that returns a cursor object, which we shall know in the next section. Transaction control is achieved by commit () and rollback () methods of the connection object. Connection class has important methods to define custom functions and aggregates to be used in SQL queries. Later in this chapter create_ function () and create_aggregate () methods are explained.

cursor Object

After opening the database, the next step is to get a cursor object from it which is essential to perform any operation on the database. A database cursor enables traversal over the records in a database. It facilitates CRUD operations on a table. The database cursor can be considered similar to the concept of an iterator. The cursor ( ) method on the connection object returns the cursor object.

>>> cur=conn.cursor()
>>> type(cur)
<class 'sqlite3.Cursor'>

Once we get hold of the cursor object, we can perform all SQL query operations, primarily with the help of its execute () method. This method needs a strong argument which must be a valid SQL statement. String argument having incorrect SQL statement raises exceptions as defined in the sqlite3 module. Hence, it is recommended that a standard exception handling mechanism is used.

Updating Data

It is fairly straightforward to programmatically perform update operations on a table in the SQLite database. As pointed out in the previous chapter, the update query is normally a conditional operation unless you intend to update all rows of a certain table. Hence a parameterized query is ideal for this purpose.

Following script (1 updateqry.py!) asks the user to input the name of the product and new price and performs update operation accordingly.

Example

import sqlite3
conn=sqlite3.connect(1mydb.sqlite')
nm=input(1 enter name of product:')
p=int(input('new price:'))
qry='update Products set price=? where name=?'
cur=conn.cursor()
try;
cur.execute(qry, (p,nm))
print ('record updated')
conn.commit()
except:
print ('error in update operation')
conn.rollback()
conn.close( )

Run the above script from a command prompt:

E:\python37>python updateqry.py 
enter the name of the product: TV 
new price:32000 
record updated

The SQLite console can confirm the above action.

sqlite> select * from products where name='TV';
ProductID    Name          Price
------------  --------      --------
2                  TV            32000

Python Data Persistence – Creating Table

Python Data Persistence – Creating Table

We shall now add a table in our newly created ‘mydb.sqlite’ database. In the following script, the first two steps are as illustrated above – setting up connection and cursor objects. Next, we call execute () method of cursor object, giving it a string with CREATE TABLE statement inside. We shall use the same ‘Products’ table that we created in the previous chapter. Save the following script as ‘createqry.py’ and execute it.

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite')
cur=conn.cursor()
qry=' ' '
CREATE TABLE Products (
ProductID INTEGER PRIMARY KEY AUTOINCREMENT,
Name     TEXT (20) ,
Price    INTEGER
) ;
' ' '
try:
        cur.execute(qry)
        print ('Table created successfully')
except:
        print ('error in creating table')
conn.close ( )

Products table will be created in our database. We can verify by listing out tables in this database in the SQLite console, as we did in the previous chapter.

sqlite> .open mydb.sqlite 
sqlite> .tables 
Products

Let us also create ‘Customers’ and ‘Invoices’ tables with the same structure as used in the previous chapter. Here, we use a convenience method to execute the script ( ) that is defined in the cursor class. With its help, it is possible to execute multiple execute statements at once.

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite')
cur=conn.cursor( )
qry= ' ' '
CREATE TABLE Customers (
          CustID INTEGER PRIMARY KEY AUTOINCREMENT,
          Name           TEXT (20),
          GSTIN           TEXT (15)
   ) ;
CREATE TABLE Invoices (
         InvID             INTEGER             PRIMARY KEY
AUTOINCREMENT,
       CustID               TEXT                REFERENCES Customers
(CustID),
      ProductID        INTEGER            REFERENCES Products
(ProductID),
     Quantity         INTEGER (5)
) ;
' ' '
try:
      cur.executescript(qry)
      print ('Table created successfully')
except:
     print ('error in creating table')
conn.close( )

 

You can go back to the SQLite console and refresh the table list to confirm that all three tables are created in mydb.sqlite database.

Python Data Persistence – Inserting Rows

Python Data Persistence – Inserting Rows

The next step is to insert rows in the tables we have just created. We know the syntax of the INSERT statement and we have used it in console mode of sQLite in the previous chapter. To do it programmatically, declare an INSERT query string and use it as an argument to execute () method.

As noted in the previous chapter, the SQLite database engine is in auto-commit mode by default. To have better transaction control, we should commit the query operation only if it doesn’t encounter any exceptions.
Following code inserts a record in the Products table.

Example

import sqlite3
conn=sqlite3 . connect (' mydb. sqlite ' )
cur=conn.cursor( )
qry="insert into Products values (1,'Laptop', 25000);"
try: cur.execute(qry)
conn.commit( )
print ('Record inserted successfully')
except print ( 'error in insert conn.rollback ( ) operation')
conn.close ( )

In many cases, you may want to accept user input for field values to be inserted. You can form a query string by substituting the user inputs in the string with the help of string formatting technique, as shown below:

Example

>>> id=input('enter ProductID:1) enter ProductID:2
>>> nm=input('enter product name:') enter product name:Hard Disk
>>> p=int(input('enter price:')) enter price:5000
>>> qry="insert into products values ({ }, { }, { });"• format(id, nm, p)
> > > qry
'insert into products values (2, Hard Disk, 5000);'

You can very well use this query string as an argument of execute () method. However, query operations using Python’s string formatting is insecure as it makes the program vulnerable to SQL injection attacks. Hence., DB-API recommends the use of parameter substitution technique.

The execute () method of the sqlite3 module supports the use of question mark symbols (‘?’) as placeholders as well as named placeholders in which case the dictionary object of name and value pairs is given as the second argument to execute( ) method.

>>> #using '?' place holder
>>> cur.execute("insert into products values (?,?,?)",(id,nra,p))
>>> #using named place holder
>>> cur.execute("insert into products values
( :id, :nm, :p) ", {"id":id, "nm":nm, "p":p})

There is another useful variant of execute () method in the sqlite3 module. The first argument to execute the many( ) method is a query string with placeholders, and the second argument is a list of parameter sequences. The query gets executed for each sequence (itself may be a list or tuple) in the list. Following script (‘insertqry.py ) uses execute many () method to insert records in the Products table, as displayed in the previous chapter.

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite') cur=conn.cursor()
qry="insert into Products values (?,?,?)" pricelist=[(1, 'Laptop1 ,25000), (2, 'TV 1,40000) ,
(3,'Router',2000),(4,'Scanner',5000),
(5,'Printer',9000), (6,'Mobile',15000)]
try:
cur.executemany(qry, pricelist) conn.commit( )
print ('Records inserted successfully')
except:
print ('error in insert operation') conn.rollback( ) conn.close( )

You can check successful insertion on the SQLite console.

sqlite> select * from products;
ProductID          Name            Price
———-          ———        ——-

1                  Laptop        25000
2                    TV            40000
3                  Router        2000
4                 Scanner       5000
5                  Printer        9000
6                   Mobile       15000

Python Data Persistence – Deleting Rows

Python Data Persistence – Deleting Rows

Similarly, we can programmatically delete a certain record from a table. This operation is also more often than not conditional. Hence, the ‘WHERE’ clause appears in the parameterized DELETE query. Following script (deleteqry.py) deletes row belonging to the user-specified product.

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite')
nm=input('enter product to delete:1)
qry='delete from Products where name=?'
cur=conn.cursor( )
try:
cur.execute(qry, (nm,))
print ('record deleted')
conn.commit ( )
except:
print ('error in delete operation')
conn.rollback( )
conn.close( )

To delete the user input product, run the above script from the command prompt.

E:\python37>python deleteqry.py 
enter product to delete: Printer 
record deleted

Execute select query in SQLite console to verify that deleted product doesn’t appear in the list.

sqlite> select * from products;
ProductID      Name         Price
---------        ---------      --------
    1                Laptop        25000
    2                   TV           32000
    3              Router           2000
   4               Scanner        5000
   6               Mobile          15000

The next section explains how to programmatically retrieve records from a table.

Python Data Persistence – ResultSet Object

Python Data Persistence – ResultSet Object

We need to call execute ( ) method on cursor object with a SELECT query string as its argument and a query result set is built which is similar to an iterator of rows returned in response to the query. The module provides the following methods to traverse the result set:

fenchone (): Next row in the query result set is retrieved and returned in the form of a tuple. The method returns None if there are no more rows to be fetched,

fetchall (): This method returns a list of all available rows in the result set. It contains a sequence corresponding to each row. You can employ a regular for loop to traverse the rows, as follows:

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite')
cur=conn.cursor()
qry="select * from Products;"
cur.execute(qry)
rows=cur.fetchall()
for row in rows:
        print (row) 
conn.close()

Run the above code (‘ selectqry. py’) from the command prompt.

E:\python37>python selectqry.py
(1,  'Laptop', 25000)
(2, ’TV', 40000)
(3, 'Router', 2000)
(4, 'Scanner' , 5000)
(5, 'Printer' , 9000)
(6, 'Mobile', 15000)

The fact that execute () method runs a parameterized query can be used to good effect to search for a certain condition in the table. The following code snippet accepts the product’s name as input and displays its price.

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite') nm=input ('Enter name of product:') cur=conn.cursor( )
qry="select * from Products where name=?";
cur.execute(qry, (nm,))
row=cur.fetchone( )
print (row)
conn.close( )

When the above script is run from the command prompt, then it above script shows the following output:

E:\python37>python selecttqry.py 
Enter name of product:TV 
(2, 'TV', 40000)

Individual items in the ‘row’ tuple can be accessed by index. The row can also be unpacked in separate variables as under:

Example

row=cur fetchone( ) 
print ( ' ID: ', row [ 0] , 'Name: 1, row[1], 'price:', row [2 ] ) 
id, nm, p=row 
print ( ID:', id, 'Name:', nm, 1 price: ' , p)

Python Data Persistence – User Defined Functions

Python Data Persistence – User Defined Functions

The SQLite database engine by itself is equipped with several built-in functions for finding string length, changing case to upper/lower case, rounding a number, etc. However, it doesn’t have the provision to define a new function with customized functionality. The SQLite module, however, has the provision to do so’ with the help of the create_function () method available to the connection object.

In the following example, we try to represent the price of the product rounded to thousands and attach a ‘k‘ alphabet to it. In other words, 40000 is represented by 40k. First, we define a regular Python function (myfunction) that accepts a number, divides it by 1000, and appends ’k’ to its string conversion. The create_f unction () method has the following prototype:

Example

create_function(SQLFunction, parameters,PythonFunction)

In other words, it assigns a name to the Python function(a function in our case) that can be used as a function in the SQL query.

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite') def myfunction(num):
return str(round(num/1000))+"k" conn.create_function('priceinK' , 1,myfunction) cur=conn.cursor()
qry="select name, priceinK(price) from products;"
cur.execute(qry)
rows=cur.fetchall( )
print (rows)
conn.close ( )

Output of above code snippet is:

Example

[('Laptop', '25k'), ('TV', '40k'), ('Router', '2k'),
('Scanner', '5k'), ('Printer', '9k'), ('Mobile',
'15k') ]

SQLite also has several built-in aggregate functions such as SUM, AVG, COUNT, etc. to be applied to one or more columns in a table. For example, the query selects SUM (price) from Products’returns sum of values in the price column of all rows. Using the create_aggregate() method defined to be used with the cursor object, it is possible to define a customized aggregate function.

In the following script, a regular Python class named my class s is defined and it contains a step( ) method which is mandatory for the user-defined aggregate function. The step() method increments the count for each product name ending with ‘r\ The create_aggregate () method attaches a name that can be used in the SQL query. When this aggregate function is called, the value returned by finalize () method of the class is in fact the result of the SELECT statement.

Example

import sqlite3
conn=sqlite3.connect('mydb.sqlite')
class myclass:
def__init__(self):
self.count=0
def step(self, string):
if string.endswith('r'):
self.count=self.count+1
def finalize (self) :
return self.count
conn.create_aggregate(1MyF',1,myclass)
cur=conn.cursor()
qry="select MyF(name) from products;"
cur.execute(qry)
row=cur.fetchone()
print ('number of products with name ending with ' r1 : ' , (row) [0] )
conn.close()

The output of the above script is:

Example

number of products with the name ending with : 3

 

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 Data Persistence – pickle Module

Python Data Persistence – pickle Module

The serialization format used by the pickle module, which is a part of Python’s built-in module library, is very Python-specific. While this fact can work as an advantage that it doesn’t face any restrictions by certain external standards such as JSON format, the major disadvantage is that non-Python applications may not be able to reconstruct ‘pickled’ objects. Also, the pickle module is not considered secure when it comes to unpickling data received from an unauthenticated or untrusted source.

The pickle module defines the module-level dumps ( ) function to obtain a byte string ‘pickled’ representation of any Python object. Its counterpart function loads () reconstructs (‘unpickles’) the byte string identical Python object.

Following code snippet demonstrates the use of dumps () and loads () functions:

Example

>>> import pickle
>>> numbers=[10,20,30,40]
>>> pickledata=pickle.dumps(numbers)
>>> pickledata
b'\x80\x03]q\x00(K\nK\xl4K\xleK(e.'
>>> #unpickled data
. . .
>>> unpickledata=pickle.loads(pickledata)
>>> unpickledata
[10, 20, 30, 40]
>>>

There are dump ( ) and load () functions that respectively write pickled data persistently to a file-like object (which may be a disk file, a memory buffer object, or a network socket object) having binary and write ‘wb’ mode enabled, and reconstruct identical object from a file-like object having ‘rb’ permission.

Example

>>> #pickle to file
. . .
>>> import pickle
>>> numbers=[ 10 , 20 , 30 , 40 ]
>>> file=open ('numbers .dat' , ' wb ')
>>> pickle . dump (numbers, file)
>>> file . close ()
>>> #unpickle from file
. . .
>>> file=open {1 numbers . dat' , ' rb' )
>>> unpickledata=pickle . load (file)
>>> unpickledata
[10, 20, 30, 40]
>>>

Almost any type of Python object can be pickled. This includes built-in types, built-in, and user-defined functions, and objects of user-defined classes.

The pickle module also provides object-oriented API as a substitute for module-level dumps () /loads () and dump () /load () functions. The module has a pickier class whose object can invoke dump () or dumps () method to ‘pickle’ an object. Conversely, the unpicker class defines load () and loads () methods.

Following script has a person class whose objects are pickled in a file using pickier class. Original objects are obtained by the load () method of unpicker class.

Example

from pickle import Pickier, Unpickler
class User:
def__init__(self,name, email, pw):
self.name=name
self.email=email
self.pw=pw
def__str__(self):
return ('Name: { } email: { } password: {}'. \ format(self.name, self.email, self.pw))
user1=User('Raj an', 'rl23@gmail.com', 'rajanl23')
user2=User('Sudheer', 's.ll@gmail.com', 's 11')
print ('before pickling..')
print (user1)
print (user2)
file=open (' users . dat' , ' wb' )
Pickier (file) .dump (userl)
Pickier (file) .dump(user2)
file.close ()
file=open ( ' users . dat' , ' rb ' )
obj 1=Unpickler (file) . load ()
print ('unpickled objects')
print (obj1)
obj2=Unpickler (file) . load()
print (obj2)

Output:

E:\python37>python pick1-example.py before pickling.
Name: Rajan email: rl23w-gmail.com password: rajanl23 
Name: Sudheer email: s.lKwgmail.com password: s_ll unpickled objects
Name: Rajan email: rl2 3wgmail.com password: rajanl23 
Name: Sudheer email: s.llwgmail.com password: s_ll E:\python3 7 >

Python Data Persistence – SELECT Statement

Python Data Persistence – SELECT Statement

This is one of the most frequently used SQL statements. The purpose of the SELECT statement is to fetch data from a database table and return it in the form of a result set. In its simplest form SELECT statement is used as follows:

Example

SELECT coll, col2, .., coin FROM table_name;

SQLite console displays data from the named table for all rows in specified columns. SQLite console offers two useful ‘dot’ commands for a neat and formatted output of the SELECT statement. The ‘.header on’ command will display the column names as the header of output. The ‘.mode column’ command will force the left alignment of data in columns.

sqlite> .header on
sqlite> .mode column
sqlite> select name as name, price from products;
name       Price
---------    --------
Laptop   25000
TV          40000
Router   2000
Scanner 5000
Printer   9000
Mobile  15000

You can use wild card characters to indicate all columns in the table.

sqlite> .header on 
sqlite> .mode column 
sqlite> select * from products;
ProductID   Name     Price
 ----------    -------   --------   
       1          Laptop    25000
       2           TV         40000
       3           Router   2000
       4          Scanner   5000
       5          Printer     9000
       6         Mobile     15000

The ORDER BY clause lists selected rows according to ascending order of data in the specified column. The following statement displays records in the Products table in ascending order of price.

sqlite> select * from products order by price;
ProductID          Name              Price
-----------          ---------         ---------     
      3                  Router             2000
      4                  Scanner           5000
      5                  Printer            9000
      6                  Mobile           15000
      1                  Laptop           25000
      2                  TV                  40000

To enforce descending order, attach ‘DESC’ to the ORDER BY clause.

sqlite> select * from products order by name desc;
ProductID             Name              Price
-----------             --------            --------      
       2                     TV                  40000
       4                     Scanner          5000
       3                     Router            2000
       5                     Printer            9000
       6                     Mobile           15000
       1                     Laptop           25000

You can apply the filter on the selection of rows by using the WHERE clause. The WHERE keyword is followed by a logical condition having logical operators (<, >, <=, >=, =, IN, LIKE, etc.). In the following example, only those rows will be selected for which value of the ‘price’ column is less than 10000.

sqlite> select * from products where price<10000;
ProductID            Name           Price
------------         ---------         --------      
      3                    Router          2000
      4                    Scanner        5000
      5                    Printer          9000

A big advantage of the relational model comes through when data from two related tables can be fetched. In our ‘Invoices’ table, we have ProductID as one of the columns that are a primary key of the ‘Products’ table. The following example uses the WHERE clause to join two tables – Invoices and Products – and fetch data from them in a single SELECT statement.

sqlite> select InvID, Products. name, Products.Price,
Quantity 
. . .> from invoices, , Products where invoices.
productID= Products.ProductID; 
InvID            Name           Price             Quantity
-------          --------       ----------         --------
 1                Laptop         25000                 2
  2                 TV               40000                 1
  3                Mobile         15000                 3
  4                Mobile         15000                 1
  5                Printer          9000                   3
  6                   TV              40000                5
  7                Laptop          25000                4
  8                Router          2000                  10
  9                Printer          9000                   2
 10               Scanner        5000                   3

It is also possible to generate a calculated column depending on some operation on other columns. Any column heading can also be given an alias name using AS keyword.
Following SELECT statement displays Total column which is Products. Price*Quantity. The column shows values of this expression is named AS Total.

sqlite > select InvID, Products.: name t Products.
Price, Quantity, Products.Price *Quantity as
Total 
> from invoices, Products where
invoices.productID=Products.ProductID;
InvID            Name            Price            Quantity           Total 
--------        ---------        ----------       -----------      --------
   1            Laptop             25000                2                  50000
   2               TV                 40000                1                  40000
   3            Mobile             15000                3                  45000
   4            Mobile             15000                1                  15000
   5            Printer              9000                 3                   27000
   6             TV                   40000               5                   200000
  7            Laptop              25000               4                   100000
  8            Router               2000                10                   20000
  9            Printer               9000                 2                   18000
 10           Scanner             5000                 3                   15000