Learn Scripting

Coding Knowledge Unveiled: Empower Yourself

Installation of Python Version(2.7/3.*) in Windows

[lwptoc min=”2″ depth=”6″ hierarchical=”1″ numeration=”decimalnested” numerationSuffix=”none” title=”Contents” toggle=”1″ labelShow=”show” labelHide=”hide” hideItems=”0″ smoothScroll=”1″ width=”auto”]

Installation of Python Version(2.7/3.*) is very easy because of it GUI Installer. Which made life simple for the programmer. For the installation of Python, we need to follow the below steps.

If you are a beginner in python before choosing the version you can go through the post The Difference Between Pyhton 2.x and Python 3.x

Step 1:Download Python According to System Processor 

Depending on your system processor you have chosen the appropriate exe file from the download page Link.

Step 2:Run the Package Installer & Setup the Python Executable Path

After downloading the python you need to install it in your system by double clicking it.During installation you need to setup few things without which you can face difficulties in future.

#Need to provide the installation path at the time of setup otherwise it will take the system default path.You have to create a folder named as PythonXX with post fix your version code. In my case i have created a folder Python37 for the python 3.7 version installation.As shown in the below image.

#Select Customize Installation.

#Add Pyhton 3.7 to PATH

#Check the options

Pip

tcl/tk

Python Test Suite

#Give the Python37 Folder Location which you have created at first step.

Step 3:Open Command and Check the Installation

Open you command prompt and Type python -v in your command prompt .Now you can able to see the pyhton version installed in your system.If you don’t find the  pyton version installed in your system you might have skip some step from above please reinstall pyhton with above prerequisite or you can setup your python path manually as provided in the step #4.

Step 4:Setting Up Python Path in the environment variable.

Go to your my computer->Properties->Advance System Setting ->Go to advance Tab->Click on Environmental Variable .

You will find two section where you need to give your python installation location as shown in the image.

If you still find difficulties please comment below with your error code.And please do not forget to give your comment.

Difference Between Pyhton 2.X Vs 3.X

The key differences between Python 2.7.x and Python 3.x with examples

Many beginning Python users are wondering with which version of Python they should start their career. Our answer to this question is usually something along the lines “just go with the version your favorite tutorial was written in, and check out the differences later on.”But what if you are starting a new project and have the choice to pick? I would say there is currently no “right” or “wrong” as long as both Python 2.7.x and Python 3.x support the libraries that you are planning to use. However, it is worthwhile to have a look at the major differences between those two most popular versions of Python to avoid common pitfalls when writing the code for either one of them, or if you are planning to port your project.

The Key Differences are as below

  1. The __future__ module in python 2
  2. The print function
    1. Python 2
    2. Python 3
  3. Integer division
    1. Python 2
    2. Python 3
  4. Unicode
    1. Python 2
    2. Python 3
  5. xrange
    1. Python 2
    2. Python 3
    3. The __contains__ method for range objects in Python 3
      1. Note about the speed differences in Python 2 and 3
  6. Raising exceptions
    1. Python 2
    2. Python 3
  7. Handling exceptions
    1. Python 2
    2. Python 3
  8. The next() function and .next() method
    1. Python 2
    2. Python 3
  9. For-loop variables and the global namespace leak
    1. Python 2
    2. Python 3
  10. Comparing unorderable types
    1. Python 2
    2. Python 3
  11. Parsing user inputs via input()
    1. Python 2
    2. Python 3
  12. Returning iterable objects instead of lists
    1. Python 2
    2. Python 3
  13. Banker’s Rounding
    1. Python 2
    2. Python 3
  14. More articles about Python 2 and Python 3

1.The __future__ module

Python 3.x introduced some Python 2-incompatible keywords and features that can be imported via the in-built __future__ module in Python 2. It is recommended to use __future__ imports it if you are planning Python 3.x support for your code. For example, if we want Python 3.x’s integer division behavior in Python 2, we can import it via the folowing syntax.

from __future__ import division

More features that can be imported from the __future__ module are listed in the table below:

feature optional in mandatory in effect
nested_scopes 2.1.0b1 2.2 PEP 227: Statically Nested Scopes
generators 2.2.0a1 2.3 PEP 255: Simple Generators
division 2.2.0a2 3.0 PEP 238: Changing the Division Operator
absolute_import 2.5.0a1 3.0 PEP 328: Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6 PEP 343: The “with” Statement
print_function 2.6.0a2 3.0 PEP 3105: Make print a function
unicode_literals 2.6.0a2 3.0 PEP 3112: Bytes literals in Python 3000

