Chapter 1
Chapter 1
Python Programming
by Narendra Allam
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
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Bitwise operators
Membership operators
Identity operators
Ternary Operator
Built-in functions
Type conversions
int()
float()
bool()
str()
complex()
Interview questions
Exercise Programs
Summary
Introduction
file:///Users/Python/Chapter1.html Page 1 of 31
Chapter 1 22/10/17, 12(31 AM
Introduction
There are 5000+ programming langauges in the world and we are still counting... Python is in the top 5
programming langauges as of 2017. 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.
Automation:
Anything that can speed up the development process and reduce manual effort.
Writing as little code as possible and hiring as little programmers as possible.
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.
Python features
High-level programming languages are close to business problems. . Whereas low-level programming
languages are close to system's problems..
file:///Users/Python/Chapter1.html Page 2 of 31
Chapter 1 22/10/17, 12(31 AM
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.
We do not choose high-level programming languages to solve system problems. Even though,
development time is more, low-level languages give real-time performance.
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. 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 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.
5. Extensible
High-level languages are not performant, because they are more focused to provide developer friendly
environment than optimizing for speed.
file:///Users/Python/Chapter1.html Page 3 of 31
Chapter 1 22/10/17, 12(31 AM
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 2.7 www.continuum.io (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, you need to install required packages seperately.
Just double click on the installer and follow the wizard to complete the installation.
Note: On windows, installer asks to 'add the python path to PATH environment variable'. Please check
the box.
Open cmd(command prompt) on Windows or terminal(shell) for Linux and Mac Users.
file:///Users/Python/Chapter1.html Page 4 of 31
Chapter 1 22/10/17, 12(31 AM
type 'python' command and hit enter, you should see the below screen.
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.
file:///Users/Python/Chapter1.html Page 5 of 31
Chapter 1 22/10/17, 12(31 AM
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, '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.
file:///Users/Python/Chapter1.html Page 6 of 31
Chapter 1 22/10/17, 12(31 AM
Output: 357
Output: 6789.0
In[] 1450 / 60 / 3
Output: 8
Why, result is 8?
Order of evalutation matters? Ofcourse, yes. We are supposed to calculate 60/3 first then the result 20,
devides 1450. By default order of evalution is left to right for most of the operators, except assignment
operators, it is right to left.
file:///Users/Python/Chapter1.html Page 7 of 31
Chapter 1 22/10/17, 12(31 AM
Output: 72
Output: 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.
Output: 73.0
There are so many functions in math module, we will discuss in detail in modules topic.
Output: 6.0
In[] (6*(6-3)*(6-4)*(6-5))**0.5
Output: 6.0
Using variables
If we define variables, we do not need to change entire expression, instead change the values assigned
to variables.
file:///Users/Python/Chapter1.html Page 8 of 31
Chapter 1 22/10/17, 12(31 AM
In[] a = 3
b = 4
c = 5
s = (a + b + c)/ 2.0
area: 6.0
int
float
str
bool
complex
Dynamically typed
In python variables change their data types dynamically.
x = 20
In[] type(x)
------------------------------------------------------------------
---------
NameError Traceback (most recent c
all last)
<ipython-input-10-c6ec0f91e335> in <module>()
----> 1 type(x)
In[] x = 3.5
file:///Users/Python/Chapter1.html Page 9 of 31
Chapter 1 22/10/17, 12(31 AM
In[] type(x)
Output: float
In[] x = 'Apple'
In[] type(x)
Output: str
In[] x = True
In[] type(x)
Output: bool
In[] x = 2 + 3j
In[] type(x)
Output: complex
'x' can change its type dynamically, because of python memory model and labeling system.
In[] a = 2
b = 4
c = 5
s = a + b + c
avg = s / 3.0
average = 3.66666666667
file:///Users/Python/Chapter1.html Page 10 of 31
Chapter 1 22/10/17, 12(31 AM
raw_input() is the function which is used to read the values from the keyboard. Prompt string is
optional
syntax:
Enter value: 20
Enter value: 30
In[] print x
20
Note: 'print' is the statment used to print values on console but shell is used, 'print' statment is not
required, we can directly get the ouput by typing the variable name. When running as a script 'print' is
mandatory
In[] print y
30
Note:
in python 2.x raw_input() - reads input from the console
in python 3.x it is input(), we dont have raw_input() in python 3.x
In[] x + y
Output: '2030'
Note: By default 'raw_input()' function reads values as strings.We should explicitely convert them to the
target type.
file:///Users/Python/Chapter1.html Page 11 of 31
Chapter 1 22/10/17, 12(31 AM
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()
Enter X Value: 20
Enter y Value: 30
Sum = 50
In[] x = raw_input()
type(x)
Output: str
print statement
syntax:
file:///Users/Python/Chapter1.html Page 12 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x = 4
y = 5
z = x + y
print '{} plus {} is {}'.format(x, y, z)
4 plus 5 is 9
'{}' is the place holder for a value we can add any text in between as above
or
4 plus 5 is 9
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
file:///Users/Python/Chapter1.html Page 13 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x = 20
140245518555440
file:///Users/Python/Chapter1.html Page 14 of 31
Chapter 1 22/10/17, 12(31 AM
In[] 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 lebel assigned to location, python's memory manger '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.
140245518555200
In[] y = 30
print id(y)
140245518555200
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:
file:///Users/Python/Chapter1.html Page 15 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x = -5
y = -5
print id(x), id(y)
x = 256
y = 256
print id(x), id(y)
140245518556040 140245518556040
140245518561632 140245518561632
In[] x = -6
y = -6
print id(x), id(y)
x = 257
y = 257
print id(x), id(y)
140245521341632 140245521339256
140245521276440 140245521341144
In[] x = 'Apple'
y = 'Apple'
print id(x), id(y)
4472141504 4472141504
Operators
file:///Users/Python/Chapter1.html Page 16 of 31
Chapter 1 22/10/17, 12(31 AM
x + y
In the below expression + is the operator, x and y are operands. Python supports 7 types of operators,
Arithmetic
Relational
Logical
Assignment
Bitwise
Membership
Identity
Arithmetic
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[] a = 7
b = 3
In[] a + b
Output: 10
In[] a - b
Output: 4
file:///Users/Python/Chapter1.html Page 17 of 31
Chapter 1 22/10/17, 12(31 AM
In[] a * b
Output: 21
In[] a / b
Output: 2
In[] 7 / 2
Output: 3
In[] 7 / 2.0
Output: 3.5
Note: There must be atleast one real number to get real number in any python expression.
In[] 7 // 2
Output: 3
In[] 7 // 2.0
Output: 3.0
In[] 7 // 2
Output: 3
In[] 7 // 2.0
Output: 3.0
In[] 7 % 4
Output: 3
In[] 4 % 7
Output: 4
file:///Users/Python/Chapter1.html Page 18 of 31
Chapter 1 22/10/17, 12(31 AM
** - Exponential Operator
In[] 9 ** 2
Output: 81
In[] 9 ** 0.5
Output: 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[] x = 20
y = 30
print x == y
False
In[] x < y
Output: True
file:///Users/Python/Chapter1.html Page 19 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x <= y
Output: True
In[] x > y
Output: False
In[] x >= y
Output: False
In[] x != y
Output: True
In[] x <> y
Output: 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.
Lets take
x = 20
y = 30
In[] x = 20
y = 30
and: gives True when all relational expressions are True remaining cases it gives False
file:///Users/Python/Chapter1.html Page 20 of 31
Chapter 1 22/10/17, 12(31 AM
Output: False
or: gives False when all relational expressions are False remaining cases it gives True
Output: False
Output: True
not: can be applied on any boolean expression, which converts a True to False and False to True
Output: True
Output: True
file:///Users/Python/Chapter1.html Page 21 of 31
Chapter 1 22/10/17, 12(31 AM
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 It takes modulus using two operands and assign the result to left operand
AND
**= Exponent Performs exponential (power) calculation on operators and assign value to the left
AND operand
//= Floor Division It performs floor division on operators and assign value to the left operand
x = 20
in the bove statment, 20 is the value assigned to variable 'x'. 'x' refers to '20', untill we assign a new
value.
x = 20
x += 10
After the execution of above two statments, x value becomes '30'. '+=' 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".
file:///Users/Python/Chapter1.html Page 22 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x = 7
y = 4
x %= y # x = x%y
print x
another one,
In[] x = 7
y = 4
x //= y # x = x // y
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
Shift right operand.
Before starting bitwise operators, we need to undertsand how numbers are represented in various
number systems in python.
Number Prefix
file:///Users/Python/Chapter1.html Page 23 of 31
Chapter 1 22/10/17, 12(31 AM
The dfault number system everybody uses is decimal number system. We can also represent numbers
directly in other number systems in python code.
In[] x = 0b10100
print x
20
In[] x = 0o4526
print x
2390
In[] x = 0xAB2F
print x
43823
Left shifting
In[] x = 20
x << 3
Output: 160
In[] x
Output: 20
In the above 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
file:///Users/Python/Chapter1.html Page 24 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x = 160
x >> 3
Output: 20
In[] print x
160
In the above 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 reprenation of a number in any hexadecimal, octal and binary number systems using
the fllowing functions,
bin()
hex()
oct()
Output: '0b100100101001'
Output: '0x9c'
Output: '0352'
file:///Users/Python/Chapter1.html Page 25 of 31
Chapter 1 22/10/17, 12(31 AM
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.
x = 2**1234567
y = 20
164636 24
In[] x = float("inf")
In[] y = float("-inf")
Output: True
Output: True
file:///Users/Python/Chapter1.html Page 26 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x == x
Output: True
Do you really thing python stores infinity in memory????? Nohh, 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[] x = 0b1010
y = 0b1100
bin(x & y)
Output: '0b1000'
Bitwise OR : |
In[] x = 0b1010
y = 0b1100
bin(x | y)
Output: '0b1110'
Complement : ~
In[] x = 1
print ~x
-2
In[] x = 15
print ~x
-16
file:///Users/Python/Chapter1.html Page 27 of 31
Chapter 1 22/10/17, 12(31 AM
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[] x = 0b1010
y = 0b1100
bin(x ^ y)
Output: '0b110'
Membership operators
in , not in
s2 in s1
Output: True
Output: True
In[] "World" in s1
Output: False
file:///Users/Python/Chapter1.html Page 28 of 31
Chapter 1 22/10/17, 12(31 AM
In[] "xyz" in s1
Output: False
Output: True
Identity operators
Identity operators checks the id() equality. Results to True, if both varibles are having reference of same
object else False.
is, is not
In[] s1 = "Hello"
s2 = "Polo"
s3 = "Hello"
In[] print s1 is s3
True
In[] print s1 is s2
False
True
In[] x = 25
y = 25
print id(x), id(y)
140245518555320 140245518555320
In[] x is y
Output: True
file:///Users/Python/Chapter1.html Page 29 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x = 2.3
y = 2.3
print id(x), id(y)
140245518173280 140245518173184
In[] x is y
Output: False
In[] c1 = 2 + 3j
In[] c2 = 2 + 3j
4471943600 4471943856
In[] c1 is c2
Output: False
In[] c1 == c2
Output: 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.
Interview Questions
Output ?
file:///Users/Python/Chapter1.html Page 30 of 31
Chapter 1 22/10/17, 12(31 AM
In[] x = 25
y = 25
print id(x) == id(y)
True
Enter value: 20
Enter value: 30
2030
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 gven 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.
Notes
file:///Users/Python/Chapter1.html Page 31 of 31