You are on page 1of 70

Department of Prepared By:

Computer Science Ms. Zainab Imtiaz


Agenda
What is Python ? Python Tuples.
Environment Setup. Python Dictionary.
Basic syntax. Decision Structures.
Identifiers.
Loops.
Reserved Word/Escape Characters.
Functions.
Python Numbers/Python Basic Operators.
File Handling.
Python Strings.

Python List. OOP With Python.


What is Python ?

Python is a general purpose interpreted, interactive, Object-oriented, and high-level programming


language.

Interpreted: A language that is read in it’s raw from and executed statement at a time without being first
compiled. (You do not need to compile your program before executing it)

Interactive: Use the Python command prompt and interact with the interpreter directly to write your script.
Environment Setup.

The Following two methods are using for running the python Script. How to Install Python
Run a python script as file/ Script Mode Programming

C:\users\your name>python myfile.py

Python Execution with the shell (Live Interpreter)/ Interactive Mode


Programming

Open command Prompt type python press enter key you will enter into
Live Interpreter Mode. Now You Write your python script code and see
result on same screen.
Basic Syntax.
(Docstrins,Comments in Python, Single Statement in Multiple lines, Multiple Statement in single line. )

 Docstrings/Triple Quotes
 Python also has extended documentation capability, called docstrings.
 Block-level comment in Python.
 Docstrings can be one line, or multiline.  In Python block level comment start with
 Python uses triple quotes at the beginning and end of the docstring.
Syntax. ‘’’comments’’’.
“”” Name of file: test.py
Author:
Created:
Irfan ul haq
25.11.2018
Syntax.
Modify: 26.11.2018
Licensed: Open source. ‘’’ comment 1.
© Copyright by Irfa Corp.
etc… “””
comment 2.
comment 3.’’’
 Comments in Python.
 Text placed in a program for the benefit of human readers.
 Comments are ignored by the Interpreter.
 Comments Explains the implementation of the code.
 In Python single line comment start with #.
Syntax.
# comment 1.
#comment 2.
#comment 3.
……
Basic Syntax.
(Docstrins,Comments in Python, Single Statement in Multiple lines, Multiple Statement in single line. )

 Single Statement in Multiple Lines.


 Sometimes it is nicer to break a long statement into smaller pieces.
 For this we use line continuation character (\).
Syntax.
Total = item_one + \
item_two + \
item_three…
 If Statement contained within [],{} or () brackets do not need to the line continuation character.
Syntax.
months = [“January”, “February”,
“March","April”,”May”,”June”]
Basic Syntax.
(Docstrins,Comments in Python, Single Statement in Multiple lines, Multiple Statement in single line. )

 Multiple Statements in single line.


 The Semicolon (;) allows multiple statements in single line.
 If you want to write multiple statements in single line you can use semicolon (;)
 Syntax.
x= ‘foo’; print(“multiple statements in single line”)

 Line Indentations.
 In other programming languages the indentation in code is for readability only in Python the
indentation is very important.
 Syntax.
if 5 > 2:
print(“Five is greater than two!”)
Identifiers
(identifiers, Naming Conventions or rules,)

 Identifier.
 .A Python identifiers is a name used to identify a variable, function, class, module, or other object.

 Naming Conventions or rules .


 A name must start with a letter or underscore character.
 A name cannot start with number.
 A name can only contain alpha numeric character and underscore( _,Aa-Zz,0-9).
 A name is case-sensitive.
 Punctuation not allow in a name (@,$,%, etc…).
 Class name start with an uppercase letter and all other identifiers with a lowercase letter.
 Starting an identifier with a single leading underscore indicates by convention that the identifier is
meant to be private.
 Starting an identifier with tow leading underscores indicates a strongly private identifier.
 If the identifier also ends with two trailing underscores, the identifiers is a language-defined special
name
Reserved word/Keywords.
()

 Reserved word.
 Python keywords are the words that are reserved. That means you can’t use them as name of
and entities like variables, classes and functions.
 They are for defining the syntax and structures of Python language.

Here are the list of the keywords.


False Await Else Import Pass
None Break Except In Raise
True Class Finally Is Return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Escape Characters.
()

 Escape Sequence.
 An escape sequence refers to a combination of characters beginning with a back slash(\)
