Chap 1
Chap 1
Python
Why Python?
◊ Simple and Easy to Learn:
◊ Python is easy to learn, easy to write. It will be like reading or
writing normal English terms
◊ We don’t require any pre-requisite to learn python
◊ Free to use
◊ Python is a Free Open source language, directly we can
download from internet, install it on the system and start
working
◊ High Level Programming language
◊ Platform Independent (Write once and Run Anywhere)
Anand Komiripalem
◊Interpreted language
◊ We don’t need to compile the program, python will directly
compile at the time of execution
◊Dynamically Typed Programming Language
◊ we don’t need to declare any variable in advance in
python, python will automatically assign the type based on
values we provide
◊Supports Web Development
◊ Python supports a variety of ready made frameworks for
developing websites.
Ex: Django, Flax, Pylons, Webwpy
◊ both Object Oriented and Procedure Oriented
programming languages
Anand Komiripalem
◊ Portable language
◊ Most platforms like Windows, Mac etc.. Supports python
Limitations of Python
◊ Speed of python is slow as compared to C/C++ or Java
◊ Python is strong in desktop and server platforms, that is it is an
excellent server-side language but for the mobile development,
Python is not a very good language which means it is a weak
language for mobile development.
◊ comparison to the popular technologies like JDBC and ODBC(open
database connectivity), it is found that the Python’s database
access layer is bit underdeveloped and primitive
Anand Komiripalem
Versions of python
Version Year
Flavors of Python
◊ Cpython: Standrd Python
◊ Jython or Jpython: for implementation of the Python
programming language which is designed to run on the Java
Platform.
◊ Iron Python: implementation of the Python targeting the .NET
Framework. It is entirely written in C# and runs on .NET virtual
machine
◊ PyPy: its primary focus is to overcome drawbacks of python.
◊ Ruby Python: embeds a running Python interpreter in the Ruby
applications.
◊ Anaconda Python: it is distribution for large-scale data
processing, predictive analytics, and scientific computing.
◊ Stackless Python: is a reimplementation of traditional python and
its key point is lightweight threading.
Key Differences Between Java vs Python
Java Python
Code Longer lines of code Less lies of code
Identifiers
1) 123total X
2) total123 √
3) java2share √
4) ca$h X
5) _abc_abc_ √
6) def X
7) If X
Anand Komiripalem
Keywords
◊ Keywords in Python are reserved words that cannot be used as
ordinary identifiers.
Keywords
Note:
◊ All reserved words contains only alphabets
◊ Except “True, False, None” all the keywords contain only lower case
alphabets.
Indentation
◊ Most of the programming languages like C, C++, Java use braces { }
to define a block of code. Python uses indentation.
for i in range(1,11):
print(i)
if i == 5:
break
Anand Komiripalem
Comments in python
◊ Comments can be used to explain Python code.
Data Types
◊ Data type represents the type of data present inside a variable
◊ In python we are not required to specify the type explicitly. Based on
value provided, the type will be assigned automatically. Hence
Python is dynamically Typed Language
Data Types
◊ Python has several inbuilt functions
a=10
b=0o10
c=0X10
d=0B10
print(a) #10
print(b) #8
print(c) #16
print(d) #2
Anand Komiripalem
Base Conversions
◊ We can convert values from one base to another.
◊ We have in-built functions to do the base conversions.
◊ bin() : converts values from any base to binary
x=20
bin(x) #0b10100
Note: We can represent int values in decimal, binary, octal and hexa
decimal forms. But we can represent float values only by using
decimal form.
Anand Komiripalem
Eg: a = 3+5j
b = 5+12.3j
c = 1.2+3.4j
we can specify real part either by decimal, octal, binary or hexa decimal form but
imaginary part should be in decimal format only
Anand Komiripalem
>>> a=10+1.5j
>>> b=20+2.5j
>>> c=a+b
>>> print(c) # (30+4j)
>>> type(c) # <class 'complex'>
Note: Complex data type has some inbuilt attributes to retrieve the real
part and imaginary part
Anand Komiripalem
Note: Complex data type has some inbuilt attributes to retrieve the real
part and imaginary part
c = 10.5+3.6j
c.real 10.5
c.imag 3.6
Anand Komiripalem
Eg:
a = ‘’’anand
komiripalem’’’
b = “”“anand
komiripalem”””
Anand Komiripalem
Type Casting
◊ We can convert one data type value to another, this process of
conversion is called as type casting/ type coersion.
◊ We have inbuilt functions for performing type casting
◊ int()
◊ float()
◊ complex()
◊ bool()
◊ str()
Int():
◊ We can convert values from other data types to int except complex
type
◊ If we want to convert str type to int, then str should contain only
integer values (of base 10)
Anand Komiripalem
Type Casting
Eg:
int(123.45) #123 int(12+34j) # Error
int(True) #1 int(False) #0
int(“10”) #10 int(“12.34”) #error
float():
◊ We can convert values from other data types to float except complex
type
◊ If we want to convert str type to float, then str should contain only
integer of floating values (of base 10)
Eg:
float(123) #123.0 float(12+34j) # Error
float(True) #1.0 float(False) #0.0
float(“10”) #10.0 float(“12.34”) #12.34
Anand Komiripalem
Type Casting
complex():
◊ We can convert values from other data types into complex type
◊ Form-1: (complex(x))
Eg:
complex(13) #13+0j complex (12.34) # 12.34+0j
complex(True) #1+0j complex (False) #0j
complex(“10”) #10+0j complex(“12.34”) #12.34+0j
◊ Form-2: (complex(x,y))
Eg:
complex(5,-3) #5-3j complex(True, False) #1+0j
Anand Komiripalem
Type Casting
bool():
◊ We can convert values from other data types into bool type
Anand Komiripalem
Type Casting
str():
◊ We can convert values from other data types into str type
Eg:
str(“13”) # ’13’ str (“12.34”) # ‘12.34’
str(“True”) # ’True’ str(‘1+5j’) #1+5j
Anand Komiripalem
>>> a=10
>>> b=10
>>> a is b #True
>>> id(a) #1572353952
>>> id(b) #1572353952
Anand Komiripalem
eg:
l= [10, 20, 30]
l.append(‘anand’)
print(l) # [10,20,30,’anand’]
l.remove(20)
print(l) # [10,30,’anand’]
l*2 #[10,30,’anand’ , 10,30,’anand’]
Eg:
s= {10, 20, 30}
s.add(‘anand’)
print(s) # {10,20,30,’anand’}
s.remove(20)
print(s) # {10,30,’anand’}
Default empty set declaration is set()
Anand Komiripalem
Escape characters
◊ escape characters are used for some special purpose in python
◊ The following are various important escape characters in Python
Operators
◊ Operator is a symbol that performs certain operations/tasks
◊ Types of operators:
Arithmetic Operators
Relational Operators or comparison operators
logical operators
bitwise operators
assignment operator
special operator
Anand Komiripalem
Arithmetic Operators
+ --------- Addition
- --------- Subtraction
* --------- Multiplication
/ --------- Division
% --------- Modulo operator
// --------- floor division Operator
** --------- Exponential / power operator
a=10
b=2
print('a+b=',a+b) #a+b=12
print('a-b=',a-b) #a-b=8
print('a*b=',a*b) #a*b=20
print('a/b=',a/b) #a/b=5.0
print('a//b=',a//b) #a//b=5
print('a%b=',a%b) #a%b=0
print('a**b=',a**b) #a**b=100
Anand Komiripalem
Arithmetic Operators
Note:
◊ / operator always performs floating point arithmetic. Hence it will always
returns float value.
◊ But Floor division (//) can perform both floating point and integral
arithmetic. If arguments are int type then result is int type. If at least one
argument is float type then result is float type.
◊ we can use +,* operators for str type also
◊ If we want to use + operator for str type then compulsory both arguments
should be str type only otherwise we will get error.
Relational Operators
Operators: <, <=, >, >=, ==, !=
a=10
b=20
print("a > b is ",a>b) # a>b is False
print("a >= b is ",a>=b) #a>=b is False
print("a < b is ",a<b) #a<b is True
print("a <= b is ",a<=b) #a<=b is True
print(“a==b is”, a==b) #a==b is False
print(“a!=b”, a!=b) #a!=b is True
Anand Komiripalem
Relational Operators
We can apply relational operators for str types also.
a=“anand”
b=“anand”
print("a > b is ",a>b) # a>b is False
print("a >= b is ",a>=b) #a>=b is True
print("a < b is ",a<b) #a<b is False
print("a <= b is ",a<=b) #a<=b is True
print(“a==b is”, a==b) #a==b is True
print(“a!=b”, a!=b) #a!=b is False
10<20 #True
10<20<30 # True
10<20<30<40 #True
10<20<30<40>50 #False
Anand Komiripalem
Logical Operators
Logical operators supported by python: and, or, not
For boolean behavior:
and If both arguments are True then only result is True
or If at least one argument is True then result is True
not Complement
True and False # False
True or False # True
not False #True
For non boolean behavior:
◊ 0 means False , non-zero means True
◊ empty string is always treated as False
Logical Operators
x or y : If x evaluates to True then result is x otherwise result is y
10 or 20 10
0 or 20 20
Bitwise Operators
◊ Bitwise operators available are:
& and
| or
^ xor
~ complement
<< left shift
>> right shift
print(4&5) # Valid
print(10.5 & 5.6) # TypeError:
print(True & True) # Valid
Anand Komiripalem
Bitwise Operators
◊ & if both bits are 1 then result is 1 otherwise result is 0
◊ | if at least one bit is 1 then result is 1 otherwise result is 0
◊ ^ if bits are different then result is 1 otherwise result is 0
◊ ~ complement
◊ << left shift
◊ >> right shift
4 - 100
print(4&5) #4
5- 101
print(4|5) #5
4 - 100 100
5- 101 print(4^5) #1
101 4 - 100
5- 101
001
Anand Komiripalem
Bitwise Operators
◊ ~ complement
print(~4) #-5
print(~100) # -101
print(~111) #-112
print(~True) # -2
◊ In complement we will get (–n-1) value of the given value
print(10<<2) #40
Anand Komiripalem
Bitwise Operators
>> operator: the bits move towards right side
print(10>>2) #2
Assignment Operators
◊ We use assignment operator to assign values to variables
Eg: x=10
Assignment Operators
Eg:
x=10
x+=20
print(x) # 30
Assignment Operators
Eg : Read two numbers from the keyboard and print minimum
value
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
min=a if a<b else b
print("Minimum Value:",min)
Special Operators
◊ Python supports the following special operators
◊ Identity Operator
◊ Membership operator
Identity Operator:
◊ Identity operators are used for address comparison
◊ The available identity operators are:
◊ Is : r1 is r2 returns True if both r1 and r2 are pointing to the same
object.
◊ Is not: r1 is not r2 returns True if both r1 and r2 are not pointing to the
same object.
Anand Komiripalem
Special Operators
Eg: Eg1:
a=10 x=True
b=10 y=True
print(a is b) #True print( x is y) True
-------------------------------------------------------------------------------------------------------------
a=“anand" list1=["one","two","three"]
b=“anand" list2=["one","two","three"]
print(id(a)) #47541440 print(id(list1)) #50038424
print(id(b)) #47541440 print(id(list2)) #45325928
print(a is b) #True print(list1 is list2) # False
print(list1 is not list2) # True
print(list1 == list2) #True
Special Operators
Membership operator:
◊ We can use Membership operators to check whether the given object
present in the given collection. (It may be String, List, Set, Tuple OR Dict)
Eg: Eg2:
x="hello learning Python is very easy!!!"
print('h' in x) #True list1=["sunny","bunny","chinny","pinny"]
print('d' in x) #False print("sunny" in list1) #True
print('d' not in x) #True print("tunny" in list1) #False
print('Python' in x) #True print("tunny" not in list1) #True
Anand Komiripalem
Eg:
import math
print(math.sqrt(16)) #4.0
print(math.pi) #3.141592653589793
Anand Komiripalem
Eg:
from math import sqrt,pi
print(sqrt(16)) #4.0
print(pi) # 3.141592653589793
Print(math.pi) #Error: now it wont recognise math module
Anand Komiripalem
◊ input() : input() function can be used to read data directly in our required
format.We are not required to perform type casting.
◊ Note: Above two are supported in Python 2 only
◊ But in Python 3 we have only input() method and raw_input() method is not
available
◊ raw_input() function of Python 2 is renamed as input() function in Python 3
-----------------------------------------------------------
Output:
x=int(input("Enter First Number:")) --------------
y=int(input("Enter Second Number:")) Enter First Number: 40
print("The Sum:",x+y) Enter Second Number: 50
The sum: 90
--------------------------------------------------
print("The Sum:",int(input("Enter First Number:"))+int(input("Enter Second
Number:")))
Anand Komiripalem
eval() can evaluate the Input to list, tuple, set, etc based the Input.
◊ Create and save the program and try to run it from command prompt.
◊ At the time of displaying we can remove the file name by using slice
operator
from sys import argv
print(type(argv))
print(argv)
print(argv[1:])
print(len(argv))
Anand Komiripalem
name = “anand"
salary = 10000
print("Hello {} your salary is {} ". format(name, salary))
print("Hello {x} your salary is {y} ". format(x=name, y=salary))
Output
Hello anand your salary is 10000
Hello anand your salary is 10000
Thank Q