0% found this document useful (0 votes)
159 views

Python Notes Apnacollegw

Uploaded by

nani031nani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
159 views

Python Notes Apnacollegw

Uploaded by

nani031nani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Programming

lege
ol
Translator

a C
(Compiler / Interpreter)

Machine
Apn Code
What is Python?
Python is simple & easy

lege
l
Free & Open Source

a
High Level Language
Co
Apn
Developed by Guido van Rossum

Portable
Our First Program
lege
Col
pna
A
print("Hello World")
Python Character Set

e
Letters – A to Z, a to z
Digits – 0 to 9

lleg
Co
Special Symbols - + - * / etc.

na
Whitespaces – Blank Space, tab, carriage return, newline, formfeed

p
A
Other characters – Python can process all ASCII and Unicode characters as part of data or literals
Variables

e
A variable is a name given to a memory location in a program.

lleg
a Co
name = "Shradha"
age = 23

Apn
price = 25.99
Memory

lege
Col
pna
A
name = "Shradha"
age = 23
price = 25.99
Rules for Identifiers

lege
Col
pna
A
Data Types

ge
Integers

String

olle
Float

na C
Ap
Boolean

None
Data Types

lege
Col
pna
A
Keywords

e
Keywords are reserved words in python.

lleg
Co
*False should be uppercase

pna
A
Print Sum

lege
Col
pna
A
Comments in Python

lege
# Single Line Comment

Col
"""

pna
A
Multi Line
Comment
"""
Types of Operators
An operator is a symbol that performs a certain operation between operands.

lege
ol
Arithmetic Operators ( + , - , * , / , % , ** )

na C
Ap
Relational / Comparison Operators ( == , != , > , < , >= , <= )

Assignment Operators ( = , +=, -= , *= , /= , %= , **= )

Logical Operators ( not , and , or )


Type Conversion

lege
l
a, b = 1, 2.0

Co
sum = a + b

pna
A
#error
a, b = 1, "2"
sum = a + b
Type Casting

lege
Col
a
a, b = 1, "2"

pn
c = int(b)

A
sum = a + c
Type Casting

lege
Col
pna
A
Input in Python

e
input( ) statement is used to accept values (using keyboard) from user

lleg
a Co
pn
input( ) #result for input( ) is always a str

A
int ( input( ) ) #int

float ( input( ) ) #float

give code eg of all 3


Let‘s Practice
lege
Col
Write a Program to input 2 numbers & print their sum.

pna
A
Let‘s Practice
lege
Col
WAP to input side of a square & print its area.

pna
A
Let‘s Practice
lege
Col
WAP to input 2 floating point numbers & print their average.

pna
A
Let‘s Practice
lege
Col
WAP to input 2 int numbers, a and b.

na
Print True if a is greater than or equal to b. If not print False.

Ap
Strings
lege
Col
String is data type that stores a sequence of characters.

pna
Basic Operations

concatenation
A
“hello” + “world” “helloworld”

length of str

len(str)
Indexing

Apna_College

ge
0 1 2 3 4 5 6 7 8 9 10 11

olle
na
str = “Apna_College”
C
Ap
str[0] is ‘A’, str[1] is ‘p’ ...

str[0] = ‘B’ #not allowed


Slicing
Accessing parts of a string

str[ starting_idx : ending_idx ] #ending idx is not included

ge
str = “ApnaCollege”

str[ 1 : 4 ] is “pna”

olle
na C
str[ : 4 ] is same as str[ 0 : 4]

Ap
str[ 1 : ] is same as str[ 1 : len(str) ]
Slicing
Negative Index

e
Apple

lleg
o
-5 -4 -3 -2 -1

na C
p
str = “Apple”

A
str[ -3 : -1 ] is “pl”
String Functions
str = “I am a coder.”

lege
str.endsWith(“er.“) #returns true if string ends with substr

Col
a
str.capitalize( ) #capitalizes 1st char

Apn
str.replace( old, new ) #replaces all occurrences of old with new

str.find( word ) #returns 1st index of 1st occurrence

