Python Essentials



Python Introduction

  • Python is an interpreted, interactive, high-level, object-oriented programming language.
  • Python is a general-purpose language. It is not a domain-specific, i.e., it is not designed to be used within a specific application domain only; it can be applied to different classes of problems.
  • Python came into existence in 1989 when it was first implemented by Guido van Rossum, quite before when Java came in 1995.
  • Python programming language is ideal for scripting and rapid application development.
  • Python has wide range of applications from Web development, scientific and mathematical computing to desktop graphical user Interfaces.
  • The syntax of the Python language is clean and length of the code is relatively short. It's fun to work in Python because it allows the coder to think about the problem rather than focusing on the syntax.
  • Python codes are shorter and easier to understand in comparison to other programming languages. For example, see the difference in the lines of code used to print "Hello World" in Java, C, and Python:

Installing Python

  • Python releases for Windows can be downloaded from this link: https://www.python.org/downloads/windows/. After installing Python as usual, go to command prompt and type ...>python to check the installation. See image below. After installing Python, do not forget to set the PATH in the Environmental variable. E.g.: C:\Python27\
  • Additionally, to check further that python is working, copy and paste the following code in a text editor, save it in the users path (shown in the command prompt) as Demo.py and type ...>python Demo.py and see how the program works.
    x = int(input("Enter a number x: "))
    y = int(input("Enter a number y: "))
    print("Addition of", x, "and", y, "is: ", x+y)
    print("Difference of", x, "and", y, "is: ", x-y)
    print("Product of", x, "and", y, "is ", x*y)
  • The above step is used to install only the Python Interpreter. To write and manage scripts or programs efficiently, we need an IDE – Integrated Development Environment. One of the best IDE for working in Python is PyCharm developed by JetBrains. The PyCharm IDE can be downloaded from the link: https://www.jetbrains.com/pycharm/download/.
  • The Community edition of PyCharm IDE, which is a Lightweight IDE for scientific development, is sufficient for personal learning and for most users.
  • One of the best things about Python is that it has wide range of software packages written by various developers from the scientific community and we can simply use those packages for our use, without reinventing the wheel. To install the packages we need the Python Package Manager (PyPM or pip). Pip is a Python utility intended to simplify the tasks of locating, installing, upgrading and removing Python packages. Pip can be installed with the following command in the command prompt: ...>python -m pip install -U pip
  • After installing pip, do not forget to set the PATH in the Environmental variable. For Python 2.7 version, pip is located in the Scripts folder. Hence, PATH is set as C:\Python27\Scripts\.

Common Operators


In command prompt, type python (...>python) for the python prompt >>> and check the how the Python Interpreter delivers results instantaneously. You can also use the python IDLE called Python Shell.
>>> 2+5
7
>>> 9-8
1
>>> 3-9
-6
>>> 4*3
12
>>> 8/4
2.0
>>> 5//2
2

// is called Integer Division or Floor Division, gives the quotient part
>>> 10 % 3
1

% is called Modulus, gives the reminder part
>>> 8 + 2 *3
14
>>> 8 + (2*3)
14
>>> (8 + 2) * 3
30

>>> 2 ** 3
8

** is called the Power of operator
String values are written inside quotes:
>>> 'vinod'
'vinod'
>>> print ('vinod')
vinod
Same type of quotation marks are used:
>>> print ("Vinod's laptop")
Vinod's laptop
>>> print ('Vinod "laptop"')
Vinod "laptop"
>>> print('Vinod\'s ' "laptop")
Vinod's laptop
\ is used to distinguish a same type quotation mark inside a quote
>>> 'vinod' + 'vinod'
'vinodvinod'
>>> print ('vinod' + 'vinod')
vinodvinod
>>> 10 * 'vinod'
'vinodvinodvinodvinodvinodvinodvinodvinodvinodvinod'
>>> print (10 * 'vinod')
vinodvinodvinodvinodvinodvinodvinodvinodvinodvinod
>>> print ('c:\docs\vinod')
c:\docs
inod
Note that v is missing and inod is printed in the next line. (I am using command prompt.)
This is because \n, \r and \t have special meaning in Python. These are called String Literals. \n means new line, \r means carriage return, \t means tab. In terminals the effects of \v and \f are often the same as new line. Hence inod is printed in the new line. This can be corrected as following:
>>> print (r'c:\vkr\docs')
c:\vkr\docs
Now it prints correctly. This is because of the use of r, called a Raw String, used to nullify the special meaning of \n, \r, \t or \v
Similarly, ASCII character is represented using the \xhh notation.
>>> print("\x23")
#
>>> print("\x24")
$
>>> print("\x34")
4
>>> print("\x64")
d
>>> print (50 * '-')
--------------------------------------------------

Variables


In Python, variables are nothing but reserved memory locations to store values. This means that when we create a variable we basically reserve some space in memory. In Java or C, the type of every variable has to be declared before it can be used. Declaring the type of a variable means binding it to a data type. Unlike in other programing languages, declaration of type of variables is not required in Python.
Some examples using variables in python is shown below.