followed by letters or digits. Escape sequences represent non-printable and special characters in
character and literal strings.
Escape characters.
Escape Meaning Escape Meaning
Sequence Sequence
\newline Backslash and newline ignored. \f ASCII Formfeed(FF).
\\ Backslash(\) \n ASCII LineFeed (LF).
\’ Single quote(‘) \r ASCII Carriage Return (CR).
\” Double quote(“) \t ASCII Horizontal Tab (TAB).
\a ASCII Bell (BEL) \v ASCII Vertical Tab (VT)
\b ASCII Backspace (BS) \ooo Character with octal value 000
Python Numbers.
()

 Numbers.
 Data types that store numeric values are called Number. If you change the value of a number
data type this result in a newly allocated object. So you can call numbers immutable.
 We can simply create a number object by assigning some value to a.

 Numeric types in Python.


 Python supports four different numerical types.
 int (signed integers)
 long (long integers)
 float (floating point real values)
 complex (complex numbers).
Python Numbers.
()

 Example.
x=1 # int
y = 2.8 # float
z = 1j # complex
Basic Operators.
()

 Python Operators.
 Python Operators are the special symbols that can manipulate values of one or more operands.
 Python operators allows us to do common processing on variables.
 We will look into different types of python operators with examples and also operator
precedence.

 Types of Operators.
 Python operators can be classified into following categories.
 Arithmetic Operators.
 Assignment operators.
 Comparison operators.
 Logical operators.
Basic Operators.
()

 Arithmetic operators.
 Arithmetic operators are used with numeric values to perform common mathematical operation.
Operator Name

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

** Exponentiation

// Floor Division
Basic operators.
()

 Assignment operators.
 Assignment operators are used to store data into variable.

Operator Name & Description


Example

= Assigns values from right side operands to left side operand


b = a assigns value of an into b

+= Add AND – It adds right operand to the left operand and assigns the result to left operand
c += a is equivalent to c = c + a

-= Subtract AND – It subtracts right operand from the left operand and assign the result to left operand
c -= a is equivalent to c = c – a

*= Multiply AND – It multiplies right operand with the left operand and assign the result to left operand
c *= a is equivalent to c = c * a

/= Divide AND – It divides left operand with the right operand and assign the result to left operand
c /= a is equivalent to c = c / ac /= a
is equivalent to c = c / a

%= Modulus AND – It takes modulus using two operands and assign the result to left operand
c %= a is equivalent to c = c % a
Basic Operators.
()

 Comparison operators.
 Comparison operators are used to compare two values.

Operator Name Example


== Equal (a == b) is true
!= Not equal (a != b) is true
> Greater than (a > b) is not true
< Less than (a < b) is true
>= Greater than or equal to (a >= b) is not true
<= Less than or equal to (a <= b) is true
Basic Operators.
()

 Logical operators.
 Logical operators are used to combine conditional Statements.

Operator Description
And Return True if both statements are true
or Return True if one of the statements is true
not Reverse the result, returns False if the result is
True
Strings in Python.
()

 Strings:
 String is an array of characters.
 String literals in python are surrounded by either single quotation marks, double quotation
marks or triple quotation marks .
Examples
‘string ’

“String in Double quotation marks”

“””String literals in python are surrounded by either single quotation marks, double quotation
marks or triple quotation marks”””
Strings manipulation.

str = 'Hello World!'


Output:
print( str) # Prints complete string
Hello World!
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd
H
to 6th llo
print(str[2:]) # Prints string starting from 3rd
character llo World!
print(str * 2) # Prints string two times Hello World!Hello World!
print( str + "TEST" ) # Prints concatenated string Hello World!TEST
String Function

STRIP :-
Defination:
Strip function is used to remove white spaces from beginning and end.
Example:
s = “ STRING ”
print(s.strip()) # ‘STRING’
SPLIT :-
Defination:
Split function the string into substring.
Example:
s =“Hello World”
print(s.split(“ ”)) # [‘Hello’ ,’World’]
String Functions

Upper:-
Defination:
Upper function is used to convert the string in the upper case.
Example:
s = “hello, world ”
print(s.upper()) # HELLO WORLD

Lower:-
Defination:
Lower function is used to convert the string in the lower case.
Example:
s = “HEllo, WOrld ”
print(s.lower()) # hello world
String Functions

Length:-
Defination:
len function is used to calculate the length of a string.
Example:
s = “hello,world ”
print(len(s)) # 11
Replace:-
Defination:
Replace function is used to replace a string to another string.
Example:
s = “hello, world ”
print(s.replace(“h”,”j”)) # jello,world
List in Python.
()

 List.
 A list is a collection which is ordered and changeable.
 In Python lists are written with square brackets.