str.count(“am“) #counts the occurrence of substr in string


Let‘s Practice
WAP to input user’s first name & print its length.

lege
Col
na
WAP to find the occurrence of ‘$’ in a String.

p
A
Conditional Statements
if-elif-else (SYNTAX)

ge
if(condition) :
Statement1

olle
a C
elif(condition):

n
Ap
Statement2
else:
StatementN
Conditional Statements
Grade students based on marks

ge
marks >= 90, grade = “A”

olle
C
90 > marks >= 80, grade = “B”

pna
80 > marks >= 70, grade = “C”

A
70 > marks, grade = “D”
Let‘s Practice
WAP to check if a number entered by the user is odd or even.

lege
Col
WAP to find the greatest of 3 numbers entered by the user.

pna
A
WAP to check if a number is a multiple of 7 or not.
Lists in Python
A built-in data type that stores set of values

e
It can store elements of different types (integer, float, string, etc.)

lleg
Co
marks = [87, 64, 33, 95, 76] #marks[0], marks[1]..

pna
A
student = [”Karan”, 85, “Delhi”] #student[0], student[1]..

student[0] = “Arjun” #allowed in python

len(student) #returns length


List Slicing
Similar to String Slicing

ge
list_name[ starting_idx : ending_idx ] #ending idx is not included

olle
C
marks = [87, 64, 33, 95, 76]

pna
marks[ 1 : 4 ] is [64, 33, 95]

A
marks[ : 4 ] is same as marks[ 0 : 4]

marks[ 1 : ] is same as marks[ 1 : len(marks) ]

marks[ -3 : -1 ] is [33, 95]


List Methods
list = [2, 1, 3]

lege
list.append(4) #adds one element at the end [2, 1, 3, 4]

Col
a
list.sort( ) #sorts in ascending order [1, 2, 3]

Apn
list.sort( reverse=True ) #sorts in descending order [3, 2, 1]

list.reverse( ) #reverses list [3, 1, 2]

list.insert( idx, el ) #insert element at index


List Methods
list = [2, 1, 3, 1]

lege
list.remove(1) #removes first occurrence of element [2, 3, 1]

Col
a
list.pop( idx ) #removes element at idx

Apn
Tuples in Python
A built-in data type that lets us create immutable sequences of values.

lege
l
tup = (87, 64, 33, 95, 76) #tup[0], tup[1]..

a Co
n
tup[0] = 43 #NOT allowed in python

Ap
tup1 = ( )

tup2 = ( 1, )

tup3 = ( 1, 2, 3 )
Tuple Methods
tup = (2, 1, 3, 1)

lege
tup.index( el ) #returns index of first occurrence tup.index(1) is 1

Col
a
tup.count( el ) #counts total occurrences tup.count(1) is 2

Apn
Let‘s Practice
WAP to ask the user to enter names of their 3 favorite movies & store them in a list.

lege
Col
na
WAP to check if a list contains a palindrome of elements. (Hint: use copy( ) method)

p
A
[1, 2, 3, 2, 1] [1, “abc”, “abc”, 1]
Let‘s Practice
WAP to count the number of students with the “A” grade in the following tuple.
[”C”, “D”, “A”, “A”, “B”, “B”, “A”]

lege
Col
na
Store the above values in a list & sort them from “A” to “D”.

p
A
Dictionary in Python
Dictionaries are used to store data values in key:value pairs

ge
They are unordered, mutable(changeable) & don’t allow duplicate keys

le
Col
na
“key” : value

Ap
dict[”name”], dict[”cgpa”], dict[”marks”]

dict[”key”] = “value” #to assign or add new


Dictionary in Python
Nested Dictionaries

lege
Col
pna
A
student[”score”][”math”]
Dictionary Methods
myDict.keys( ) #returns all keys

lege
ol
myDict.values( ) #returns all values

na C
p
myDict.items( ) #returns all (key, val) pairs as tuples

A
myDict.get( “key““ ) #returns the key according to value

myDict.update( newDict ) #inserts the specified items to the dictionary