>>> 2 + 3
5
>>> x = 2
>>> x + 3
5
>>> y = 3
>>> x + y
5
>>> x = 9
>>> x + y
12
>>> y = 10
>>> x * y
90
>>> x
9
>>> y
10
>>> x + 20
29
>>> _ + y
39

_ mean the output of the previous operation.
>>> name = 'youtube'
>>> name
'youtube'
>>> print (name)
youtube
>>> print ('name')
name
>>>
>>> name + 'rocks'
'youtuberocks'
>>> name[0]
'y'
>>> name[1]
'o'
>>> name[-1]
'e'
>>> name[-7]
'y'
>>> name[0:2]
'yo'
>>> name[1:4]
'out'
>>> name[1:]
'outube'
>>> name[:4]
'yout'
>>> name[3:10]
'tube'

Even if there is no 10 characters, it will stop at index number of the maximum number of character i.e., 6
>>> 'my ' + name[3:]
'my tube'
>>> myname = 'Vinod Rowmuria'
>>> len(myname)
14

As mentioned above, in Python variables reserve memory locations to store values. The following examples show the memory locations for the variables.
>>> num = 5
>>> id(num)
140727162688672
>>> name = 'vinod'
>>> id(name)
2405631147624
>>> a = 10
>>> b = a
>>> a
10
>>> b
10
>>> id(a)
140727162688832
>>> id(b)
140727162688832
>>> id(10)
140727162688832
>>> k = 10
>>> id(k)
140727162688832

Note that the id value representing the memory location value for a, b, 10, and k, is the same.
>>> a = 9
>>> id(a)
140727162688800
>>> id(b)
140727162688832
>>> id(k)
140727162688832
>>> k=a
>>> id(k)
140727162688800
>>> b = 8
>>> id(b)
140727162688768
>>> id(10)
140727162688832

Note that 10 is no longer assigned to any variable. So, its memory location is no longer in used. And so this memory location will be part of the Garbage Collection. Python's memory allocation and deallocation method is automatic.
>>> 22 / 7
3.142857142857143
>>> PI = 3.14
>>> PI
3.14
>>> PI = 3.15
>>> PI
3.15
>>> type(PI)
<class 'float'>
>>> type(a)
<class 'int'>
>>> type(name)
<class 'str'>


Data Types in Python

  1. None (like Null)
  2. Numeric (int, float, complex, bool)
  3. List
  4. Tuple
  5. Set
  6. String
  7. Range
  8. Map or Dictionary
The items from 3 to 7 are also called Sequence and are widely used in data-centric applications. These are - List, Tuple, Set, String, and Range.
Let's see the Data Types in the following examples:
>>> num = 2.5
>>> type(num)
<class 'float'>
>>> num = 5
>>> type(num)
<class 'int'>
>>> num = 6+9j
>>> type(num)
<class 'complex'>

Complex Number like a+bi. In the above Complex Number example j (in Python) stands for i.
>>> a = 5.6
>>> b = int(a)
>>> type(b)
<class 'int'>
>>> b
5
>>> k = float(b)
>>> k
5.0
>>> k = 6
>>> c = complex(b,k)
>>> c
(5+6j)
>>> type(c)
<class 'complex'>
>>> b
5
>>> k
6
>>> b<k
True
>>> b>k
False
>>> con = b < k
>>> con
True
>>> type(con)
<class 'bool'>
Why bool a numeric data type? Because bool represents 1 and 0; 1 for True, 0 for False.
>>> int(True)
1
>>> int(False)
0

List in Python


There are four collection data types in the Python - List, Tuple, Set, and Dictionary.
List collection is ordered and changeable, and is represented with square brackets.
>>> nums = [25, 12, 36, 75, 46]
>>> nums
[25, 12, 36, 75, 46]
>>> nums[0]
25
>>> nums[3]
75
>>> nums[2:]
[36, 75, 46]
>>> nums[-1]
46
>>> nums[-5]
25
>>> names = ['vinod','navin','john']
>>> names
['vinod', 'navin', 'john']
>>> values = [9.5, 'vinod', 25]
>>> values
[9.5, 'vinod', 25]
>>> mix = [nums, names]
>>> mix
[[25, 12, 36, 75, 46], ['vinod', 'navin', 'john']]
>>> misc = [nums, names, values]
>>> misc
[[25, 12, 36, 75, 46], ['vinod', 'navin', 'john'], [9.5, 'vinod', 25]]
>>> nums.append(14)
>>> nums
[25, 12, 36, 75, 46, 14]
>>> nums.insert(2,77)
>>> nums
[25, 12, 77, 36, 75, 46, 14]
>>> nums.pop(1)
12
>>> nums
[25, 77, 36, 75, 46, 14]
>>> nums.pop()
14
>>> nums
[25, 77, 36, 75, 46]
>>> del nums[2:]
>>> nums
[25, 77]
>>> nums.extend([29,12,14,36])
>>> nums
[25, 77, 29, 12, 14, 36]
>>> min(nums)
12
>>> max(nums)
77
>>> sum(nums)
193
>>> nums.sort()
>>> nums
[12, 14, 25, 29, 36, 77]


Tuple in Python