(Source: [https://docs.python.org/2/library/__future__.html](https://docs.python.org/2/library/__future__.html#module-__future__))

from platform import python_version

2.The print function

This is an important change in the Pyhton from the 2 to 3, and the change in the print-syntax is probably the most widely known change, but still it is worth mentioning: Python 2’s print statement has been replaced by the print() function, meaning that we have to wrap the object that we want to print in parenthesis.

Python 2 doesn’t have a problem with additional parenthesis, but in contrast, Python 3 would raise a SyntaxError if we called the print function the Python 2-way without the parentheses.

Python 2

print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

print('Python', python_version())
print('Hello, World!')

print("some text,", end="")
print(' print more text on the same line')
Python 3.4.1
Hello, World!
some text, print more text on the same line
print 'Hello, World!'
  File "<ipython-input-3-139a7c5835bd>", line 1
    print 'Hello, World!'
                        ^
SyntaxError: invalid syntax

Note:

Printing “Hello, World” above via Python 2 looked quite “normal”. However, if we have multiple objects inside the parantheses, we will create a tuple, since print is a “statement” in Python 2, not a function call.

print 'Python', python_version()
print('a', 'b')
print 'a', 'b'
Python 2.7.7
('a', 'b')
a b

3.Integer division

This change is particularly dangerous if you are porting code, or if you are executing Python 3 code in Python 2, since the change in integer-division behavior can often go unnoticed (it doesn’t raise a SyntaxError).
So, I still tend to use a float(3)/2 or 3/2.0 instead of a 3/2 in my Python 3 scripts to save the Python 2 guys some trouble (and vice versa, I recommend a from __future__ import division in your Python 2 scripts).

Python 2

print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Python 3

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

4.Unicode

Python 2 has ASCII str() types, separate unicode(), but no byte type.

Now, in Python 3, we finally have Unicode (utf-8) strings, and 2 byte classes: byte and bytearrays.

Python 2

print 'Python', python_version()
Python 2.7.6
print type(unicode('this is like a python3 str type'))
<type 'unicode'>
print type(b'byte type does not exist')
<type 'str'>
print 'they are really' + b' the same'
they are really the same
print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>

Python 3

print('Python', python_version())
print('strings are now utf-8 \u03BCnico\u0394é!')
Python 3.4.1
strings are now utf-8 μnicoΔé!
print('Python', python_version(), end="")
print(' has', type(b' bytes for storing data'))
Python 3.4.1 has <class 'bytes'>
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
'note that we cannot add a string' + b'bytes for data'
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-13-d3e8942ccf81> in <module>()
----> 1 'note that we cannot add a string' + b'bytes for data'


TypeError: Can't convert 'bytes' object to str implicitly

5.xrange

The usage of xrange() is very popular in Python 2.x for creating an iterable object, e.g., in a for-loop or list/set-dictionary-comprehension.
The behavior was quite similar to a generator (i.e., “lazy evaluation”), but here the xrange-iterable is not exhaustible – meaning, you could iterate over it infinitely.

Thanks to its “lazy-evaluation”, the advantage of the regular range() is that xrange() is generally faster if you have to iterate over it only once (e.g., in a for-loop). However, in contrast to 1-time iterations, it is not recommended if you repeat the iteration multiple times, since the generation happens every time from scratch!

In Python 3, the range() was implemented like the xrange() function so that a dedicated xrange() function does not exist anymore (xrange() raises a NameError in Python 3).

import timeit

n = 10000
def test_range(n):
    return for i in range(n):
        pass

def test_xrange(n):
    for i in xrange(n):
        pass    

Python 2

print 'Python', python_version()

print '\ntiming range()'
%timeit test_range(n)

print '\n\ntiming xrange()'
%timeit test_xrange(n)
Python 2.7.6

timing range()
1000 loops, best of 3: 433 µs per loop


timing xrange()
1000 loops, best of 3: 350 µs per loop

Python 3

print('Python', python_version())

print('\ntiming range()')
%timeit test_range(n)
Python 3.4.1

timing range()
1000 loops, best of 3: 520 µs per loop
print(xrange(10))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

<ipython-input-5-5d8f9b79ea70> in <module>()
----> 1 print(xrange(10))


NameError: name 'xrange' is not defined

6.The __contains__ method for range objects in Python 3

Another thing worth mentioning is that range got a “new” __contains__ method in Python 3.x (thanks to Yuchen Ying, who pointed this out). The __contains__ method can speedup “look-ups” in Python 3.x range significantly for integer and Boolean types.

x = 10000000
def val_in_range(x, val):
    return val in range(x)
def val_in_xrange(x, val):
    return val in xrange(x)
print('Python', python_version())
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_range(x, x/2)
%timeit val_in_range(x, x//2)
Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 µs per loop

Based on the timeit results above, you see that the execution for the “look up” was about 60,000 faster when it was of an integer type rather than a float. However, since Python 2.x’s range or xrange doesn’t have a __contains__ method, the “look-up speed” wouldn’t be that much different for integers or floats:

print 'Python', python_version()
assert(val_in_xrange(x, x/2.0) == True)
assert(val_in_xrange(x, x/2) == True)
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_xrange(x, x/2.0)
%timeit val_in_xrange(x, x/2)
%timeit val_in_range(x, x/2.0)
%timeit val_in_range(x, x/2)
Python 2.7.7
1 loops, best of 3: 285 ms per loop
1 loops, best of 3: 179 ms per loop
1 loops, best of 3: 658 ms per loop
1 loops, best of 3: 556 ms per loop

Below the “proofs” that the __contain__ method wasn’t added to Python 2.x yet:

print('Python', python_version())
range.__contains__
Python 3.4.1





<slot wrapper '__contains__' of 'range' objects>
print 'Python', python_version()
range.__contains__
Python 2.7.7



---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

<ipython-input-7-05327350dafb> in <module>()
      1 print 'Python', python_version()
----> 2 range.__contains__


AttributeError: 'builtin_function_or_method' object has no attribute '__contains__'
print 'Python', python_version()
xrange.__contains__
Python 2.7.7



---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

<ipython-input-8-7d1a71bfee8e> in <module>()
      1 print 'Python', python_version()
----> 2 xrange.__contains__


AttributeError: type object 'xrange' has no attribute '__contains__'

Note about the speed differences in Python 2 and 3

Some people pointed out the speed difference between Python 3’s range() and Python2’s xrange(). Since they are implemented the same way one would expect the same speed. However the difference here just comes from the fact that Python 3 generally tends to run slower than Python 2.

def test_while():
    i = 0
    while i < 20000:
        i += 1
    return
print('Python', python_version())
%timeit test_while()
Python 3.4.1
100 loops, best of 3: 2.68 ms per loop
print 'Python', python_version()
%timeit test_while()
Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop

7.Raising exceptions

Where Python 2 accepts both notations, the ‘old’ and the ‘new’ syntax, Python 3 chokes (and raises a SyntaxError in turn) if we don’t enclose the exception argument in parentheses:

Python 2

print 'Python', python_version()
Python 2.7.6
raise IOError, "file error"
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

<ipython-input-8-25f049caebb0> in <module>()
----> 1 raise IOError, "file error"


IOError: file error
raise IOError("file error")
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)

<ipython-input-9-6f1c43f525b2> in <module>()
----> 1 raise IOError("file error")


IOError: file error

Python 3

print('Python', python_version())
Python 3.4.1
raise IOError, "file error"
  File "<ipython-input-10-25f049caebb0>", line 1
    raise IOError, "file error"
                 ^
SyntaxError: invalid syntax

The proper way to raise an exception in Python 3:

print('Python', python_version())
raise IOError("file error")
Python 3.4.1



---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)

<ipython-input-11-c350544d15da> in <module>()
      1 print('Python', python_version())
----> 2 raise IOError("file error")


OSError: file error

8.Handling exceptions

Also the handling of exceptions has slightly changed in Python 3. In Python 3 we have to use the “as” keyword now

Python 2

print 'Python', python_version()
try:
    let_us_cause_a_NameError
except NameError, err:
    print err, '--> our error message'
Python 2.7.6
name 'let_us_cause_a_NameError' is not defined --> our error message

Python 3

print('Python', python_version())
try:
    let_us_cause_a_NameError
except NameError as err:
    print(err, '--> our error message')
Python 3.4.1
name 'let_us_cause_a_NameError' is not defined --> our error message

9.The next() function and .next() method

Since next() (.next()) is such a commonly used function (method), this is another syntax change (or rather change in implementation) that is worth mentioning: where you can use both the function and method syntax in Python 2.7.5, the next() function is all that remains in Python 3 (calling the .next() method raises an AttributeError).

Python 2

print 'Python', python_version()

my_generator = (letter for letter in 'abcdefg')

next(my_generator)
my_generator.next()
Python 2.7.6





'b'

Python 3

print('Python', python_version())

my_generator = (letter for letter in 'abcdefg')

next(my_generator)
Python 3.4.1





'a'
my_generator.next()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)

