0% found this document useful (0 votes)
14 views14 pages

Lecture1 - Py-1 (1) (8 Files Merged)

The document provides an overview of Python programming, highlighting its simplicity, open-source nature, and high-level language features. It covers fundamental concepts such as variables, data types, operators, control structures, and built-in data types like lists, tuples, dictionaries, and sets. Additionally, it includes practical exercises for users to practice their coding skills.

Uploaded by

Md Rony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views14 pages

Lecture1 - Py-1 (1) (8 Files Merged)

The document provides an overview of Python programming, highlighting its simplicity, open-source nature, and high-level language features. It covers fundamental concepts such as variables, data types, operators, control structures, and built-in data types like lists, tuples, dictionaries, and sets. Additionally, it includes practical exercises for users to practice their coding skills.

Uploaded by

Md Rony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Programming What is Python?

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

Data Types Keywords

ge
Keywords are reserved words in python.

lle
ege a Co
*False should be uppercase

oll Apn
pnaC
A

Print Sum Comments in Python

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

Logical Operators ( not , and , or )

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

int ( input( ) ) #int

float ( input( ) ) #float

give code eg of all 3


Let‘s Practice
llege Let‘s Practice
llege
a Co a Co
WAP to input side of a square & print its area. WAP to input 2 floating point numbers & print their average.

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

“hello” + “world” “helloworld”

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]

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


str[0] = ‘B’ #not allowed
Slicing String Functions
Negative Index
str = “I am a coder.”

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

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

Let‘s Practice Conditional Statements


WAP to input user’s first name & print its length. if-elif-else (SYNTAX)

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

Conditional Statements Let‘s Practice


Grade students based on marks WAP to check if a number entered by the user is odd or even.

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”

70 > marks, grade = “D” Apn


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

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) ]

len(student) #returns length marks[ -3 : -1 ] is [33, 95]

List Methods List Methods


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

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

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

Tuples in Python Tuple Methods


A built-in data type that lets us create immutable sequences of values.
tup = (2, 1, 3, 1)

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”.

[1, 2, 3, 2, 1] [1, “abc”, “abc”, 1]

Dictionary in Python Dictionary in Python


Dictionaries are used to store data values in key:value pairs Nested Dictionaries

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

Col Col
na na
Ap Ap
“key” : value

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

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

Dictionary Methods Set in Python


Set is the collection of the unordered items.

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}

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


null_set = set( ) #empty set syntax
Set Methods Set Methods

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

set.pop( ) #removes a random value

Let‘s Practice Let‘s Practice


Store following word meanings in a python dictionary : WAP to enter marks of 3 subjects from the user and store them in a dictionary. Start with

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)

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


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

Loops in Python Let‘s Practice

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 the elements of the following list using a loop:

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

print hello 5 times Search for a number x in this tuple using loop:
print numbers from 1 to 5

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


show infinite, iterator
Break & Continue Loops in Python

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 Loop with else

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

Let‘s Practice range( )

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:

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

Let‘s Practice pass Statement

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

Print the multiplication table of a number n.

generally used in execption handling


Let‘s Practice Functions in Python

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

func_name( arg1, arg2 ..) #function call

Functions in Python Default Parameters

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

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

WAF to convert USD to INR.


Recursion Let‘s Practice

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.

File I/O in Python Open, read & close File

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

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


sample.txt r : read mode
2. Binary Files : .mp4, .mov, .png, .jpeg etc. demo.docx w : write mode

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

Deleting a File Let‘s Practice

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.

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

Let‘s Practice OOP in Python

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”

#creating object (instance)

s1 = Student( )
print( s1.name )

_ _init_ _ Function Methods


Constructor Methods are functions that belong to objects.
All classes have a function called __init__(), which is always executed when the object is being
initiated. #creating class #creating object

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.

Let‘s Practice Static Methods

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

You might also like