Set in Python
Set is the collection of the unordered items.

ge
Each element in the set must be unique & immutable.

olle
nums = { 1, 2, 3, 4 }

na C
set2 = { 1, 2, 2, 2 }

Ap
#repeated elements stored only once, so it resolved to {1, 2}

null_set = set( ) #empty set syntax


Set Methods
set.add( el ) #adds an element

lege
ol
set.remove( el ) #removes the elem an

na C
p
set.clear( ) #empties the set

A
set.pop( ) #removes a random value
Set Methods
set.union( set2 ) #combines both set values & returns new

lege
set.intersection( set2 ) #combines common values & returns new

Col
pna
A
Let‘s Practice
Store following word meanings in a python dictionary :

ge
table : “a piece of furniture”, “list of facts & figures”
cat : “a small animal”

olle
na C
Ap
You are given a list of subjects for students. Assume one classroom is required for 1
subject. How many classrooms are needed by all students.

”python”, “java”, “C++”, “python”, “javascript”,


“java”, “python”, “java”, “C++”, “C”
Let‘s Practice
WAP to enter marks of 3 subjects from the user and store them in a dictionary. Start with
an empty dictionary & add one by one. Use subject name as key & marks as value.

lege
Col
pna
A
Figure out a way to store 9 & 9.0 as separate values in the set.
(You can take help of built-in data types)
Loops in Python

ge
Loops are used to repeat instructions.

olle
C
while Loops

pna
while condition :

A
#some work

print hello 5 times


print numbers from 1 to 5

show infinite, iterator


Let‘s Practice

e
Print numbers from 1 to 100.

lleg
Co
Print numbers from 100 to 1.

pna
A
Print the multiplication table of a number n.

Print the elements of the following list using a loop:

[1, 4, 9, 16, 25, 36, 49, 64, 81,100]

Search for a number x in this tuple using loop:

[1, 4, 9, 16, 25, 36, 49, 64, 81,100]


Break & Continue

e
Break : used to terminate the loop when encountered.

lleg
Co
Continue : terminates execution in the current iteration & continues execution of the loop

na
with the next iteration.

Ap
take search example
& stop the search when found

print all numbers but not multiple of 3


Loops in Python

ge
Loops are used used for sequential traversal. For traversing list, string, tuples etc.

olle
C
for Loops

pna
for el in list:

A
#some work

for Loop with else

for el in list:
#some work

else:
else used as it doesn’t execute
#work when loop ends when break is used
Let‘s Practice

ge
using for

olle
Print the elements of the following list using a loop:

na C
[1, 4, 9, 16, 25, 36, 49, 64, 81,100]

Ap
Search for a number x in this tuple using loop:

[1, 4, 9, 16, 25, 36, 49, 64, 81,100]


range( )

ge
Range functions returns a sequence of numbers, starting from 0 by default, and increments by

lle
1 (by default), and stops before a specified number.

o
a C
range( start?, stop, step?)

n
Ap
Let‘s Practice

ge
using for & range( )

olle
Print numbers from 1 to 100.

na C
p
Print numbers from 100 to 1.

A
Print the multiplication table of a number n.
pass Statement

ge
pass is a null statement that does nothing. It is used as a placeholder for future code.

olle
na C
for el in range(10):

Ap
pass

generally used in execption handling


Let‘s Practice

e
WAP to find the sum of first n numbers. (using while)

lleg
a Co
Apn
WAP to find the factorial of first n numbers. (using for)
Functions in Python

ge
Block of statements that perform a specific task.

olle
na C
def func_name( param1, param2..) : Function Definition

Ap
#some work
return val

func_name( arg1, arg2 ..) #function call


Functions in Python

lege
ol
Built-in Functions User defined Functions

n
print( )

a C
Ap
len( )

type( )

range( )
Default Parameters

ge
Assigning a default value to parameter, which is used when no argument is passed.

olle
na C
Ap
Let‘s Practice

lege
WAF to print the length of a list. ( list is the parameter)

Col
pna
WAF to print the elements of a list in a single line. ( list is the parameter)

