Chapter 1 Introduction
Chapter 1 Introduction
Chapter 1 Introduction
Python Programming
by Narendra Allam
Copyright 2019
Chapter 1
Introduction
Topics Covering
Introduction to Python
Values and variables
Python data types
type(), id(), sys.getsizeof()
Python labeling system
Object pooling
Conversion functions
The language which knew infinity
Console input, output
Operators in python
Built-in functions
Type conversions
Exercise Programs
Introduction
There are 5000+ programming langauges in the world and we are still counting... Python is in the top 5
programming langauges as of 2019. Java, C, C++ and C# are other langauges in the top 5.
Python developed by Guido Van Rossum in 1989, and came into the programming world in 1991.
Python came into software industry as a scripting language.. PERL and Bash were other alternatives for
scripting by that time.
Later python was widely adopted in the research community and became a complete programming
language with robust futures like object orientation and functional programming. Having machine learning and
data analysis packages, Python has extensive support for research.
a devops engineer
a server side programmer
etc..
Python features
High-level programming languages are close to business problems. . whereas low-level programming
languages are close to system's problems..
Examples of Business problems are writing banking software, building an ecommerce website etc., Examples
of system problems are writing a device driver, memory manager, anti-virus, etc.
2. Interpreted
Python is interpreted programming language. Code which is written in English, has to be translated to binary
code and understood by a computer. This is the process of translation.
1. Compilation.
2. Interpretation.
In compilation a compiler translates all the lines of code at the same time then starts the execution first line of
code.
In interpretation an interpreter takes the first line, translates to machine code and executes, then takes the
second line and so on.
3. Multi-purpose
Python is a general purpose language. One can use python as a scripting language or as a programming
language, the puspose for which we use is different. In automation field, python programming is called as
scripting. And in application development side, it is called programming. In both cases, a single set of python
keywords and constructs are used. As a computer language there is no difference between scripting and
Programming in python.
Note:
The biggest difference is, Programming requires designing whihc is not necessary for scripting As we design,
programs are maintained for longer time, where as scripts are short-lived and use and throw code files.
5. Extensible
High-level languages are not performant, because they are more focused to provide developer friendly
environment than optimizing for speed.
In real-time and time-critical applications, when performance required, we still have to consider languages
with low-level features, like C and C++. Python provides futures required to merge other programming
languages with python code. Java code can be used in python using 'jython', C# code can be accessed using
'IronPython'.
6. Multi paradigm
Python welcomes programmers from various backgrounds, as python supports procedural, functional and
object oriented programming styles.
Software Installation
All the code examples in this book, are developed and tested using cutting edge tools, jupyter notebook and
PyCharm IDE.
Anaconda installation:
Download and install python 3.7 www.anaconda.com (http://www.anaconda.com) (anaconda python). We are
suggesting anaconda python for practice, as it bundles all the packages required for a programmer. If you
install python community version from www.python.org (http://www.python.org), you need to install required
packages seperately.
Just double click on the installer and follow the wizard to complete the installation.
Open Anaconda Prompt(command prompt) on Windows or terminal(shell) for Linux and Mac Users.
type 'python' command and hit enter, you should see the below screen.
WINDOWS:
MAC:
This is python shell, we can use this for python programming, but we have a better option Jupyter notebook.
Come out of this shell by typing _'ctrl + D'_.
Some text scrolling , but wait until you see your default browser with the following screen.
Do not close cmd/shell, which should be running in the bachground, just minimize it.
Creating a notebook:
Open New button on the right side and click on python 2 or python 3, then 'Untitled' is created now, we
can rename it just clicking on 'Untitled' word on the top.
We can start programming here, write python code and 'Shift + Enter' to execute each cell. We can type
multiple lines in the same cell.
In [1]:
1 100 * 67.89
Out[1]:
6789.0
In [2]:
1 1450 / 60 / 3
Out[2]:
8.055555555555555
Order of evaluation matters? Of course, yes. We are supposed to calculate 60/3 first then the result 20, divides
1450. By default order of evaluation is left to right for most of the operators, except assignment operators, it is
right to left.
In [3]:
1 1450 / (60 / 3)
Out[3]:
72.5
In [4]:
1 1450.0 / (60 / 3)
Out[4]:
72.5
We can use built-in functions. There is a function ceil() in module(set of functions) called 'math' in python. We
have to import math module and we can use functions in it.
In [5]:
1 import math
2 math.ceil(1450.0 / (60 / 3))
Out[5]:
73
There are so many functions in math module, we will discuss in detail in modules topic.
In [6]:
1 (3 + 4 + 5)/ 2.0
Out[6]:
6.0
In [7]:
1 (6*(6-3)*(6-4)*(6-5))**0.5
Out[7]:
6.0
Using variables
If we define variables, we do not need to change entire expression, instead change the values assigned to
variables.
In [8]:
1 a = 3
2 b = 4
3 c = 5
4 s = (a + b + c)/ 2.0
5 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
6 print ('Area: ', area)
Area: 6.0
Note: print() is an output function in python3, and is used to display output on the conaolew or shell.
int
float
str
bool
complex
Dynamically typed
In python variables change their data types dynamically.
In [9]:
1 x = 20
2 print(type(x))
<class 'int'>
In [10]:
1 x = 3.5
In [11]:
1 type(x)
Out[11]:
float
In [12]:
1 x = 'Apple'
In [13]:
1 type(x)
Out[13]:
str
now 'x' has become a str, as python is 'Dynamically typed' language. Variables can change their data type
when a different value is assigned.
In [14]:
1 x = True
In [15]:
1 type(x)
Out[15]:
bool
In [16]:
1 x = 2 + 3j
In [17]:
1 type(x)
Out[17]:
complex
'x' can change its type dynamically, because of python memory model and labeling system.
In [18]:
1 a = 2
2 b = 4
3 c = 5
4
5 s = a + b + c
6 avg = s / 3
7 print('average =', avg)
average = 3.6666666666666665
input() is the function which is used to read the values from the keyboard. Prompt string is optional
syntax:
In [19]:
Enter x value: 12
In [20]:
Enter y value: 25
In [21]:
1 print(x)
12
In [22]:
1 print(y)
25
Note:
As explained above, 'print' is the statement/function used to print values on console but when shell is used,
'print' statement is not required, we can directly get the output by typing the variable name. When running as a
script 'print' is mandatory
In [23]:
In [24]:
1 x + y
Out[24]:
'1225'
Note: By default 'raw_input()' function reads values as strings.We should explicitly convert them to the target
type.
Conversion functions
In python, we can change one type into other if it is legitimate. We have conversion functions for all types in
python.
int()
float()
bool()
str()
complex()
In [25]:
Enter x Value: 20
Enter y Value: 30
Sum = 50
In [26]:
1 x = input()
2 type(x)
56
Out[26]:
str
In [27]:
1 x = -100
2 y = 300
3 z = x + y
4 print(x, 'plus', y, 'is', z, 'and', x, 'is -ve')
In [28]:
1 x = -100
2 y = 300
3 z = x + y
4 print('{} plus {} is {} and {} is -ve'.format(x, y, z, x))
'{}' is the place holder for a value we can add any text in between as above
or
In [29]:
1 x = -100
2 y = 300
3 z = x + y
4 print('{0} plus {1} is {2} and {0} is -ve'.format(x, y, z))
we can reorder the arguments using their positional values(indices) in the format function.
x index is {0},
y index is {1},
z index is {2} and so on...
And we can also use them multiple times, as below
In [30]:
In [31]:
1 x = 20
In [32]:
1 print (id(x))
10965504
In [33]:
1 x = 30
If we execute above statement in other programming languages like C/C++, Java and C#, x's old value(20) will
be replaced by 30, as 'x' owns a memory location and always can hold one value. In python value '20' owns
the location 'x' is just a label to it. When we assign 30, x will be moved to 30's location by leaving 20's location.
If there is no label assigned to location, python's memory manager 'gc'(garbage collector), collects the
memory.
Labeling: Python treats object names as lables. When we assign a new value to a label(variable name), it
allocates space and constructs an object for new value and adds a label to it, but it do not replace the exisitng
value.
In [34]:
1 print(id(x))
10965824
In [35]:
1 y = 30
2 print(id(y))
10965824
Surprise! x and y are pointing same object. Python pools frequently used objects.
Integer pooling:
Typical Python program spends much of its time in allocating and deallocating integers, these operations
should be very fast. Therefore python uses a dedicated allocation scheme with a much lower overhead (in
space and time). Python generally pools integers between -5 to +256, in pre-allocated object list. This is also
applicable for characters(str) afterall ASCII codes are integers.
Note:
In [36]:
1 x = -5
2 y = -5
3 print (id(x), id(y))
4
5 x = 256
6 y = 256
7 print (id(x), id(y))
10964704 10964704
10973056 10973056
In [37]:
1 x = -6
2 y = -6
3 print (id(x), id(y))
4
5 x = 257
6 y = 257
7 print (id(x), id(y))
140183578270576 140183578270640
140183578271024 140183578271120
In [38]:
1 x = 'Apple'
2 y = 'Apple'
3 print (id(x), id(y))
140183577803496 140183577803496
Operators
x + y
In the below expression + is the operator, x and y are operands. Python supports 7 types of operators
Arithmetic Operators
Operator Description
% Modulus Divides left hand operand by right hand operand and returns remainder
// Integer Division or Floor Division - Rounds the quotient towards -ve infinity
In [39]:
1 a, b = 7, 3
In [40]:
1 a + b
Out[40]:
10
In [41]:
1 a / b
Out[41]:
2.3333333333333335
In [42]:
Out[42]:
3.5
In [43]:
Out[43]:
In [44]:
1 7 // 2.0
Out[44]:
3.0
In [45]:
1 7 % 4
Out[45]:
In [46]:
1 4 % 7
Out[46]:
** - Exponential Operator
In [47]:
1 9 ** 2 # square of nine
Out[47]:
81
In [48]:
Out[48]:
3.0
Relational operators
Operator Description
== If the values of two operands are equal, then the condition becomes True.
!= If values of two operands are not equal, then condition becomes True.
> If the value of left operand is greater than the value of right operand, then condition becomes True.
< If the value of left operand is less than the value of right operand, then condition becomes True.
>= If the value of left operand is greater than or equal to the value of right operand, then condition
becomes True.
<= If the value of left operand is less than or equal to the value of right operand, then condition becomes
True.
In [49]:
1 x = 20
2 y = 30
3 x == y
Out[49]:
False
In [50]:
1 x < y
Out[50]:
True
In [51]:
1 x <= y
Out[51]:
True
In [52]:
1 x != y
Out[52]:
True
Logical Operators
Logical operators are used to combine multiple relational expressions into one.
Operator Description
and Logical AND If both the operands are true, then condition becomes true.
or Logical OR If any of the two operands are non-zero, then condition becomes true.
not Logical NOT Used to reverse the logical state of its operand.
In [53]:
1 x = 20
2 y = 30
and: gives True when all relational expressions are True remaining cases it gives False
In [54]:
Out[54]:
False
or: gives False when all relational expressions are False remaining cases it gives True
In [55]:
Out[55]:
False
In [56]:
Out[56]:
True
not: can be applied on any boolean expression, which converts a True to False and False to True
In [57]:
1 not x > 30
Out[57]:
True
In [58]:
Out[58]:
True
Operator Description
+= Add AND It adds right operand to the left operand and assign the result to left operand
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand
⧵*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand
/= Divide AND It divides left operand with the right operand and assign the result to left operand
%= Modulus AND It takes modulus using two operands and assign the result to left operand
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand
//= Floor Division It performs floor division on operators and assign value to the left operand
x = 20
x += 10
'=' is assignment operator. After the execution of above statements, 20 is the value assigned to variable 'x'.
'x' refers to '20', until we assign a new value to x.
'+=' is short hand assignment operator, which adds right side value '10' to 'x', and stores the result back in
'x'. That means, "x += 10' is equivalent to "x = x + 10". So x value becomes '30'.
In [59]:
1 x = 7
2 y = 4
3 x %= y # equivalent to x = x%y
4 print (x)
Bitwise Operators
Bitwise operators are used to manipulate values at bit and byte level.
Operator Description
& Binary AND Operator copies a bit to the result if it exists in both operands
^ Binary XOR It copies the bit if it is set in one operand but not both.
<< Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand.
>> Binary Right The left operands value is moved right by the number of bits specified by the right operand.
Shift
Before starting bitwise operators, we need to undertsand how numbers are represented in various number
systems in python.
Number Prefix
The default number system everybody uses is decimal number system. We can also represent numbers directly
in other number systems in python code.
Left shifting
In [60]:
1 x = 20
2 print (x << 3)
160
In [61]:
1 x
Out[61]:
20
In this example we are shifting bits of 20 (i.e 0b10100) 3 times to the left side, which becomes 0b10100000.
Three 0s are added to the right side.
Note: When x is shifted n times to the left side, its value becoms, x * 2^n
Right Shifting
In [62]:
1 x = 160
2 x >> 3
Out[62]:
20
In [63]:
1 print (x)
160
In this example we are shifting bits of 160 (i.e 0b10100000) 3 times to the right side,which becomes 0b10100.
Three bits are discarded from right side.
Note: When x is shifted n times to the right side, its value becoms, x / 2^n
We can get string representation of a number in any hexadecimal, octal and binary number systems using the
following functions,
bin()
hex()
oct()
In [64]:
Out[64]:
'0b100100101001'
In [65]:
Out[65]:
'0x9c'
In [66]:
Out[66]:
'0o352'
Python can handle huge numbers, as, it is not having any limitation on the number size.
Note: sys.getsizeof() function gives the number of bytes allocated to a value. We have to import sys module to
use this function.
In [67]:
1 import sys
2
3 x = 2**1234567
4 y = 20
5
6 print (sys.getsizeof(x), sys.getsizeof(y))
164636 28
In [68]:
1 x = float("inf")
In [69]:
1 y = float("-inf")
In [70]:
1 2 ** 1234567 < x
Out[70]:
True
In [71]:
1 y < 2 ** 1234567
Out[71]:
True
In [72]:
1 x == x
Out[72]:
True
Do you really thing python stores infinity in memory????? No, actually, it is playing with your mind. It simply
gives you True, when infinity is on the right side of less than symbol!!! same for -ve infinity.
AND (&) results 1 if both the bits are One else zero.
In [73]:
1 x = 0b1010
2 y = 0b1100
3 bin(x & y)
Out[73]:
'0b1000'
Bitwise OR : |
In [74]:
1 x = 0b1010
2 y = 0b1100
3 bin(x | y)
Out[74]:
'0b1110'
Complement : ~
In [75]:
1 x = 1
2 print (~x)
-2
In [76]:
1 x = 15
2 print (~x)
-16
In 16 bits, 1 is represented as 0000 0000 0000 0001. Inverted, we get 1111 1111 1111 1110, which is -2.
Similarly, 15 is 0000 0000 0000 1111. Inverted, you get 1111 1111 1111 0000, which is -16.
EX-OR(^) - results 0, if both are either zeros or ones, results one, if one is zero and other is one.
In [77]:
1 x = 0b1010
2 y = 0b1100
3 bin(x ^ y)
Out[77]:
'0b110'
Membership operators
In [78]:
1 s1 = 'Hello world!'
2 s2 = 'Hell'
3 print (s2 in s1)
4 print ("World" in s1)
5 print ("xyz" not in s1)
True
False
True
In [79]:
True
Identity operators
Identity operators checks the id() equality. Results to True, if both variables are having reference of same object
else False.
is, is not
In [80]:
1 s1 = "Hello"
2 s2 = "Polo"
3 s3 = "Hello"
In [81]:
In [82]:
True
In [83]:
False
In [84]:
1 x = 2.3
2 y = 2.3
3 print (id(x), id(y))
140183578663624 140183578663480
In [85]:
1 x = 2.3
2 y = x
3 print (id(x), id(y))
4 print(x is y)
140183578663672 140183578663672
True
Keywords in Python
Every language has a set of keywords. In python, to know the list of all keywords, just import module 'keyword'
and use the kwlist variable to see all the keywords.
In [86]:
1 import keyword
2 print (keyword.kwlist)
3 # help("keywords")
1 import sys
2 print(sys.version)
Exrecise Programs
1. Write a program to calcualte compound interest when principle, rate and number of periods are given.
2. Write a program to convert given seconds to hours and minutes
3. Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through keyboard and print the details.