Lecture1 - Py-1 (1) (8 Files Merged)
Lecture1 - Py-1 (1) (8 Files Merged)
ge ge
Python is simple & easy
lle lle
Co Co
Free & Open Source
Translator
na na
(Compiler / Interpreter) High Level Language
Ap Ap
Developed by Guido van Rossum
Machine Code
Portable
lege
Our First Program Python Character Set
Col
na ge
Ap
Letters – A to Z, a to z
lle
print("Hello World")
Co
Digits – 0 to 9
a
Special Symbols - + - * / etc.
Apn
Whitespaces – Blank Space, tab, carriage return, newline, formfeed
Other characters – Python can process all ASCII and Unicode characters as part of data or literals
Variables Memory
ege ege
A variable is a name given to a memory location in a program.
C oll Coll
na na
name = "Shradha"
Ap Ap
age = 23
price = 25.99
name = "Shradha"
age = 23
price = 25.99
Rules for Identifiers Data Types
ege lege
Integers
oll Col
aC
String
n na
Ap
Float
Ap
Boolean
None
ge
Keywords are reserved words in python.
lle
ege a Co
*False should be uppercase
oll Apn
pnaC
A
llege
# Single Line Comment
lege a C o
Col Apn
"""
na
Multi Line
Ap
Comment
"""
Types of Operators Type Conversion
ge ge
An operator is a symbol that performs a certain operation between operands.
lle lle
Co Co
a, b = 1, 2.0
Arithmetic Operators ( + , - , * , / , % , ** )
a a
sum = a + b
Apn Apn
Relational / Comparison Operators ( == , != , > , < , >= , <= )
#error
Assignment Operators ( = , +=, -= , *= , /= , %= , **= ) a, b = 1, "2"
sum = a + b
Type Casting
ge
Type Casting
lle lege
na Co a Col
a, b = 1, "2"
Ap Apn
c = int(b)
sum = a + c
llege
Input in Python Let‘s Practice
aCo
ege
Write a Program to input 2 numbers & print their sum.
pn
input( ) statement is used to accept values (using keyboard) from user
C oll A
na
Ap
input( ) #result for input( ) is always a str
Apn Apn
Let‘s Practice
llege Strings
llege
a Co a Co
WAP to input 2 int numbers, a and b.
Apn
String is data type that stores a sequence of characters.
Apn
Print True if a is greater than or equal to b. If not print False.
Basic Operations
concatenation
length of str
len(str)
Indexing Slicing
Accessing parts of a string
Apna_College
ge
str[ starting_idx : ending_idx ] #ending idx is not included
le
0 1 2 3 4 5 6 7 8 9 10 11
Col ege
l
str = “ApnaCollege”
a l
Apn Co
str = “Apna_College” str[ 1 : 4 ] is “pna”
na
Ap
str[0] is ‘A’, str[1] is ‘p’ ... str[ : 4 ] is same as str[ 0 : 4]
ge ge
Apple
l le l le
str.endsWith(“er.“) #returns true if string ends with substr
Co Co
-5 -4 -3 -2 -1
na na
str.capitalize( ) #capitalizes 1st char
Ap Ap
str = “Apple”
str.replace( old, new ) #replaces all occurrences of old with new
str[ -3 : -1 ] is “pl”
str.find( word ) #returns 1st index of 1st occurrence
l lege l lege
if(condition) :
Co Co
Statement1
a a
Apn n
elif(condition):
Ap
WAP to find the occurrence of ‘$’ in a String.
Statement2
else:
StatementN
lege lege
marks >= 90, grade = “A”
Col
90 > marks >= 80, grade = “B”
Col
a a
WAP to find the greatest of 3 numbers entered by the user.
Apn
80 > marks >= 70, grade = “C”
ge ge
It can store elements of different types (integer, float, string, etc.)
le le
list_name[ starting_idx : ending_idx ] #ending idx is not included
Col Col
a a
marks = [87, 64, 33, 95, 76] #marks[0], marks[1].. marks = [87, 64, 33, 95, 76]
Apn Apn
marks[ 1 : 4 ] is [64, 33, 95]
student = [”Karan”, 85, “Delhi”] #student[0], student[1]..
marks[ : 4 ] is same as marks[ 0 : 4]
student[0] = “Arjun” #allowed in python marks[ 1 : ] is same as marks[ 1 : len(marks) ]
l lege l lege
list.append(4) #adds one element at the end [2, 1, 3, 4] list.remove(1) #removes first occurrence of element [2, 3, 1]
a Co a Co
Apn Apn
list.sort( ) #sorts in ascending order [1, 2, 3] list.pop( idx ) #removes element at idx
l lege l lege
tup.index( el ) #returns index of first occurrence tup.index(1) is 1
o o
tup = (87, 64, 33, 95, 76) #tup[0], tup[1]..
na C na C
tup.count( el ) #counts total occurrences tup.count(1) is 2
Ap Ap
tup[0] = 43 #NOT allowed in python
tup1 = ( )
tup2 = ( 1, )
tup3 = ( 1, 2, 3 )
Let‘s Practice Let‘s Practice
WAP to ask the user to enter names of their 3 favorite movies & store them in a list. WAP to count the number of students with the “A” grade in the following tuple.
ge ge
[”C”, “D”, “A”, “A”, “B”, “B”, “A”]
l le l le
na Co na Co
Ap Ap
WAP to check if a list contains a palindrome of elements. (Hint: use copy( ) method) Store the above values in a list & sort them from “A” to “D”.
lege lege
They are unordered, mutable(changeable) & don’t allow duplicate keys
Col Col
na na
Ap Ap
“key” : value
ge ge
myDict.keys( ) #returns all keys
e e
Each element in the set must be unique & immutable.
Coll Coll
myDict.values( ) #returns all values
a a
Apn Apn
nums = { 1, 2, 3, 4 }
myDict.items( ) #returns all (key, val) pairs as tuples
set2 = { 1, 2, 2, 2 }
myDict.get( “key““ ) #returns the key according to value #repeated elements stored only once, so it resolved to {1, 2}
ege ege
set.add( el ) #adds an element set.union( set2 ) #combines both set values & returns new
oll oll
set.intersection( set2 ) #combines common values & returns new
C C
set.remove( el ) #removes the elem an
na na
Ap Ap
set.clear( ) #empties the set
ge ge
an empty dictionary & add one by one. Use subject name as key & marks as value.
e e
table : “a piece of furniture”, “list of facts & figures”
Coll Coll
cat : “a small animal”
na na
Ap Ap
You are given a list of subjects for students. Assume one classroom is required for 1 Figure out a way to store 9 & 9.0 as separate values in the set.
subject. How many classrooms are needed by all students. (You can take help of built-in data types)
ege ege
Print numbers from 1 to 100.
l l
Loops are used to repeat instructions.
Col Col
Print numbers from 100 to 1.
a a
while Loops
Apn Apn
while condition :
Print the multiplication table of a number n.
#some work
print hello 5 times Search for a number x in this tuple using loop:
print numbers from 1 to 5
ege ege
Break : used to terminate the loop when encountered.
l l
Loops are used used for sequential traversal. For traversing list, string, tuples etc.
Col Col
a a
Continue : terminates execution in the current iteration & continues execution of the loop for Loops
Apn Apn
with the next iteration.
for el in list:
#some work
for el in list:
#some work
take search example
& stop the search when found else:
else used as it doesn’t execute
print all numbers but not multiple of 3
#work when loop ends when break is used
ege ege
using for
l l
Range functions returns a sequence of numbers, starting from 0 by default, and increments by
ol Col
1 (by default), and stops before a specified number.
aC
Print the elements of the following list using a loop:
pn na
Ap
[1, 4, 9, 16, 25, 36, 49, 64, 81,100] range( start?, stop, step?)
A
Search for a number x in this tuple using loop:
ege ege
using for & range( )
l l
pass is a null statement that does nothing. It is used as a placeholder for future code.
Col Col
Print numbers from 1 to 100.
a a
Apn Apn
for el in range(10):
Print numbers from 100 to 1.
pass
ege ege
WAP to find the sum of first n numbers. (using while)
l l
Block of statements that perform a specific task.
Col Col
na na
Ap Ap
def func_name( param1, param2..) : Function Definition
#some work
WAP to find the factorial of first n numbers. (using for)
return val
lege lege
Assigning a default value to parameter, which is used when no argument is passed.
ol Col
aC
Built-in Functions User defined Functions
pn na
Ap
print( )
A
len( )
type( )
range( )
ge
Let‘s Practice Recursion
ge lle
le Co
When a function calls itself repeatedly.
l
WAF to print the length of a list. ( list is the parameter)
a Co Apna
#prints n to 1 backwards
Apn
WAF to print the elements of a list in a single line. ( list is the parameter) Base case
ge llege
#returns n! Write a recursive function to calculate the sum of first n natural numbers.
lle C o
na Co Apna
Ap
Write a recursive function to print all elements in a list.
Hint : use list & index as parameters.
lege lege
Python can be used to perform operations on a file. (read & write data) We have to open a file before reading or writing.
Col Col
a a
f = open( “file_name”, “mode”)
Apn Apn
Types of all files
data = f.read( )
f.close( )
Reading a file
llege
Co
data = f.read( ) #reads entire file
na
Ap
data = f.readline( ) #reads one line at a time
ollege
na C
Ap
Writing to a file with Syntax
ge ege
olle oll
f = open( “demo.txt”, “w”) with open( “demo.txt”, “a”) as f:
a C a C
data = f.read( )
n n
f.write( “this is a new line“ ) #overwrites the entire file
Ap
f = open( “demo.txt”, “a”)
Ap
f.write( “this is a new line“ ) #adds to the file
ege ege
using the os module
l l
Create a new file “practice.txt” using python. Add the following data in it:
ol Col
aC
Module (like a code library) is a file written by another programmer that generally has
a
Hi everyone
a functions we can use.
pn Apn
we are learning File I/O
A
using Java.
import os
I like programming in Java.
os.remove( filename )
WAF that replace all occurrences of “java” with “python” in above file.
lege lege
To map with real world scenarios, we started using objects in code.
l l
WAF to find in which line of the file does the word “learning”occur first.
Co Co
Print -1 if word not found. This is called object oriented programming.
a a
Apn
From a file containing numbers separated by comma, print the count of even numbers.
Apn
Class & Object in Python Class & Instance Attributes
lege lege
Class is a blueprint for creating objects.
C ol Col
Class.attr
a a
#creating class
Apn n
obj.attr
Ap
class Student:
name = “karan kumar”
s1 = Student( )
print( s1.name )
ege ege
class Student: s1 = Student( “karan” )
#creating class #creating object
l
def __init__( self, fullname ): s1.hello( )
o l o ll
class Student: s1 = Student( “karan” ) self.name = fullname
a C C
def __init__( self, fullname ):
a
print( s1.name )
Apn Apn
self.name = fullname def hello( self ):
print( “hello”, self.name)
*The self parameter is a reference to the current
instance of the class, and is used to access variables
that belongs to the class.
ege
Create student class that takes name & marks of 3 subjects as arguments in constructor. Methods that don’t use the self parameter (work at class level)
Coll
Then create a method to print the average.
a
class Student:
Apn
@staticmethod #decorator
ege
def college( ):
Coll
print( “ABC College” )
na
Ap
*Decorators allow us to wrap another function in order to
extend the behaviour of the wrapped function, without
permanently modifying it
Important Let‘s Practice
ege ege
Create Account class with 2 attributes - balance & account no.
l l
Abstraction
ol ol
Create methods for debit, credit & printing the balance.
C C
Hiding the implementation details of a class and only showing the essential features to the user.
na na
Encapsulation
Ap
Wrapping data and functions into a single unit (object).
Ap