Python Programming Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 76

History of Python

✓ The idea of PYTHON started in early 1980s.


✓ Real Implementation started in 1989.
✓ Published in 27 Feb 1991.
✓ Developed by Guido van Rossum who was working in National
Research Institute Netherlands.
Ancestors of PYTHON
✓ SETL(SET Language) is a very high level programming language
based on the mathematical theory of sets.
✓ SETL appeared in 1969,developed at NEW YORK University.
✓ ABC language influenced by SETL was developed at CWI,
intended to replace BASIC, Pascal.
✓ ABC had a major influence on the design
of Python Programming language.
✓ Guido previously worked for several
years on the ABC system in the early 1980s.
Naming of PYTHON
✓ Python name was inspired from a TV show Monty Python’s
Flying Circus it has nothing to do with snake.
Installation of Jupyter Notebook
Keywords in Python
✓ Keywords are reserved words in python.
✓ We can’t use a keyword as variable name or any other identifier.
✓ Keywords are case sensitive.
Keywords in Python
Identifiers in Python
✓ Identifier is the name given to entities like class, functions, variable.
✓ It helps differentiating one entity from other.
✓ (a-z) , (A-Z) , (0-9) , ( _ ) .
✓ Cannot Start with digit.
✓ Keywords cannot be used as an identifier.
Standard IO in Python
Comments & Indentation in Python
✓ Comments are lines that exist in computer programs that are ignored
by compilers & interpreters.
✓ Including comments in program makes code more readable for
humans as it provides some information or explanation about what
each part of a program is doing.
Data types in Python
✓ Every value in python has a datatype. Since, everything is an object in
python programming, data types are actually classes & variables are
instances (object) of these classes.
Operators in Python
✓ Operators are special symbols in python that carry out arithmetic or
logical computation. The value that the operator operates on is called
the operand.

Types:
▪ Arithmetic Operator
▪ Relational Operator
▪ Logical Operator
▪ Bitwise Operator
▪ Assignment Operator
▪ Special Operator
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
•Equals: a == b
•Not Equals: a != b
•Less than: a < b
•Less than or equal to: a <= b
•Greater than: a > b
•Greater than or equal to: a >= b
These conditions can be used in several ways,
most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
Python Conditions and If statements
Example If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")
Elif:
The elif keyword is pythons way of saying "if the previous
conditions were not true, then try this condition".
Example:-
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else:
The else keyword catches anything which isn't caught by the preceding conditions.

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")
Loops in Python:
Python has two primitive loop commands:
•while loops
•for loops
The while Loop:

With the while loop we can execute a set of statements as long as a


condition is true.
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Python For Loops:
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming
languages.
With the for loop we can execute a set of statements,
once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Break & Continue in Python
List Data Structure:
A list in Python is used to store the sequence of various types of data. Python lists
are mutable type its mean we can modify its element after it created. However,
Python consists of six data-types that are capable to store the sequences, but the
most common and reliable type is the list.
A list can be defined as a collection of values or items of different types. The
items in the list are separated with the comma (,) and enclosed with the square
brackets [].

A list can be define as below


1.L1 = ["John", 102, "USA"]
2.L2 = [1, 2, 3, 4, 5, 6]
Tuple Data Structure:
A Tuple is a collection of Python objects separated by commas. In someways a
tuple is similar to a list in terms of indexing, nested objects and repetition but a
tuple is immutable unlike lists which are mutable.

thistuple = ("apple", "banana", "cherry")


print(thistuple)
String Data Structure:
A string is a sequence of characters.
A character is simply a symbol.

For example:
print("Hello")
print('Hello')
Set Data Structure:
Sets are used to store multiple items in a single variable.

For example:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Dictionary Data Structure:
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.

Creating a Function
In Python a function is defined using
the def keyword:
Example
def my_function():
print("Hello from a function")
Python Functions:
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by
parenthesis:
Example
def my_function():
print("Hello from a function")

my_function()
Arguments:

Information can be passed into functions as arguments.


Arguments are specified after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function
is called, we pass along a first name, which is used inside the function to print the full
name:
Example
def my_function(fname):
print(fname + " Pandey")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Argument:
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function
definition.
An argument is the value that is sent
to the function when it is called.
Number of Argument:
Number of Arguments
By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you
have to call the function with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil", “Pandey")
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access
the items accordingly:

Example
If the number of arguments is unknown, add a * before the parameter
name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Keyword Arguments:
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


Default Parameter Value:
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Example
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument:
You can send any data types of argument to a function (string, number,
list, dictionary etc.), and it will be treated as the same data type inside
the function.
E.g. if you send a List as an argument,
it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
Return Values:
To let a function return a value, use the return statement:

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement:
function definitions cannot be empty, but if you for some
reason have a function definition with no content, put in
the pass statement to avoid getting an error.