<ipython-input-14-125f388bb61b> in <module>()
----> 1 my_generator.next()


AttributeError: 'generator' object has no attribute 'next'

10.For-loop variables and the global namespace leak

Good news is: In Python 3.x for-loop variables don’t leak into the global namespace anymore!

This goes back to a change that was made in Python 3.x and is described in What’s New In Python 3.0 as follows:

“List comprehensions no longer support the syntactic form [... for var in item1, item2, ...]. Use [... for var in (item1, item2, ...)] instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.”

Python 2

print 'Python', python_version()

i = 1
print 'before: i =', i

print 'comprehension: ', [i for i in range(5)]

print 'after: i =', i
Python 2.7.6
before: i = 1
comprehension:  [0, 1, 2, 3, 4]
after: i = 4

Python 3

print('Python', python_version())

i = 1
print('before: i =', i)

print('comprehension:', [i for i in range(5)])

print('after: i =', i)
Python 3.4.1
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 1

11.Comparing unorderable types

Another nice change in Python 3 is that a TypeError is raised as warning if we try to compare unorderable types.

Python 2

print 'Python', python_version()
print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
print "(1, 2) > 'foo' = ", (1, 2) > 'foo'
print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)
Python 2.7.6
[1, 2] > 'foo' =  False
(1, 2) > 'foo' =  True
[1, 2] > (1, 2) =  False

Python 3

print('Python', python_version())
print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
Python 3.4.1



---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

<ipython-input-16-a9031729f4a0> in <module>()
      1 print('Python', python_version())
----> 2 print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
      3 print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
      4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))


TypeError: unorderable types: list() > str()

12.Parsing user inputs via input()

Fortunately, the input() function was fixed in Python 3 so that it always stores the user inputs as str objects. In order to avoid the dangerous behavior in Python 2 to read in other types than strings, we have to use raw_input() instead.

Python 2

Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'int'>

>>> my_input = raw_input('enter a number: ')

enter a number: 123

>>> type(my_input)
<type 'str'>

Python 3

Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> my_input = input('enter a number: ')

enter a number: 123

>>> type(my_input)
<class 'str'>

13.Returning iterable objects instead of lists

As we have already seen in the xrange section, some functions and methods return iterable objects in Python 3 now – instead of lists in Python 2.

Since we usually iterate over those only once anyway, I think this change makes a lot of sense to save memory. However, it is also possible – in contrast to generators – to iterate over those multiple times if needed, it is only not so efficient.

And for those cases where we really need the list-objects, we can simply convert the iterable object into a list via the list() function.

Python 2

print 'Python', python_version()

print range(3)
print type(range(3))
Python 2.7.6
[0, 1, 2]
<type 'list'>

Python 3

print('Python', python_version())

print(range(3))
print(type(range(3)))
print(list(range(3)))
Python 3.4.1
range(0, 3)
<class 'range'>
[0, 1, 2]

Some more commonly used functions and methods that don’t return lists anymore in Python 3:

  • zip()
  • map()
  • filter()
  • dictionary’s .keys() method
  • dictionary’s .values() method
  • dictionary’s .items() method

14.Banker’s Rounding

Python 3 adopted the now standard way of rounding decimals when it results in a tie (.5) at the last significant digits. Now, in Python 3, decimals are rounded to the nearest even number. Although it’s an inconvenience for code portability, it’s supposedly a better way of rounding compared to rounding up as it avoids the bias towards large numbers. For more information, see the excellent Wikipedia articles and paragraphs:

  • https://en.wikipedia.org/wiki/Rounding#Round_half_to_even
  • https://en.wikipedia.org/wiki/IEEE_floating_point#Roundings_to_nearest