A
WAF to find the factorial of n. (n is the parameter)

WAF to convert USD to INR.


Recursion

lege
ol
When a function calls itself repeatedly.

#prints n to 1 backwards

na C
Ap Base case
Recursion

e
#returns n!

lleg
a Co
Apn
Let‘s Practice

lege
Write a recursive function to calculate the sum of first n natural numbers.

Col
pna
A
Write a recursive function to print all elements in a list.
Hint : use list & index as parameters.
File I/O in Python

ge
Python can be used to perform operations on a file. (read & write data)

olle
a C
Types of all files

n
Ap
1. Text Files : .txt, .docx, .log etc.

2. Binary Files : .mp4, .mov, .png, .jpeg etc.


Open, read & close File

ge
We have to open a file before reading or writing.

olle
C
f = open( “file_name”, “mode”)

pna
A
sample.txt r : read mode
demo.docx w : write mode

data = f.read( )

f.close( )
lege
Col
pna
A
Reading a file

lege
l
data = f.read( ) #reads entire file

a Co
pn
data = f.readline( ) #reads one line at a time

A
Writing to a file

lege
l
f = open( “demo.txt”, “w”)

a Co
f.write( “this is a new line“ ) #overwrites the entire file

Apn
f = open( “demo.txt”, “a”)

f.write( “this is a new line“ ) #adds to the file


with Syntax

lege
l
with open( “demo.txt”, “a”) as f:

Co
data = f.read( )

pna
A
Deleting a File

ge
using the os module

olle
Module (like a code library) is a file written by another programmer that generally has

C
a functions we can use.

pna
A
import os
os.remove( filename )
Let‘s Practice

ge
Create a new file “practice.txt” using python. Add the following data in it:

olle
C
Hi everyone

na
we are learning File I/O

Ap
using Java.
I like programming in Java.

WAF that replace all occurrences of “java” with “python” in above file.

Search if the word “learning” exists in the file or not.


Let‘s Practice

ege
WAF to find in which line of the file does the word “learning”occur first.

l
ol
Print -1 if word not found.

na C
Ap
From a file containing numbers separated by comma, print the count of even numbers.
OOP in Python

ge
To map with real world scenarios, we started using objects in code.

olle
This is called object oriented programming.

na C
Ap
Class & Object in Python

ge
Class is a blueprint for creating objects.

olle
C
#creating class

na
class Student:

Ap
name = “karan kumar”

#creating object (instance)

s1 = Student( )
print( s1.name )
Class & Instance Attributes

lege
ol
Class.attr

C
obj.attr

pna
A
_ _init_ _ Function
Constructor
All classes have a function called __init__(), which is always executed when the object is being
initiated.

#creating object

e
#creating class

leg
class Student:

l
s1 = Student( “karan” )

Co
def __init__( self, fullname ): print( s1.name )

na
self.name = fullname

Ap
*The self parameter is a reference to the current
instance of the class, and is used to access variables
that belongs to the class.
Methods
Methods are functions that belong to objects.

#creating class #creating object

class Student: s1 = Student( “karan” )

ge
def __init__( self, fullname ): s1.hello( )

lle
self.name = fullname

a Co
n
def hello( self ):

Ap
print( “hello”, self.name)
Let‘s Practice

e
Create student class that takes name & marks of 3 subjects as arguments in constructor.

lleg
Then create a method to print the average.

a Co
Apn
Static Methods
Methods that don’t use the self parameter (work at class level)

class Student:
@staticmethod #decorator

e
def college( ):

lleg
print( “ABC College” )

a Co
Apn
*Decorators allow us to wrap another function in order to
extend the behaviour of the wrapped function, without
permanently modifying it
Important

ge
Abstraction

olle
Hiding the implementation details of a class and only showing the essential features to the user.

na C
Encapsulation
Ap
Wrapping data and functions into a single unit (object).
Let‘s Practice

e
Create Account class with 2 attributes - balance & account no.

lleg
Create methods for debit, credit & printing the balance.

a Co
Apn

You might also like