Chapter 1 Introduction
Chapter 1 Introduction
Python Programming
Punit A. Lathiya
Assistant Professor
EC Department
GEC Rajkot
Syllabus : 3151108
Syllabus : 3151108
Teaching and Examination Scheme
Books
Online Courses
• https://www.coursera.org/learn/python-programming
• https://nptel.ac.in/courses/106/106/106106145/
• https://nptel.ac.in/courses/106/106/106106182/
Index
• Old Stuff you must remember…..
• Introduction
• History
• Scope
• Software Installation
• Sample Code
You Should Know, Old Stuff
Language Type
• Higher Level Language
▫ Machine Independent
▫ C, C++, C#, Java, HTML, COBOL, Python
▫ Need Compiler/Interpreter
• Lower Level Language
▫ Machine Dependent
▫ Assembly
Instruction Based (Ex. : MOV R0, R1)
Dedicated to microprocessor and microcontroller
Needs Assembler
▫ Machine Level(Binary codes)
Different for all processor and controller
Can’t understand or write directlly
Aim : To convert Program into Machine
Create binary/executable files which execute from Doesn’t create binary/executable files, no
system memory memory allocated
C, C++, C#, Java, COBOL, Pascal etc Javascript, VBScript, Perl, Python, Ruby etc
https://www.educba.com/programming-vs-scripting/
History of Python
• Invented by Guido Van Rossum from Netherlands in
early 90’s.
• Guido Van Rossum is fan of “Monty Python’s flying circus”,
a famous TV shows in Netherlands.
• Language is named after Monty Python
• Its implementation was started in December 1989
• Open source from beginning. (No license required)
• Python 1.0 was released to public in 1994,
• Python 2.0 in 2000 and
• Python 3.0 in 2008
Why people use python?
• Python is Object-Oriented
▫ Language support class-object, polymorphism, operation
overloading, inheritance
• Indentation is must
• It’s free (Open Source)
▫ Downloading and installation is free
• It’s powerful
▫ Dynamic typing
▫ Built-in types and tools
▫ Library utility
▫ Third party utility (i.e. numpy, numeric, scipy )
▫ Automatic memory management
Concept of Indentation
for(i=0;i<30;i++) for i in range(30):
{ a=a+i
a = a + i; print(a)
printf(“%d”,a);
if(a>20)
if(a>20):
printf(“A is greater); print(“A is greater);
else else:
printf(“A is lesser”); print(“A is lessor”);
}
printf(“%d”,a); print(a)
▫ x=2
▫ x+10 ➔ 12 (x doesn’t change)
▫ y= 4
▫ x= x+y ➔ 6 (x changes here, x=6)
▫ x+y ➔ 10 (x doesn’t change)
▫ Use of Underscore to access previous answer
▫ _ +y ➔ 14 (value of underscore = 10)
String p y t h o n 1
Basics PositiveIndex 0 1 2 3 4 5 6
NegativeIndex -7 -6 -5 -4 -3 -2 -1
• Variable for str:
▫ Name =‘python1’
▫ Access string using index
Name[0], Name[10], Name[0:2], Name[1:], Name[:4] , Name[2:5], Name[2:10]
Name[-1] , Name[-5:-2], Name[-5:], Name[-5:-7]
▫ String in python is immutable (Not changeable)
Name[0:2]=‘my’ ➔ Error
▫ Merge String with + :
Name + ‘video’ ➔ ‘python1 video’
‘My’ + name[3:] ➔ ‘Myhon1’
Name ‘video’ ➔ Syntax error
▫ Duplicating String with * :
5* “GECR ” ➔ “GECR GECR GECR GECR GECR”
▫ Len(name) ➔ 7
Operators
Arithmetic
Operator + , - , / , * , ** , // , % , ()
Assignment
Operator
=, += , -= , *= , /= , (a,b=5,6)
Bitwise
Operator
~, & , | , ^, << , >>
Relational
Operator < , > , == , != , <= ,>=
Results
Logical in
Operator
and, or, not
Boolean
Unary
Operator
n=-n
Operators
Membership
Operator
in , not in
Identity
Operator
is , is not
Bitwise Operator
A= 2 (0000 0010)
B = A<<1 (0000 0100) = 4 << : Multiplication by 2
>> : Division by 2
C = 16 (0001 0000)
D = C>>1 (0000 1000) = 8
D = 15 (0000 1111)
E =5 (0000 0101)
F = D^E (0000 1010) = 10
Relational Operator
(5>3) => True A = 10
A = (5>3) => A = True B=3
C=5
A = (5>4) and (10<3) if((A>B) or (B>C)):
print(“Hello”);
= True and False
else:
= False print(“GECR”);
Result : Hello
Operator Precedence and Associativity
• Precedence :
▫ It defines order in which complex expression can be evaluated.
▫ Ex : a = (2+3*7)/6 + sin(2*3.14*(f+100))
• Associativity:
▫ For any expression, when more than one operator exist from same
group, then associativity helps to determine order of evaluation.
▫ Mostly of Two type :
Left-to-Right
Right-to-Left
▫ Ex : a = 3 * 5 * 4/6 * 2
▫ Ex : b = (a > 3) and (a<10) or (a<=threshold)
Operator Precedence and Associativity
Operator Description Precedence Associativity
() Parentheses Highest left-to-right
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< , <= , > , >= Relational : less than , less than or equal to, greater than, greater than or equal to left-to-right
== != Relational is equal to/is not equal to left-to-right
is, is not Identity
left-to-right
in, not in Membership operators
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
not Logical NOT right-to-left
and Logical AND left-to-right
Or Logical OR left-to-right
= Assignment
+= , -= , *= , /= , %= Addition/Subtraction/ Multiplication/Division/Modulus assignment Lowest right-to-left
&= , ^= , |= , <<= , >>= bitwise AND / bitwise XOR / bitwise OR / Bitwise shift left/right assignment
Operator Precedence (Example)
# Code-1
meal = "fruit"
Result : Lunch being delivered
money = 0
if (meal == "fruit" or meal == "sandwich" and money >= 2): Logical AND has high precedence
delivered") so it evaluated first.
print("Lunch being delivered")
else: Wrong Answer
print("Can't deliver lunch")
# Code-2
meal = "fruit" Result : Can’t deliver lunch
money = 0
if ((meal == "fruit" or meal == "sandwich“) and money >= 2): Parenthesis has high precedence
print("Lunch being delivered") so it evaluated first.
else: Correct Answer
print("Can't deliver lunch")
Sequence
Use type( ) function to
check datatype of list supported
variable/value
Tuple
Set
Ex: type(a) , type(3.56) Set
type(mystr) Frozenset
Range
byte
Map(Dictionary)
bytearray
Byte
memoryview
Numeric
• Integer
▫ 32-bit
▫ -231 to 231-1
• Floating point
• Complex
▫ C = complex(5,7)
▫ type(C)
• Boolean
▫ x = True
▫ y = False
To store multiple items…
• Methods to store multiple items in single
variables...
▫ String
▫ List
▫ Tuple
▫ Set
▫ Dictionary
▫ Range
▫ Bytes
String p y t h o n 1
String PositiveIndex 0 1 2 3 4 5 6
Reference : https://www.w3schools.com/python/python_ref_string.asp
String Methods (Built-in Methods)
Method Description
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Reference : https://www.w3schools.com/python/python_ref_string.asp
String
String
List
• List values are ordered, changeable and allow duplicate values
• List are created using square bracket [ ]
▫ Ex: a = [10, 34, 5, 23]
▫ Ex: mst = [“GECR”, “HJK”, “5thEC”]
▫ Ex: b = [ 10, “Hello”, 4.556, ‘JAVA’, True]
• Indexed with 0,1,2,….
• Use constructor to make list
▫ Mylist = list((“Hello”, 45 , 5.77))
• List value is mutable (changeable)
▫ Ex: a[2] = 45
List
List Methods (Built-in Functions)
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Reference : https://www.w3schools.com/python/python_lists_methods.asp
List Methods
• A is list of value, apply following methods
• A.append(value)
• A.insert(index, value)
• A.remove(value)
List Methods
• A is list of value, apply following methods
• A.pop(index)
• A.sort( )
• len(A)
List Methods
• A is list of value, apply following methods
• del(A[2])
• del(A[1:2])
• A.extend([3,4])
List Methods
• Inbuild function like
▫ min,max,sum,etc
Tuple
• Tuple is collection which is ordered and unchangeable.
• Written with or without round bracket ( ).
▫ Ex : tup1 = (“GECR”, “Hello”, “5thEC”)
▫ Ex : tup2 = (90 , 4, 30, 2)
▫ Ex : tup3 = 2,3,4
• Feature :
▫ Ordered, Unchangeable, Allow duplicate entry
Tuple
Tuple
• One item tuple, Comma is necessary
Reference : https://www.w3schools.com/python/python_ref_tuple.asp
Tuple Functions
• Tp1 is tuple, apply following methods…
Ex: Tp1 = (23, 45, 65, 45, 44, 45)
• Tp1.count(value)
• Tp1.index(value)
• len(Tp1)
set
• Collection of unique elements
• Written with curly bracket { }.
▫ Ex : s1 = {“GECR”, “Hello”, “5thEC”}
▫ Ex : s2 = {90 , 4, 30, 2}
▫ Ex : s3 = {90 , 4 , 90 , 2} ➔ {2, 4, 90}
• Feature :
▫ Unordered (No sequence), No index, Changeable,
▫ No duplicate members
▫ New Item can be added in set
Set Methods (In-built Functions)
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
Removes the items in this set that are also included in another, specified
difference_update()
set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two or more sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
Reference : https://www.w3schools.com/python/python_ref_set.asp
Set Methods (In-built Functions)
Method Description
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_u
inserts the symmetric differences from this set and another
pdate()
union() Return a set containing the union of sets
update() Update the set with another set, or any other iterable
Reference : https://www.w3schools.com/python/python_ref_set.asp
Set methods
• S1 is set, apply following methods
• S1.add(value)
• S1.discard(value)
• S1.clear( )
• S1.remove( )
• S1.add( )
• S1.difference( )
• Etc…..
Frozenset
• Frozenset is similar to set except it is immutable
• Elements cannot be added or removed once created.
• Also Known as read-only set.
• Example :
▫ Ex : s1 = frozenset({“GECR”, “Hello”, “5thEC”})
• Feature :
▫ Unordered (No sequence), No index, Unchangeable,
▫ No duplicate members
▫ New Item can’t be added in set
▫ Doesn’t support add( ) , remove( ), discard( ) methods.
Dictionary (Associative Array)
• Dictionaries are used to store data values in key:value
pairs.
• Every value have key
• Values can be any data types
• Ex:
▫ Dic = {1: ‘Punit’ , 2: ‘GECR’, 3: ‘5thEC’}
▫ car = { ‘Model’ : ‘Hyndai i10’,
‘Color’ : ‘White’
‘Year’ : 2019}
• Feature:
▫ UnOrdered, Changeable, No Duplicate
Dictionary
Dic = {1: ‘Punit’ , 2: ‘GECR’, 3: ‘5thEC’}
car = { ‘Model’ : ‘Hyndai i10’,
‘Color’ : ‘White’ ,
‘Year’ : 2019}
print(car)
print(car[‘Model’])
Print(type(car))
+
Dictionary
• Create Dictionary using zip of keys and values
• Ex:
▫ Keys = [‘name’, ‘enrollment’, ‘branch’]
▫ Values = [‘Rajat’, ‘190200111007’ , ‘5thEC’]
▫ Dic = dict(zip(Keys, Values))
Dictionary
• Adding items to dictionary
▫ car = { ‘Model’ : ‘Hyndai i10’,
‘Color’ : ‘White’,
‘Year’ : 2019}
▫ car[‘Engine’] = ‘Petrol 4 stroke’
▫ Print(car)
Dictionary Methods (In-built Functions)
Method Description
clear() Removes all the elements from the dictionary
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
Reference : https://www.w3schools.com/python/python_ref_dictionary.asp
Dictionary Methods
Difference
Property List Tuple Set FronzenSet Dictionary
Ordered Yes Yes No No No
(allow indexing)
Duplicate Yes Yes No No No
value Allowed
Mutable Yes No Yes No Yes
(changeable)
Methods 11 2 17 17-3 = 14 11
available
Brackets [] () {} {} {key:value}
Range
• range(10)
• L = range(10)
• L = list(range(10))
• L = list(range(0,10,2))
• L = list(range(-10,-1,2))
Operators
Membership
Operator
in , not in
• In : Returns True if a sequence with specified value is present in the object.
• Not in : Returns True if a sequence with specified value is not present.
Operators
Identity
Operator
is , is not
• is : Returns True if both variables are same object with same memory location.
• is not : Returns True if both variables are not same object with different
memory location.
Memory location can be found
using id(var)
a = 30
b = 20 Output:
print(id(a)) 1864289420432
Print(id(b)) 1864289420752
Number system
• Convert number into octal, hexadecimal and binary..
▫ Ex: A = 100
▫ bin(A) ➔ 2’b01100100
▫ oct(A) ➔ O144
▫ hex(A) ➔ 0x64
• Result is available as string
Math Functions
• import math
• X = math.sqrt(64) ➔ 8.0
• PI = math.pi ➔ 3.141592653589793
• Y = math.sin(PI/3) ➔ 0.866025403784438
• math.floor(9.333) ➔ 9.0
• math.ceil(9.333) ➔ 10.0
• math.pow(2,10) ➔ 1024.0
Thank You