Python 2

print 'Python', python_version()
Python 2.7.12
round(15.5)
16.0
round(16.5)
17.0

Python 3

print('Python', python_version())
Python 3.5.1
round(15.5)
16
round(16.5)
16

Features of Python Programming Language

As being programmer we always play with the programming languages.To work with any programming language we need to know the thatcher are available in a particular programming language.In this below post we will discuss the features of that language.In this Features of Python Programming Language post we will discuss in details .
Simple
If we compare with other language Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English (but very strict English!). This pseudo-code nature of Python is one of its greatest strengths. It allows you to concentrate on the solution to the problem rather than the syntax i.e. the language itself.
Easy to Learn
As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax as already mentioned.For an armature it will be a very easy stuff to learn it quickly,because of its English like keywords.
Free and Open Source
Everyone needs an free solution for the organization.Pyhton is being a free and powerful solution  which is an example of a FLOSS (Free/Libre and Open Source Software). In simple terms, you can freely distribute copies of this software, read the software’s source code, make changes to it, use pieces of it in new free programs, and that you know you can do these things. FLOSS is based on the concept of a community which shares knowledge. This is one of the reasons why Python is so good – it has been created and improved by a community who just want to see a better Python.
High-level Language
When you write programs in Python, you never need to bother about low-level details such as managing the memory used by your program.Unlike any other language python is not an complex stuff for managing the memory.Its inbuilt mechanism can able manage the memory by itself.
Portable
Due to its open-source nature, Python has been ported (i.e. changed to make it work on) to many many platforms. All your Python programs will work on any of these platforms without requiring any changes at all. However, you must be careful enough to avoid any system-dependent features.

You can use Python on Linux, Windows, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and PocketPC !

Interpreted
This requires a little explanation.

A program written in a compiled language like C or C++ is translated from the source language i.e. C/C++ into a language spoken by your computer (binary code i.e. 0s and 1s) using a compiler with various flags and options. When you run the program, the linker/loader software just stores the binary code in the computer’s memory and starts executing from the first instruction in the program.

When you use an interpreted language like Python, there is no separate compilation and execution steps. You just run the program from the source code. Internally, Python converts the source code into an intermediate form called bytecodes and then translates this into the native language of your specific computer and then runs it. All this makes using Python so much easier. You just run your programs – you never have to worry about linking and loading with libraries, etc. They are also more portable this way because you can just copy your Python program into another system of any kind and it just works!

Object Oriented
Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simple way of doing object-oriented programming, especially, when compared to languages like C++ or Java.
Extensible
It will support the other language bindings.If you need a critical piece of code to run very fast, you can achieve this by writing that piece of code in C, and then combine that with your Python program.
Embeddable
Cross language support feature is providing more power to python.You can embed Python within your C/C++ program to give scripting capabilities for your program’s users.
Extensive Libraries
The Python Standard Library is huge indeed. It can help you do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, ftp, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI(graphical user interfaces) using Tk, and also other system-dependent stuff. Remember, all this is always available wherever Python is installed. This is called the “batteries included” philosophy of Python.

Besides the standard library, there are various other high-quality libraries such as the Python Imaging Library which is an amazingly simple image manipulation library.

Summary

 

Python is indeed an exciting and powerful language. It has the right combination of performance and features that makes writing programs in Python both fun and easy.

How to Press or Fire Keyboard Event by Shell Scripting Technique

In most of the programming language the key press events are not comes as inbuilt feathers.At that point of time we need support of the shell scripting technique.In this post you will find the use and the different shortcut key available for this .

For VB Shell Scripting Scripting we need to create the code using set command as below

‘Set WshShell = WScript.CreateObject(“WScript.Shell”)
‘WshShell.Run “%windir%\notepad”
set objSendKey=CreateObject(“WScript.shell”)
set objSetFocus = Window(“nativeclass:=Notepad”,”index:=0″)
SystemUtil.Run “notepad.exe”, “”, “”, ”
wait 2
objSetFocus.Move 10,10
wait 1
objSetFocus.Click
[smartads]

1. How do I send an enter keystroke using QTP?

You could use the ASCII character for a carriage return Chr(13)

objSendKey.SendKeys(Chr(13))

(For more ASCII codes to use in QTP check out :QTP ASCII CHR() CODE CHART )

or use the Tilde character:
objSendKey.SendKeys(“~”)

Both will emulate an ‘Enter’ key.

2. How do I send a space?

To send a space, send the string ” “

3. How do I to send multiple keystrokes at one time using QTP’s VBscript?

To send multiple keys you can create compound string arguments. For example the following will hold down the Ctrl key, press the H key for the ‘Replace’ and type joe into the Replace window’s find textbox:
objSendKey.SendKeys(“^(h)joe”

)

4. How do I send a SHIFT, CTRL or Alt keystroke?

The special character for the Shift key in vbscript is the + sign.
For example to hold down the shift key and type a string all in capital letters try this:
objSendKey.SendKeys(“+(joecolantonio)”)

The special character for the Ctrl key in vbscript is the ^ sign and the character for the Alt key in vbscript is the % sign
Keystroke Equivalent
Alt %
Ctrl ^
Shift +

5. How do a send a right mouse click?

Try sending a a shift F10:
objSendKey.

SendKeys(“+{F10}”);

6. Are there any Sendkeys best practices?

There are a few I can think of :

Always move the application to a known start position.
Always set focus to the object you want to interact with before using SendKeys.
For synchronization issues use the .exist or wait functionality often in your script.

