Professional Documents
Culture Documents
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
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. )
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.
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.
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.
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.
+= 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.
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 literals in python are surrounded by either single quotation marks, double quotation
marks or triple quotation marks”””
Strings manipulation.
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:
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)
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
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 :
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:
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
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
Clear() Method
The clear() keyword clear the dictionary:
Example:
dict = {
“name": “madiha",
“class": "MSCS",
"year": 2018
}
dict.clear()
print(dict)
Output:{}
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 )
Example:
Yes
i=0
While i <= 10: <body>
print(i)
i += 1
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.
Functions Example.
def my_function( ):
print(“welcome to python crash course”) # Function Definition.
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
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
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