Python Fundamentals
Python Fundamentals
using
Python-Django
@SSMRV
26th and 27th April 2022
What is Python?
●
Python is a high-level general purpose
programming language
●
Developed by Guido van Rossum in
1991
●
The language has object-oriented
programming constructs
●
Python is dynamically typed and
manages memory functionalities using
private help containers
●
It also supports procedural, functional programming tasks
●
Python has access to comprehensive libraries and
standard tools for software development and is known as
a maintained language.
●
The language can be used on many operating systems for
frontend and backend web development and was last updated
to series 3.0 in 2008
Examples of imperative languages are Pascal, C, Java, etc.
Examples of declarative languages are ML, pure Lisp and pure Prolog.
Filename: Hello.c
// Simple C Program to Display “Addition of Two
Numbers"
int a = 5;
#include <stdio.h>
int main()
{ Dataty Value
pe
int a = 5;
int b = 6;
int sum;
sum = a+b;
printf(“The addition is %d!“, sum); Variable_na
me
return 0;
}
Filename: Hello.c
// Simple C Program to Display “Addition of Two
Numbers"
int a = 5; int b = 6; int sum;
#include <stdio.h>
int main() a b sum
{
int a = 5;
5 6
int b = 6; 12214 12214 12216
int sum; 54 78 82
sum = a+b;
printf(“The addition is %d!“, sum);
return 0;
}
Filename: Hello.c
// Simple C Program to Display “Addition of Two
Numbers"
int a = 5; int b = 6; int sum;
#include <stdio.h>
int main() a b sum
{
int a = 5;
5 + 6 = 11
int b = 6; 1221454 1221478 1221682
int sum;
sum = a+b;
printf(“The addition is %d!“, sum);
return 0;
}
Filename: Hello.c
Rules for framing a variable:
No Reserved words
4
Example 1 >>> a = b = c = 1
Example 2 >>> a, b = 2 , 3
Example 4 >>> a, b = b, a
Python input()
input():
input() reads a value from user input.
input() is a built-in Python function which prompts user to enter some text input.
If we call input(), the program will stop at that point and waits until user inputs some information.
Program will resume once the user presses ENTER key
input() always read the string data
Syntax:
input([Optional])
Example:
age = input("How old are you? ")
print ("Your age is", age)
print ("You have", 65 - age, "years until retirement“)
Command Line Arguments:
Python also supports command line arguments which we can pass during run time
sys module is used for passing the command line arguments
Operators
➢
Python operator is a symbol that performs an operation on one or more operands.
➢
An operand is a variable or a value on which we perform the operation.
➢
The standard mathematical operators that you are familiar with work the same way in Python as in
most other languages.
➢
Python Operator falls into 7 categories
➢
Python language supports the following types of operators.
●
Arithmetic Operators (+ - * / // % **)
●
Comparison (Relational) Operators (> < == <= >= != )
●
Assignment Operators (= += -= /= *= //= **=)
●
Logical Operators (and or not)
●
Bitwise Operators ( & | ^ << >> ~)
●
Membership Operators ( in not in)
●
Identity Operators (is is not)
Expressions and Statements
>>> x = 5
>>> x+5
>>>6+4/4*10/5
10
Exponentiation
✔
Addition and Substraction (Operators with the same precedence are evaluated from left to right)
✔
Comments
Indentation
✔
Most languages don’t care about indentation
✔
Most humans do
✔
We tend to group similar things together
/* C Code */
If (foo) {
If (bar) {
baz(foo, bar);
}
else {
qux();
} }
Basic Statements: The If Statement (1)
If statements have the following basic structure:
# inside the interpreter # inside a script
>>> if condition: if condition:
... action .. action
Subsequent indented lines are assumed to be part of the if statement. The same is true for most other types of python statements.
A statement typed into an interpreter ends once an empty line is entered, and a statement in a script ends once an unindented line
appears. The same is true for defining functions.
If statements can be combined with else if (elif) and else statements as follows:
if condition1: # if condition1 is true, execute action1
action1
elif condition2: # if condition1 is not true, but condition2 is, execute
action2 # action2
else: # if neither condition1 nor condition2 is true, execute
action3 # action3
Conti...
Nested if Statement
If statment
Syntax:
Syntax: if expression:
if expression: statement(s)
elif expression:
statement(s)
statement(s)
else:
statement(s)
Example:
num = 3 Example:
num = 75
if num > 0:
if num >100:
print(num, "is a positive number.")
print(num, "is a greater than 100")
print("This is always printed.") elif num < 50:
num = -1 print(num, “less than 50”)
if num > 0: else:
print(num, "is a positive number.") print (num,”less than 50 )
As long as the condition is true, the while statement will execute the action
Example:
>>> x = 1
>>> while x < 4: # as long as x < 4...
... print x**2 # print the square of x
... x = x+1 # increment x by +1
...
1 # only the squares of 1, 2, and 3 are printed, because
4 # once x = 4, the condition is false
9
>>>
Continuation (\)
Python statements are in general, delimited by NEWLINEs, meaning one statement per line.
➢
Single statements can be broken up into multiple lines by use of the backslash.
➢
➢
The backslash symbol ( \ ) can be placed before a NEWLINE to continue the current
statement onto the next line.
Example:
# check conditions
If (weather_is_hot == 1) and \
(shark_warnings == 0):
send_goto_beach_mesg_to_pager()
Multiple Statements Groups as Suites (:)
➢
Groups of individual statements making up a single code block are called
"suites" in Python.
➢
Compound or complex statements, such as if , while , def , and class , are
those that require a header line and a suite.
➢
We will refer to the combination of a header line and a suite as a clause.
Examples:
➢
➢If condition :
pass
➢ While condition:
pass
➢ def name() :
pass
Multiple Statements on a Single Line ( ; )
➢
The semicolon ( ; ) allows multiple statements on a single line given that neither statement
starts a new code block.
Example:
➢
A = 10
B = “RVCE”
C= A=A+1
C = (A = A + 1) <--- Error (Its Not Expression
●
Augmented Assignment
Beginning in Python 2.0, the equal sign can be combined with an arithmetic operation and the resulting value reassigned to the existing
variable. Known as augmented assignment, statements
●
Example:
x = x + 1 ==> x += 1
+= -= <<= >>= *= &= /= ^= |= %= **=
Python Identifiers
➢
A Python identifier is a name used to identify a
➢ Variables,
➢ Functions,
➢ Class,
➢ Modules or
➢ Other object.
➢
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
➢
Python does not allow punctuation characters such as @, $, and % within identifiers.
➢
Python is a case sensitive programming language.
➢
Thus, RVCE and rvce are two different identifiers in Python.
➢ First character must be a letter or underscore ( _ )
➢ Any additional characters can be alphanumeric or underscore
➢ Case-sensitive
Data Types
Data Types
●
Data type determines the set of values that a data item can take and the operations that can be performed on the item.
●
Python language provides Six basic data types.
List
Sets
1. Numbers
✔
A particular kind of data item, as defined by the values it can take, the programming language used, or the operations that can be performed
on it
✔
Number data types store numeric values.
✔
They are immutable data types
✔
Example: Var = 1
Var = 2
➢
int
➢
long
➢
float
➢
complex
Cont... (numbers)
int long float complex
✔
Type int(x) :convert x to a plain integer.
✔
Type long(x) :convert x to a long integer.
✔
Type float(x) :convert x to a floating-point number.
✔
Type complex(x) :convert x to a complex number with real part x and imaginary part zero.
✔
Type complex(x, y) :convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions
Mathematical Functions:
abs(x), random.random(), log(x) , choice(seq), etc........
2. String
✔
Strings are enclosed in single or double quotation marks
✔
Double quotation marks allow the user to extend strings over multiple lines
without backslashes, which usually signal the continuation of an expression
✔
Examples: 'abc', “ABC”, “””ABC”””
Concatenation and repetition
Strings are concatenated with the + sign:
>>> 'abc'+'def'
'abcdef'
Strings are repeated with the * sign:
>>> 'abc'*3
'abcabcabc'
String Operatons
>>>s = “GPRMC,235316.000,A,4003.9040,N,10512.5792,W,0.09,144.75,141112,,*19”
➢
>>>a, b
➢
output:
('4003.9040', '10512.5792')
➢
>>>a=float(a), b=float(b)
Output:
(4003.904, 10512.5792)
3. Lists:
Basic properties:
✔
Lists are contained in square brackets []
✔
Lists can contain numbers, strings, nested sublists, or nothing
Examples:
L1 = [0,1,2,3]
✔
L2 = ['zero', 'one']
✔
L3 = [0,1,[2,3],'three',['four,one']]
✔
L4 = []
✔
✔
List indexing works just like string indexing
✔
Lists are mutable: individual elements can be reassigned in place. Moreover, they can grow and shrink in
place
✔
Example:
>>> L1 = [0,1,2,3]
>>> L1[0] = 4
>>> L1[0]
4
List Operations
Examples:
✔
t1 = (0,1,2,3),
✔
t2 = ('zero', 'one'),
✔
t3 = (0,1,(2,3),'three',('four,one')),
t4 = ()
✔
As long as you're not nesting tuples, you can omit the parentheses
✔
Concatenation:
✔
>>> t1*2
(0,1,2,3,0,1,2,3)
Length: len(t1) (this also works for lists and strings)
✔
Tuple:
✔
Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces.
Empty dictionary = {}
✔
Keys are unique within a dictionary while values may not be.
✔
✔
The values of a dictionary can be of any type, but the keys must be of an immutable data
type such as strings, numbers, or tuples.
Example:
✔
✔
A set itself may be modified, but the elements contained in the set must be of an
immutable type.
Example:
✔
a = {1, 2, 3, 5, 6, 'RVCE'}
Operation on Sets
>>> print_hello("hello","how r
u")
hello how r u
Parameter Passing >>> def argdemo(nlist):
●
Pass by Reference by default nlist.append(['r','v','c','e'])
print("LIST INSIDE",nlist)
Return
>>> nlist=[1,2,3]
>>> nlist
[1, 2, 3]
>>> argdemo(nlist)
LIST INSIDE [1, 2, 3, ['r', 'v', 'c',
'e']]
>>> nlist
[1, 2, 3, ['r', 'v', 'c', 'e']]
Types of parameter passing
●
Function can take four different types of arguments
Required arguments
Keyword arguments
Default argumets
Variable length argumets
Required Arguments
Arguments must be passed in correct number and order during function call
def concat(b,a):
print ("Message from the function\n")
c=a+b
print (c)
concat(a="MCA ",b= "2")
Default Arguments
Arguments will take the default value if no argument value is passed during function call
defaultargument(a="Miki",b= "26")
defaultargument(a="Miki")
Variable number of Arguments
Variable number of arguments can be passed based on requirement during function call
●
Procedural language is based on functions but object oriented language is based on real
world objects.
●
Procedural language gives importance on the sequence of function execution but object
oriented language gives importance on states and behaviors of the objects.
●
Procedural language exposes the data to the entire program but object oriented language
encapsulates the data.
●
Procedural language follows top down programming paradigm but object oriented
language follows bottom up programming paradigm.
●
Procedural language is complex in nature so it is difficult to modify, extend and maintain
but object oriented language is less complex in nature so it is easier to modify, extend and
maintain.
●
Procedural language provides less scope of code reuse but object oriented language provides
more scope of code reuse.
Encapsulation
●
Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP)
●
It describes the idea of wrapping data and the methods that work on
data within one unit
●
This puts restrictions on accessing variables and methods directly
and can prevent the accidental modification of data.
●
To prevent accidental change, an object’s variable can only be
changed by an object’s method.
●
Those types of variables are known as private
Variable
●
A class is an example of encapsulation as it
encapsulates all the data that is member
functions, variables, etc.
Methods Variables
Class
Class
●
A class is a user-defined blueprint or prototype from which objects are
created.
●
Classes provide a means of bundling data and functionality together.
●
Creating a new class creates a new type of object, allowing new
instances of that type to be made.
●
Each class instance can have attributes attached to it for maintaining
its state.
●
Class instances can also have methods (defined by their class) for
modifying their state
Class members
(Data member and Member function)
Data Members:
●
Variables defined in a class are called data memebers.
●
There are 2 types of variables: Class Variables and Instance Variables
– Class variable:
●
The variables accessed by all the objects(instances) of a class are called class variables.
●
There is only copy of the class variable and when any one object makes a change to a class variable, the
change is reflected in all the other instances as well.
●
Class variables can be accessed using the syntax
– Class_name.Class variable
– Object_name. Class variable
– Object/instance Variable:
●
Variables owned by each individual object (instance of a class) are called object variables.
●
Each object has its own copy of the field i.e. they are not shared and are not related in any way to the
field by the same name in a different instance of the same class.
●
Note: if user changes the value of class variable using class name, then it reflects
to all objects if user changes the value of class variable using object name, then it
reflects only to that objects
Member Function(method)
Member function(method):
●
A method is a function that is defined inside a class.
●
Methods are members of classes.
●
A method is a function that is available for a given object.
●
There are different types of methods like
– Class methods,
– Instance methods,
– Service methods, and
– Support methods.
Class method:
●
A "class method" is a method where the initial parameter is not an instance object(self), but the class object , which by
convention is called cls .
●
This is implemented with the @classmethod decorator.
●
The class method does not require object to invoke it.
Instance Method:
●
An "Instance method" is a method where the initial parameter is an instance of object(self) and requires no decorator.
●
These are the most common methods used.
Object
●
An Object is an instance of a Class.
●
An object consists of :
– State: It is represented by the attributes of an object. It also
reflects the properties of an object.
– Behavior: It is represented by the methods of an object. It
also reflects the response of an object to other objects.
– Identity: It gives a unique name to an object and enables
one object to interact with other objects.
●
Identify: name of the pen
●
State/Attributes: color, height, type
●
Behaviour: weight, volume calculation , etc. ,
The self
●
Class methods must have an extra first
parameter in the method definition.
●
We do not give a value for this parameter
when we call the method, Python provides it.
●
If we have a method that takes no arguments,
then we still have to have one argument.
__init__ method
●
The __init__ method is the constructor that is used to
initializing the object’s state.
●
A constructor also contains a collection of statements(i.e.
instructions) that are executed at the time of Object
creation.
●
It runs as soon as an object of a class is instantiated.
●
The method is useful to do any initialization you want to do
with your object
Inheritance
Inheritance
●
Inheritance is the ability to define a new class which is a modified version of an existing class.
●
The primary advantage of this feature is that you can add new methods to a class without modifying the existing class.
●
The existing class is called as Super Class/Parent class.
●
A Subclass, "derived class", their class, or child class is a derivative class which inherits the properties (methods and attributes) from one are
more super classes.
●
Inheritance is a powerful feature of Object Oriented Programming.
●
Inheritance can facilitate code reuse, since you can customize the behavior of parent classes without having to modify them.
●
Disadvantage of inheritance is that it make programs difficult to read.
●
When a method is invoked, it is sometimes not clear where to find its definition.
●
The relevant code may be scattered among several modules.
●
In Inheritance base class and child classes are tightly coupled. Hence If you change the code of parent class, it will get affects to the all the child
classes.
Polymorphism
Polymorphism
●
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form.
●
A language that features polymorphism allows developers to program in the general rather than program in
the specific.
●
In a programming language that exhibits polymorphism, objects of classes belonging to the same
hierarchical tree (inherited from a common base class) may possess functions bearing the same name, but
each having different behaviors
●
Polymorphism is mainly divided into two types:
– Static or Compile Time Polymorphism
●
Operator Overloading
●
Function Overloading
– Dynamic or Runtime Polymorphism
Polymorphism
●
Association of method call to the method body is known as binding.
●
There are two types of binding:
– Static Binding that happens at compile time
●
Examples:
– Operator Overloading
– Function Overloading
– Dynamic Binding that happens at runtime.
●
Example:
– Method Overriding
Method overriding
●
Method overriding is an ability of any object-oriented programming language that allows a subclass or child
class to provide a specific implementation of a method that is already provided by one of its super-classes or
parent classes.
●
When a method in a subclass has the same name, same parameters or signature and same return type(or sub-
type) as a method in its super-class, then the method in the subclass is said to override the method in the super-
class.