For Example:
objSetFocus.Move 10,10
wait 1
objSetFocus.Click

7. How do I send parenthesis using SendKeys?

Parenthesis are special characters in QTP so one way to do this is to use a combination of the shift key with the numeric nine and zero keys:
objSendKey.SendKeys(“+9”)
objSendKey.SendKeys(“joe colantonio”)
objSendKey.SendKeys(“+0”)

8. My SendKeys is not working when I try to send a multiple values.What should I do?

If QTP’s SendKeys is not performing as expected try sending each keystroke a separate line.

9. What is the QTPs equivalent for shell available in the market?

In QTP you can use the Run Method which can be used to run a file or an application. For example to start notepad:
SystemUtil.Run “notepad.exe”, “”, “”, “”

10. How to do a select a checkbox or a row in an object?

If the object like a checkbox has focus sending a blank space should select it:
objSendKey.SendKeys(” “)

11. How do I repeat a keystroke multiple times?

This only works for singe keystrokes but if you wanted to type a letter five times you could use this shortcut:
objSendKey.SendKeys(“{J 5}”)

12. What is VBScript’s equivalent for keystroke :

These are the short code for the equivalent keystroke available for the particular key.
Keystroke Equivalent
Alt %
Backspace {BACKSPACE}
Break {BREAK}
Caps Lock {CAPSLOCK}
Ctrl ^
Delete {DELETE}
Down Arrow {DOWN}
End {END}
Esc {ESC}
Help {HELP}
Home {HOME}
Insert {INSERT}
Left Arrow {LEFT}
Num Lock {NUMLOCK}
Page Down {PGDN}
Page Up {PGUP}
Print Screen {PRTSC}
Right Arrow {RIGHT}
Scroll Lock {SCROLLOCK}
Shift +
Tab {TAB}
UP Arrow {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}

13. What are the QTP VBScript’s string constants for non-visible characters in strings?

Constant Value Description
VbCr Chr(13) Carriage return
VbCrLf Chr(13) & Chr(10) Carriage return and a Linefeed
VbLf Chr(10) Line Feed
VbNewLine Chr(13) & Chr(10) New Line
VbTab Chr(9) Horizontal tab

14. I don’t see the action I need to perform in the chart above – what should I do?

Try the Device Replay method instead – check out the Device Replay chart (QTP DEVICE REAPLY CODE CHART )

15. I’m using C# not QTP how do I start an application

Use Process() for example:
using System;
using System.Diagnostics;
using System.Windows.Forms;
Process myProcess = new Process():
myProcess.StartInfo.FileName = “cmd”;
myProcess.Start();

16. In CSharp what are the SendKeys methods?

Flush() – processes all Window messages in the queue

Send() – this sends keystrokes to an app

SendWait() – Sends keystrokes to an app and waits for the keystrokes to complete.

More Info:

If you found this helpful you might want to also check out my post 3 ways to use keyboard input in QuickTest Professional: Type, SendKeys and Device Replay.

Bibliomaniacs:

And as always for my fellow bibliomaniacs who may want to dive deeper into SendKeys , I would also recommend these two books:

1. VBScript Programmer’s Reference. (Sendkey info starts on page 338)

2. A Tester’s Guide to .NET Programming (Expert’s Voice) – This book is for the automation imagineer who may want to create a simple custom GUI sendkeys app (check out page 173 of this book)

How to Handle XML Files in Python

Introduction

 

  • Xml (eXtensible Markup Language) is a markup language.
  • XML is designed to store and transport data.
  • Xml was released in late 90’s. it was created to provide an easy to use and store self-describing data.
  • XML became a W3C Recommendation on February 10, 1998.
  • XML is not a replacement for HTML.
  • XML is designed to be self-descriptive.
  • XML is designed to carry data, not to display data.
  • XML tags are not predefined. You must define your own tags.
  • XML is platform independent and language independent.

Sample XML File

<?xmlversion=“1.0”?>

<data>

<countryname=“Inida”>

<rankgrade=“22”>1</rank>

<yeargrade=“33”>2008</year>

<gdpgrade=“33”>141100</gdp>

<neighborname=“Austria”direction=“E”/>

<neighborname=“Switzerland”direction=“W”/>

</country>

<countryname=“Singapore”>

<rankgrade=“225”>1</rank>

<yeargrade=“335”>208</year>

<gdpgrade=“335”>11100</gdp>

<neighborname=“Malaysia”direction=“N”/>

</country>

<countryname=“US”>

<rank>68</rank>

<year>2011</year>

<gdppc>13600</gdppc>

<neighborname=“Canada”direction=“W”/>

<neighborname=“Colombia”direction=“E”/>

</country>

</data>

Python Module (xml.etree.ElementTree)

Parse()

This method will take the xml file as input  will parse to the python friendly tree.

getroot()

This will return us the roots of the tree element.

Get()

This method will return us the attribute of an particular root element.

import xml.etree.ElementTree as ETT
tree = ETT.parse('ConData.xml')
root = tree.getroot()
for i in root:
    print(i.get('name'))
    #print(i)
    for j in i:
        #print(j.get('grade'))
        print(j.text)

# for country in root.findall('country'):
#     rank = country.find('rank').text
#     rank = country.find('rank')
#     name = country.get('name')
#     print (name, rank)

Selenium Important Interview Question Part-II

Q #1) Why should Selenium be selected as a test tool?

Selenium

  1. is a free and open source
  2. have a large user base and helping communities
  3. have cross Browser compatibility (Firefox, Chrome, Internet Explorer, Safari etc.)
  4. have great platform compatibility (Windows, Mac OS, Linux etc.)
  5. supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)
  6. has fresh and regular repository developments
  7. supports distributed testing

