Python Programming Notes
Python Programming Notes
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:
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:
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])
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
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)
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
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)
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.
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")
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