Examples:
thislist = [“apple”, “banana”,”Cherry”]
print(thislist)
print(thislist[1])
Output:
[‘apple’,’banana’,’cherry’]
banana
List Functions

Length:-
Defination:
len function is used to calculate the length of the elements in a list.
Example:
a=[“apple”,”banana”,”cherry”]
print(len(a)) #3
Append:-
Defination:
append function is used to append item at the end of the string.
Example:
a=[“apple”,”banana”,”cherry”]
a.append(“orange”)
# ['apple', 'banana‘,’cherry’, 'orange']
List Functions

Insert:-
Defination:
Insert function is used to insert an elements in a list.
Example:
a=[“apple”,”banana”,”cherry”]
a.insert(1,”kiwi”)
print(a) #[‘apple’,’kiwi’,’banana’,’cherry’]
Remove:-
Defination:
Remove function is used to remove an item in a list.
Example:
a=[“apple”,”banana”,”cherry”]
a.remove(”banana”)
print(a) #[‘apple’,’cherry’]
List Functions

POP:-
Defination:
pop function is used to pop an elements in a list.
Example:
a=[“apple”,”banana”,”cherry”]
a.pop(1,) #’apple’
print(a) #[‘apple’,’cherry’]
del:-
Defination:
del function is used to delete a list.
Example:
list=[“apple”,”banana”,”cherry”]
del list
print(list) #NameError: name ‘list' is not defined
Built-in List Functions & Methods:

SN Function with Description


1 cmp(list1, list2)
Compares elements of both lists.

2 len(list)
Gives the total length of the list.

3 max(list)
Returns item from the list with max value.

4 min(list)
Returns item from the list with min value.

5 list(seq)
Converts a tuple into list.
Python - Tuples

 A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

 Example
 Create a Tuple:
 thistuple = ("apple", "banana", "cherry")
print(thistuple)

 Output: ('apple', 'banana', 'cherry')


The empty tuple is written as two parentheses containing nothing:
tup1 = ();
To write a tuple containing a single value you have to include a comma, even though there is only one value:
tup1 = (50,);
 Like string indices, tuple indices start at 0, and tuples can be sliced, concatenated and so on.
Access Tuple Items

 You can access tuple items by referring to the index number, inside square
brackets:
 Example
 Return the item in position 1:
 thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
 Output:
banana
Access Tuple Items

 To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index:
 Example:
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: “, tup2[1:5])

 Output
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples

 Once a tuple is created, you cannot change its values. Tuples are unchangeable.
 Example
 You cannot change values in a tuple:
 thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant"
# The values will remain the same:
print(thistuple)
 Output:
('apple', 'banana', 'cherry')
Updating Tuples

 Example :
 We cannot change a tuple value but concatenate tuples by creating a new tuple.
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
tup3 = tup1 + tup2;
print tup3;
Output:
(12, 34.56, 'abc', 'xyz')
Delete Tuple Elements

 Removing individual tuple elements is not possible.


 Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple
completely:
 Example:
thistup = (‘apple', ‘banana', ‘cherry’, 200)
del thistup
Print(thistup) #this will raise an error because the tuple no longer exists
NameError: name ‘thistup; is not defined.
Add Items in Tuple

 Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
 Example
 You cannot add items to a tuple:
 thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Basic Tuples Operations:

 Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.
 In fact, tuples respond to all of the general sequence operations we used on strings in
the prior chapter :

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
['Hi!'] * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) TRUE Membership
for x in (1, 2, 3): print x, 123 Iteration
Indexing, Slicing, and Matrixes:

 Because tuples are sequences, indexing and slicing work the same way for tuples as they do for
strings.
 Assuming following input:
L = ('spam', 'Spam', 'SPAM!')

Python
Results Description
Expression
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Built-in Tuple Functions:

SN Function with Description


1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.
Python - Dictionaries

 A dictionary is a collection which is unordered, changeable and indexed. In


Python dictionaries are written with curly brackets, and they have keys and
values.
 Each key is separated from its value by a colon (:)
 The items are separated by commas
 The whole thing is enclosed in curly braces.
 An empty dictionary without any items is written with just two curly braces, like
this: {}.
 Keys are unique within a dictionary while values may not be.