Q #2) What are the testing types that can be supported by Selenium?

Selenium supports the following types of testing:

  1. Functional Testing
  2. Regression Testing

Q #3) What are the limitations of Selenium?

Following are the limitations of Selenium:

  • Selenium supports testing of only web-based applications
  • Mobile applications cannot be tested using Selenium
  • Captcha and Barcode readers cannot be tested using Selenium
  • Reports can only be generated using third-party tools like TestNG or JUnit.
  • The user is expected to possess prior programming language knowledge.

Q#4)What are the different Selenium components?

  • Selenium Integrated Development Environment (IDE) – Selenium IDE is a record and playback tool. It is distributed as a Firefox Plugin.
  • Selenium Remote Control (RC) – Selenium RC is a server that allows a user to create test scripts in the desired programming language. It also allows executing test scripts within the large spectrum of browsers.
  • Selenium WebDriver – WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility to automate.
  • Selenium Grid – Selenium Grid is used to distribute your test execution on multiple platforms and environments concurrently.

Q #5) What is Selenese?

Selenese is the language which is used to write test scripts .Generally Selenese refers to selenium commands.

Q #6) What are the different types of locators in Selenium?

The locator can be termed as an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely.Locators are,

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath
  • CSS Selector

Q #7) What is the difference between assert and verify commands?

Assert: Assert command checks whether the given condition is true or false. Let’s say we assert whether the given element is present on the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the execution would stop and no further test would be executed.

Q #8) What is an XPath?

XPath is used to locate a web element based on its XML path. XML stands for Extensible Markup Language and is used to store, organize and transport arbitrary data. It stores data in a key-value pair which is very much similar to HTML tags. Both being markup languages and since they fall under the same umbrella, XPath can be used to locate HTML elements.

The fundamental behind locating elements using XPath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element.

Q #9) What is the difference between “/” and “//” in Xpath?

Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.

Double Slash “//” – Double slash is used to create Xpath with relative path i.e. the xpath would be created to start selection from anywhere within the document.

Q #10) What is Same origin policy and how it can be handled?

The problem of same origin policy disallows to access the DOM of a document from an origin that is different from the origin we are trying to access the document.

Origin is a sequential combination of scheme, host, and port of the URL. For example, for a URL https://www.softwaretestinghelp.com/resources/, the origin is a combination of http, softwaretestinghelp.com, 80 correspondingly.

Q #11) When should I use Selenium Grid?

Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution, testing under different environments and saving execution time remarkably.

Q #12) What do we mean by Selenium 1 and Selenium 2?

Selenium RC and WebDriver, in a combination, are popularly known as Selenium 2. Selenium RC(Selenium          remotecontrol )alone is also referred as Selenium 1.

 #13) What are the different types of waits available in WebDriver?

There are two types of waits available in WebDriver:

  1. Implicit Wait
  2. Explicit Wait

Implicit Wait: Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.

Explicit Wait: Explicit waits are used to halt the execution till the time a particular condition is met or the maximum time has elapsed. Unlike Implicit waits, explicit waits are applied for a particular instance only.

Q #14) How can you find if an element in displayed on the screen?

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

  1.  
  2.  
  3.  

 

 

Q #15) What are the different types of navigation commands?

Following are the navigation commands:
navigate().back() – The above command requires no parameters and takes back the user to the previous webpage in the web browser’s history.

Sample code:
driver.navigate().back();

navigate().forward() – This command lets the user to navigate to the next web page with reference to the browser’s history.

Sample code:
driver.navigate().forward();

navigate().refresh() – This command lets the user to refresh the current web page there by reloading all the web elements.

Sample code:
driver.navigate().refresh();

navigate().to() – This command lets the user to launch a new web browser window and navigate to the specified URL.