Example
def myfunction():
pass
Recursion:
Python also accepts function recursion, which means a defined function
can call itself.
Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can
loop through data to reach a result.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)
Check whether a year is leap year or not?
How to remove duplicates?
Print first 10 natural numbers?
How to reverse a tuple?
How to print next prime?
How to print N prime numbers?
Single line code for factorial of a number?
How to remove duplicates from string?
Sum of Squares using Recursion?
Reverse a String using Slicing?
Check divisibility of a number?
Sort in dictionary order?
How to sort a list?
Comparing two tuples?
Sum of n natural number?
Euclid’s Algorithm:
OOPS Concept in Python
Classes & Objects :
▪ Python is an object oriented programming language.
▪ Almost everything in Python is an object, with its
properties and methods.
▪ A Class is like an object constructor, or a "blueprint"
for creating objects.
The __init__() Function:
The examples above are classes and objects in their simplest form, and are not really
useful in real life applications.
To understand the meaning of classes we have to understand
the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class
is being initiated.
Use the __init__() function to assign values to object properties,
or other operations that are necessary to do
when the object is being created:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
Types of Variables in OOPS:
1. Instance Variable
2. Static(Class) Variable
Polymorphism:
The literal meaning of polymorphism is the condition of
occurrence in different forms.
Polymorphism is a very important concept in programming. It
refers to the use of a single type entity (method, operator or
object) to represent different types in different scenarios.
Example 1: Polymorphism in addition operator
We know that the + operator is used extensively in Python programs. But, it does not have a single usage.
For integer data types, + operator is used to perform arithmetic addition operation.

num1 = 1
num2 = 2
print(num1+num2)

Hence, the above program outputs 3.


Similarly, for string data types, + operator is used to perform concatenation.

str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)
As a result, the above program outputs Python Programming.
Here, we can see that a single operator + has been used to carry out
different operations for distinct data types.
This is one of the most simple occurrences
of polymorphism in Python.
Function Polymorphism in Python
There are some functions in Python which are compatible to run with
multiple data types.
One such function is the len() function. It can run with many data types
in Python. Let's look at some example use cases of the function.

Example 2: Polymorphic len() function

print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
Class Polymorphism in Python:
Polymorphism is a very important concept in Object-Oriented
Programming.
We can use the concept of polymorphism while creating class methods as
Python allows different classes to have methods with the same name.
We can then later generalize calling these methods by disregarding the
object we are working with.
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print("I am a cat. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Meow")

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def info(self):
print("I am a dog. My name is {self.name}. I am {self.age} years old.")

def make_sound(self):
print("Bark")

cat1 = Cat("Kitty", 2.5)


dog1 = Dog("Fluffy", 4)

for animal in (cat1, dog1):


animal.make_sound()
animal.info()
animal.make_sound()
Output:
Meow I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark I am a dog. My name is Fluffy. I am 4 years old.
Bark
Inheritance:
Inheritance allows us to define a class that inherits all the
methods and properties from another class.
Parent class is the class being inherited from,
also called base class.
Child class is the class that inherits from another class,
also called derived class.
Create a Parent Class: Any class can be a parent class, so the
syntax is the same as creating any other class:

Example:
#Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

x = Person("John", "Doe")
x.printname()
File I/O:
▪ File is a named location on disk to store related information.
▪ It is used to permanently store data when computer is turned
off, we use files for future use of the data.
File Operation:
▪ Open a file
▪ Read or write
▪ Close the file
File Handling:
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename,
and mode.
There are four different methods (modes) for opening a
file:
"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" - Create - Creates the specified file, returns an error if the file exists
“t” - Opens in text mode
“b”- Opens in binary mode
“+”- Opens a file for updating (reading & writing)
Python Errors & Built-in Exception:
▪ When writing a program, we more often not encounter errors
▪ Error caused by not following the proper structure(syntax) of
the language is called syntax error or passing error.
▪ Errors can also occur at runtime & these are called
exceptions.
▪ E.g. File Not Found Error, Dividing by zero, Import module
error.
Python Exception Handling-Try, Except & Finally:
▪ Python has many built-in exceptions which forces your
program to output an error when something in it goes wrong.
▪ When these exception occurs, it causes the current process to
stop & passes it to the calling process until it is handled.
▪ If not handled, our program will crash, an error message is
spit out & our program came to a sudden, Unexpected halt.
Catching Exceptions in Python:
▪ In python, exception can be handled using a try statement.
▪ A critical operation which can raise exception is placed inside
the try clause and the code that handles exception is written
in except clause.
Numpy , Matplot Library & Pandas

You might also like