Python - Dictionaries

 Example
 Create and print a dictionary:
 dict = {
“name": “madiha",
“class“ : “MSCS",
"year": 2018
}
print(dict)
 Output: {‘name': ‘madiha', ‘class': 'MSCS', 'year': 2018}
Accessing Values in Dictionary

 To access dictionary elements, you can use the familiar square brackets along with the key to obtain its
value.
 Example:
 dict = {
“name": “madiha",
“class“ : “MSCS",
"year": 2018
}
print(dict[“name”])
print(dict[“class”])
Output:
madiha
MSCS
Adding Items in Dictionary

 Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
 Example
 dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018
}
dict[“department"] = “cs"
print(dict)
 Output: {‘name': ‘madiha', ‘class': 'MSCS', 'year': 2018, ‘department': ‘cs'}
Updating Dictionary

 Adding an item to the dictionary is done by using a new index key and assigning a value
to it:
 Example
 dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018 , “department”:”cs”
}
dict[“department"] = “CE"
print(dict)
 Output: {‘name': ‘madiha', ‘class': 'MSCS', 'year': 2018, ‘department': ‘CE'}
Delete Dictionary Elements

 There are several methods to remove items from a dictionary:


 POP Method
 Del Method
 Clear Method
Delete Dictionary Elements

 pop() Method
 The pop() method removes the item with the specified key name.
 Example:
 dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018
}
dict.pop(“class")
print(dict)
 Output: {‘name': ‘madiha', 'year': 2018}
Delete Dictionary Elements

 popitem() Method
 Example:
 dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018
}
dict.popitem()
print(dict)
 Output: {‘name': ‘madiha', ‘class': ‘MSCS’}
Delete Dictionary Elements

 del Method:
 The del keyword remove the item with specified key name.
 Example:
 dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018
}
del dict[“name"]
print(dict)
 Output:{‘class': ‘MSCS', ‘year': 2018}
Delete Dictionary Elements

 The del keyword also delete the dictionary completely.


 Example:
 dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018
}
del dict
print(dict) #this will cause an error because "dict" no longer exists.
Delete Dictionary Elements

 Clear() Method
 The clear() keyword clear the dictionary:
 Example:
 dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018
}
dict.clear()
print(dict)
 Output:{}
Python - Decision Making

 Decision structures evaluate multiple expressions which produce TRUE or FALSE


as outcome.
 Python provides following types of decision making statements:
 If statements
 If…else statements
 If..elif statement
 Nested if statements
Python - Decision Making

 If Statement:
 An "if statement" is written by using the if keyword.
 Syntax:
if expression:
statementss
 Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
Output: #b is greater than a
Python - Decision Making

 If…else Statemets :
An else statement contains the block of code that executes if the conditional
expression in the if statement resolves to 0 or a FALSE value.
 Syntax:
If expression:
Statement(s)
else:
Statement(s)
Python - Decision Making

 If..elif Statement:
 The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".
 Syntax:
if expression:
statement(s)
elif expression2:
statement(s)
else:
statement(s)
Python - Decision Making

 Example:
 a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Python - Decision Making

 Nested..if statements:
 a=2
 If a>1:
 If a==2:
 Print(“done”)

 Output:
done
Loops.
(for loop, while loop, Nested loop, break, continue, use of else )

 Types of Loops in python.  Example


 There are two main types of loop in  Find average of the given numbers.
python. def main():
 For loop and while loop.
n = int(input(“How many numbers do you have ?”))
For loop syntax. total = 0.0
for <var> in <sequence>:
for i in range(n):
<body>
x = flaot (input(“Enter number >> ”))
total = total + x
print(“\nThe average of the numbers is ” ,total /n)
main()
Loops.
(for loop, while loop, Nested loop, break, continue, use of else )

 Indefinite loop.  Flow chart of while loop.

while loop syntax


while <condition>:
<body> No
<condition>?

Example:
Yes
i=0
While i <= 10: <body>
print(i)
i += 1
Loops.
(for loop, while loop, Nested loop, break, continue, use of else )

 Nested loop.  Example Nested loop.


 Python allows to use one loop inside another
adj = [“red”, “big”, “tasty”]
loop.
fruits =[“apple”, “banana”, “cherry”]
Nested loop syntax
for x in adj:
for iterating_var in sequence:
for iterating_var in sequence: for y in fruits:
statement(s)
statement(s) print(x,y)
Loops.
(for loop, while loop, Nested loop, break, continue, use of else )

 Break .  Continue .
 break is used to exit a for loop or a while loop.  continue is used to skip the current block.

Example Example
Count = 0 for x in range(10):
while true : # Check if x is even
print(count) if x % 2 == 0:
count += 1 continue
if count >= 5: print(x)
break
# prints out only odd numbers- 1,3,5,7,9
# prints out 0,1,2,3,4
Loops.
(for loop, while loop, Nested loop, break, continue, use of else )

 Use of else .
 We can use else for loops. When the loop condition of for or while statement fails then code part in else is
executed. If break statement is executed inside for loop then the else part is skipped. Note that else part is
executed even if there is a continue statement

Example
Count = 0
while (count < 5):
print(count)
count += 1
else
print(“count value reached %d” %(count))
# prints out 0,1,2,3,4 and
then it prints count value reached 5
Functions.
(function, function with parameters, Anonymous Function)

 Functions in Python.
 A function is a block of code which only runs when it is called. You can pass data, known as parameters’
 A function can return data as a result.
 Function block begin with the keyword def followed by the function name ,parentheses and colon.

Basic function syntax


def functionname( parameters ):
statement-1
statement-2
.
.
return value
Functions.

 Functions Example.
def my_function( ):
print(“welcome to python crash course”) # Function Definition.

my_function() # Calling a function.


Functions.

 Functions with parameters example.


def addInterest(balances, rate): # Function Definition with formal-parameters.
for i in range(len(balances)):
balances[i] = balances[i] * (1+rate)

def test( ):
amounts = [1000,2200, 800, 360]
rate = 0.05
addInterest(amount, rate) # Calling a function with actual-parameters.
return amounts
Function.

 Anonymous Function.
 In Python, anonymous function means that a function is without a name. As we already know
that def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.
 The lambda functions are syntactically restricted to a single expression.
 It has the following syntax

lambda arguments : expression


Examples:
Show difference between def() and lambda().

def cube(y): g = lambda x: x*x*x


return y*y*y print(g(7))
print(cube(7))
File handling.

 File handling in python.


 File handling is an important part of any web and data science application.
 Python has several functions for creating, reading, updating, and deleting files.
 The key function for working with files in Python in the open() function.
 The open() function takes two parameters; filename, and mode.
 Following modes are used to open a file.

Modes Description
“r” Read Default value. Opens a file for reading, error if the file does not exist
“a” Append Opens a file for appending, creates the file if it does not exist
“w” Write Opens a file for writing, creates the file if it does not exist
“x” Creates the specified file, returns an error if the file exists
“t” Text Default value. Text mode
“b” Binary Binary mode (e.g. images)
File handling.

 Examples.
 To open text file use:
Txtfo = open(“textfile.txt”,”r”)
 To read a text file, use:
txtfo = open(“textfile.txt”,”rt”)
print(txtfo.read())
To write to a file use:
txtfo = open(“txtfile.txt”,”w”)
txtfo.write(“Hello Python”)
txtfo.close()
To append to file use:
txtfo = open(“txtfile.txt”,”a”)
txtfo .write(“hello Python”)
txtfo.close()
Object Oriented Programming in Python

 Python is an object oriented programming language. Object oriented programing


stress on objects.
 Object is simply a collection of data (variables) and methods (functions) that act
on those data. And, class is a blueprint for the object.
 An object is also called an instance of a class and the process of creating this
object is called instantiation.
Object Oriented Programming in Python

 Defining a Class in Python


In Python, we define a class using the keyword class. The first string is called
docstring and has a brief description about the class. Although not mandatory, this
is recommended.
Class myNewClass:
“This is a new class”
pass
Object Oriented Programming in Python

 Creating an Object in Python


 We saw that the class object could be used to access different attributes.
 The procedure to create an object is similar to a function call.
It’s syntax is as follows :-
 >>> ob = myClass()

 This will create a new instance object named ob. We can access attributes of
objects using the object name prefix.
 Attributes may be data or method. Method of an object are corresponding
functions of that class
Object Oriented Programming in Python

 Constructors in Python
 Class functions that begins with double underscore (__) are called special
functions as they have special meaning. Of one particular interest is the
__init__() function. This special function gets called whenever a new object of
that class is instantiated. We normally use it to initialize all the variables.
 class ComplexNumber
def __init__(self,r = 0,i = 0):
self.real = r
self.imag = I
def getData(self):
print("{0}+{1}j".format(self.real,self.imag))
Object Oriented Programming in Python

 Deleting Attributes and Objects


 Any attribute of an object can be deleted anytime, using the del statement.
>> c1 = ComplexNumber
>>del c1.imag
>>c1.getdate()

You might also like