Sample code:
driver.navigate().to(“https://google.com”);

Q #16) What is the difference between driver.close() and driver.quit command?

close(): WebDriver’s close() method closes the web browser window that the user is currently working on or we can also say the window that is being currently accessed by the WebDriver. The command neither requires any parameter nor does it return any value.

quit(): Unlike close() method, quit() method closes down all the windows that the program has opened. Same as close() method, the command neither requires any parameter nor does is return any value.

Q #17) Can Selenium handle windows based pop up?

Selenium is an automation testing tool which supports only web application testing. Therefore, windows pop up cannot be handled using Selenium.

Q #18) How can we handle web-based pop up?

WebDriver offers the users with a very efficient way to handle these pop-ups using Alert interface. There are the four methods that we would be using along with the Alert interface.

  • void dismiss() – The accept() method clicks on the “Cancel” button as soon as the pop-up window appears.
  • void accept() – The accept() method clicks on the “Ok” button as soon as the pop-up window appears.
  • String getText() – The getText() method returns the text displayed on the alert box.
  • void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.

Syntax:- 
                Alert alert = driver.switchTo().alert();
alert.accept();

Q #19) How can we handle windows based pop up?

Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support testing of windows based applications. However Selenium alone can’t help the situation but along with some third-party intervention, this problem can be overcome. There are several third-party tools available for handling window based pop-ups along with the selenium like AutoIT, Robot class etc.

Q #20) What is Object Repository? How can we create Object Repository in Selenium?

Object Repository is a term used to refer to the collection of web elements belonging to Application Under Test (AUT) along with their locator values. Thus, whenever the element is required within the script, the locator value can be populated from the Object Repository. Object Repository is used to store locators in a centralized location instead of hardcoding them within the scripts.

In Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.

 

How to Verify or Check XPath Using Chrome Native Tools

To verify an element using native chrome no need of any plugins or any extentions we can check our xpath Using Chrome Browser itself as described in this How to Verify or Check XPath Using Chrome Native Tools post.

Step 1:Install Chrome

Chrome Installatio  is the normal installation download the chrome form the official site link.

Step 2:Open Chrome

Step 3: Open Developer Option
You can open developer option by 3 Ways.

1st Method

Go to the Chrome Option ->More Tools ->Developer Tools

2st Method

Press Ctrl+Shift+I
To open the developer option

3st Method

Press F12 to open the developer option

Once the Developer tool is open you can able to see the multiple frame in side the chrome window.

Step 4:

Click on the HTML and Press Ctrl+F
Once text Box Will pop Up you can search any text or verify your XPATH

 

Python + Selenium Syllabus

  • 1. Installation
  • 2. Getting Started
    • 2.1. Simple Usage
    • 2.2. Example Explained
    • 2.3. Using Selenium to write tests
    • 2.4. Walk through of the example
    • 2.5. Using Selenium with remote WebDriver
  • 3. Navigating
    • 3.1. Interacting with the page
    • 3.2. Filling in forms
    • 3.3. Drag and drop
    • 3.4. Moving between windows and frames
    • 3.5. Popup dialogs
    • 3.6. Navigation: history and location
    • 3.7. Cookies
  • 4. Locating Elements
    • 4.1. Locating by Id
    • 4.2. Locating by Name
    • 4.3. Locating by XPath
    • 4.4. Locating Hyperlinks by Link Text
    • 4.5. Locating Elements by Tag Name
    • 4.6. Locating Elements by Class Name
    • 4.7. Locating Elements by CSS Selectors
  • 5. Waits
    • 5.1. Explicit Waits
    • 5.2. Implicit Waits
  • 6. Page Objects
    • 6.1. Test case
    • 6.2. Page object classes
    • 6.3. Page elements
    • 6.4. Locators
  • 7. WebDriver API
    • 7.1. Exceptions
    • 7.2. Action Chains
    • 7.3. Alerts
    • 7.4. Special Keys
    • 7.5. Locate elements By
    • 7.6. Desired Capabilities
    • 7.7. Touch Actions
    • 7.8. Proxy
    • 7.9. Utilities
    • 7.10. Service
    • 7.11. Application Cache
    • 7.12. Firefox WebDriver
    • 7.13. Firefox WebDriver Options
    • 7.14. Firefox WebDriver Profile
    • 7.15. Firefox WebDriver Binary
    • 7.16. Firefox WebDriver Extension Connection
    • 7.17. Chrome WebDriver
    • 7.18. Chrome WebDriver Options
    • 7.19. Chrome WebDriver Service
    • 7.20. Remote WebDriver
    • 7.21. Remote WebDriver WebElement
    • 7.22. Remote WebDriver Command
    • 7.23. Remote WebDriver Error Handler
    • 7.24. Remote WebDriver Mobile
    • 7.25. Remote WebDriver Remote Connection
    • 7.26. Remote WebDriver Utils
    • 7.27. Internet Explorer WebDriver
    • 7.28. Android WebDriver
    • 7.29. Opera WebDriver
    • 7.30. PhantomJS WebDriver
    • 7.31. PhantomJS WebDriver Service
    • 7.32. Safari WebDriver
    • 7.33. Safari WebDriver Service
    • 7.34. Select Support
    • 7.35. Wait Support
    • 7.36. Color Support
    • 7.37. Event Firing WebDriver Support
    • 7.38. Abstract Event Listener Support
    • 7.39. Expected conditions Support
  • 8. Appendix: Frequently Asked Questions
    • 8.1. How to use ChromeDriver ?
    • 8.2. Does Selenium 2 support XPath 2.0 ?
    • 8.3. How to scroll down to the bottom of a page ?
    • 8.4. How to auto save files using custom Firefox profile ?
    • 8.5. How to upload files into file inputs ?
    • 8.6. How to use firebug with Firefox ?
    • 8.7. How to take screenshot of the current window ?

Pyhton Code to Get Text Data From Pdf File by fetching form URL or Form Local Drive

In this post we will explain how to fetch the text data from the pdf file using Pyhton Code. To Get Text Data From Pdf You need to in install the flowing python library for data read form the pdf document.

1.urllib

This library will help you to download data file or pdf from the internet.By using this library we can download file from the http sites .

To install url library use this below command to get the data form the web.

pip install urllib

pip install urllib2

pip install urllib3

import urllib

urllib.urlretrieve(‘http://ird.iitd.ac.in/sites/default/files/jobs/project/advtprofaksrivastava2.pdf’, ‘data.pdf’)

2.PyPDF2

This library will help you to read the pdf and extract data

import PyPDF2
pdfFileObj = open('data.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
print pdfReader.numPages
pageObj = pdfReader.getPage(0)
print pageObj.extractText()

 
        

Chewing data Efficiently with NumPy and intelligently with SciPy

In this following tutorial we will learn about Chewing data Efficiently with NumPy and intelligently with SciPy and the NumPy. Let us quickly walk through some basic NumPy examples and then take a look at what SciPy provides on top of it. On the way, we will get our feet wet with plotting using the marvelous Matplotlib package.
You will fnd more interesting examples of what NumPy can offer at

    http://www.scipy.org/Tentative_NumPy_Tutorial.

You will also fnd the book NumPy Beginner’s Guide – Second Edition, Ivan Idris,Packt Publishing very valuable. Additional tutorial style guides are at http://scipy-lectures.github.com; you may also visit the offcial SciPy tutorial at http://docs.scipy.org/doc/scipy/reference/tutorial.


In this blog, we will use NumPy Version 1.6.2 and SciPy Version 0.11.0.
Learning NumPy
So let us import NumPy and play a bit with it. For that, we need to start the Python
interactive shell.

      >>> import numpy
>>> numpy.version.full_version
1.6.2

As we do not want to pollute our namespace, we certainly should not do the following:

      >>> from numpy import *


The numpy.array array will potentially shadow the array package that is included


in standard Python. Instead, we will use the following convenient shortcut:

>> import numpy as np
>>> a = np.array([0,1,2,3,4,5])
>>> a
array([0, 1, 2, 3, 4, 5])
>>> a.ndim
1
>>> a.shape
(6,)


We just created an array in a similar way to how we would create a list in Python.However, NumPy arrays have additional information about the shape. In this case,it is a one-dimensional array of fve elements. No surprises so far.


We can now transform this array in to a 2D matrix.
>>> b = a.reshape((3,2))
>>> b
array([[0, 1],
[2, 3],
[4, 5]])
>>> b.ndim
2
>>> b.shape
(3, 2)



The funny thing starts when we realize just how much the NumPy package is
optimized. For example, it avoids copies wherever possible.

>> b[1][0]=77
>>> b
array([[ 0, 1],
[77, 3],
[ 4, 5]])
>>> a
array([ 0, 1, 77, 3, 4, 5])


In this case, we have modifed the value 2 to 77 in b, and we can immediately see
the same change reflected in
a as well. Keep that in mind whenever you need a
true copy.

>> c = a.reshape((3,2)).copy()
>>> c
array([[ 0, 1],
[77, 3],
[ 4, 5]])
>>> c[0][0] = -99
>>> a
array([ 0, 1, 77, 3, 4, 5])
>>> c
array([[-99, 1],
[ 77, 3],
[ 4, 5]])


Here, c and a are totally independent copies.
Another big advantage of NumPy arrays is that the operations are propagated
to the individual elements.

>> a*2
array([ 2, 4, 6, 8, 10])
>>> a**2
array([ 1, 4, 9, 16, 25])
Contrast that to ordinary Python lists:
>>> [1,2,3,4,5]*2
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> [1,2,3,4,5]**2
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): ‘list’ and
‘int’


Of course, by using NumPy arrays we sacrifce the agility Python lists offer. Simple
operations like adding or removing are a bit complex for NumPy arrays. Luckily,
we have both at our disposal, and we will use the right one for the task at hand.
Indexing


Part of the power of NumPy comes from the versatile ways in which its arrays can
be accessed.
In addition to normal list indexing, it allows us to use arrays themselves as indices.

>> a[np.array([2,3,4])]
array([77, 3, 4])
In addition to the fact that conditions are now propagated to the individual elements,
we gain a very convenient way to access our data.
>>> a>4
array([False, False, True, False, False, True], dtype=bool)
>>> a[a>4]
array([77, 5])
This can also be used to trim outliers.
>>> a[a>4] = 4
>>> a
array([0, 1, 4, 3, 4, 4])


As this is a frequent use case, there is a special clip function for it, clipping the values
at both ends of an interval with one function call as follows:

>> a.clip(0,4)
array([0, 1, 4, 3, 4, 4])

 

Handling non-existing values
The power of NumPy’s indexing capabilities comes in handy when pre processing data that we have just read in from a text fle. It will most likely contain invalid values, which we will mark as not being a real number using numpy.NAN as follows:

c = np.array([1, 2, np.NAN, 3, 4]) # let’s pretend we have read this
from a text file
>>> c
array([ 1., 2., nan, 3., 4.])
>>> np.isnan(c)
array([False, False, True, False, False], dtype=bool)

>>> c[~np.isnan(c)]
array([ 1., 2., 3., 4.])
>>> np.mean(c[~np.isnan(c)])
2.5


Comparing runtime behaviors Let us compare the runtime behavior of NumPy with normal Python lists. In the
ollowing code, we will calculate the sum of all squared numbers of 1 to 1000 and see how much time the calculation will take. We do it 10000 times and report the total time so that our measurement is accurate enough.

import timeit
normal_py_sec = timeit.timeit(‘sum(x*x for x in xrange(1000))’,
number=10000)
naive_np_sec = timeit.timeit(‘sum(na*na)’,
setup=”import numpy as np; na=np.
arange(1000)”,
number=10000)
good_np_sec = timeit.timeit(‘na.dot(na)’,
setup=”import numpy as np; na=np.
arange(1000)”,
number=10000)
print(“Normal Python: %f sec”%normal_py_sec)
print(“Naive NumPy: %f sec”%naive_np_sec)
print(“Good NumPy: %f sec”%good_np_sec)
Normal Python: 1.157467 sec
Naive NumPy: 4.061293 sec
Good NumPy: 0.033419 sec


We make two interesting observations. First, just using NumPy as data storage (Naive NumPy) takes 3.5 times longer, which is surprising since we believe it must be much faster as it is written as a C extension. One reason for this is that the access of individual elements from Python itself is rather costly. Only when we are able to apply algorithms inside the optimized extension code do we get speed improvements, and
tremendous ones at that: using the
dot() function of NumPy, we are more than 25 times faster. In summary, in every algorithm we are about to implement, we should always look at how we can move loops over individual elements from Python to some of the highly optimized NumPy or SciPy extension functions.

However, the speed comes at a price. Using NumPy arrays, we no longer have the incredible flexibility of Python lists, which can hold basically anything. NumPy arrays always have only one datatype.
>>> a = np.array([1,2,3])
>>> a.dtype
dtype(‘int64’)
If we try to use elements of different types, NumPy will do its best to coerce them to the most reasonable common datatype:
>>> np.array([1, “stringy”])
array([‘1’, ‘stringy’], dtype=’|S8′)
>>> np.array([1, “stringy”, set([1,2,3])])
array([1, stringy, set([1, 2, 3])], dtype=object)