List is mutable. Tuple is not mutable; we can’t change the values. Tuple is represented with round brackets.
>>> tup = (21,36,14,25)
>>> tup
(21, 36, 14, 25)
>>> tup[1]
36
>>> tup.count(21)
1
>>> tup.count(25)
1
>>> tup.index(21)
0
>>> tup.index(25)
3


Set in Python


The elements in the set cannot be duplicates. The elements in the set are immutable(cannot be modified) but the set as a whole is mutable. There is no index attached to any element in a python set. So they do not support any indexing or slicing operation. Set is represented with curly brackets.
>>> set = {22,25,14, 21,5}
>>> set
{5, 14, 21, 22, 25}
>>> set = {25,14,98,63,75,98,44,62}
>>> set
{98, 75, 44, 14, 25, 62, 63}
>>> set.add(87)
>>> set
{98, 75, 44, 14, 87, 25, 62, 63}


Dictionary in Python


Dictionary collection is unordered, changeable and indexed, and they have keys and values. Dictionary is represented with curly brackets.

>>> d = {"fname": "Vikash", "lname": "Sharma", "age": 25}
>>> print(d)
{'fname': 'Vikash', 'lname': 'Sharma', 'age': 25}


Checking Data Types for List, Tuple, and Set


>>> lst = [25, 36, 47, 54]
>>> tpl = (12, 33,84, 27, 46)
>>> set = {35, 46, 23, 15, 78}
>>> type(lst)
<class 'list'>
>>> type(tpl)
<class 'tuple'>
>>> type(set)
<class 'list'>
>>> lst
[25, 36, 47, 54]
>>> tpl
(12, 33, 84, 27, 46)
>>> set
[35, 46, 23, 15, 78]
>>> st1 = {35, 46, 23, 15, 78}
>>> type(st1)
<class 'set'>
>>> st1
{35, 78, 15, 46, 23}
>>> st = 'vinod'
>>> type(st)
<class 'str'>
>>> range(0, 10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range (5))
[0, 1, 2, 3, 4]
>>> type(range)
<class 'type'>
>>> type(range(10))
<class 'range'>
>>> lst1 = list(range (5))
>>> type(lst1)
<class 'list'>

Map or Dictionary - Identify each object in a Map as Key, and Key should not repeat, so use curly brackets as used in Set, which means values should not repeat.
>>> d = {'vinod':'Samsung', 'rahul':'iPhone', 'kiran':'Nokia', 'sunil':'OnePlus', 'john':'Micromax'}
>>> d
{'vinod': 'Samsung', 'rahul': 'iPhone', 'kiran': 'Nokia', 'sunil': 'OnePlus', 'john': 'Micromax'}
These are called key-value-pairs, where key is 'vinod' and value is 'Samsung', and so on...
>>> type(d)
<class 'dict'>
>>> d.keys()
dict_keys(['vinod', 'rahul', 'kiran', 'sunil', 'john'])
>>> d.items()
dict_items([('vinod', 'Samsung'), ('rahul', 'iPhone'), ('kiran', 'Nokia'), ('sunil', 'OnePlus'), ('john', 'Micromax')])
>>> d.values()
dict_values(['Samsung', 'iPhone', 'Nokia', 'OnePlus', 'Micromax'])
>>> d['rahul']
'iPhone'
>>> d.get('vinod')
'Samsung'


More on Operators in Python


Arithmetic Operators using Variables:
>>> x = 2
>>> y = 3
>>> z = x + y
>>> z
5
>>> x - y
-1
>>> x * y
6
>>> x / y
0.6666666666666666
>>> y // x
1
>>> x // y
0
>>> x = x + 2
>>> x
4
>>> x += 2
>>> x
6
>>> x *= 3
>>> x
18
>>> a,b = 5,6
>>> a
5
>>> b
6
>>>


Relational Operators:
>>> a
5
>>> b
6
>>> a < b
True
>>> b < a
False
>>> a == b
False
>>> a = 6
>>> a == b
True
>>> a,b
(6, 6)
>>> a < b
False
>>> a <= b
True
>>> a != b
False
>>> a >= b
True
>>> b != a
False
>>>


Logical Operators: And - Or - Nor
>>> a = 5
>>> b = 4
>>> a,b
(5, 4)
>>> a < 8 and b < 5
True
>>> a > 8 or b < 5
True
>>> a < 8 and b < 2
False
>>> a < 8 and b > 5
False
>>> x = True
>>> x
True
>>> not x
False
>>> x = not x
>>> x
False
>>>
Unary
>>> n=7
>>> n
7
>>> -n
-7
>>> n = -n
>>> n
-7


Help Command in Python


Use help command help() to know further details on everything in Python.
>>> help()

Welcome to Python 3.7's help utility!

help> topics

Here is a list of available topics.  Enter any topic name to get more help.

help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

help> symbols

Here is a list of the punctuation symbols which Python assigns special meaning
to. Enter any symbol to get more help.

help> modules   

Please wait a moment while I gather a list of all available modules...

help> LISTS
Mutable Sequence Types
**********************

>>> help('LISTS')
Mutable Sequence Types
**********************

help> quit



Reference: Taking online class from Navin Reddy's Python YouTube Videos