0% found this document useful (0 votes)
11 views30 pages

Python Programming Basics and Concepts

The document provides an overview of Python programming, covering its features, variables, data types, operators, decision-making statements, loops, functions, and object-oriented programming concepts. It explains the characteristics of Python, such as being interpreted and dynamically typed, and details how to create and manage variables, use different data types, and implement control structures. Additionally, it introduces the principles of object-oriented programming in Python, including classes, objects, inheritance, and encapsulation.

Uploaded by

manjierrasree11
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views30 pages

Python Programming Basics and Concepts

The document provides an overview of Python programming, covering its features, variables, data types, operators, decision-making statements, loops, functions, and object-oriented programming concepts. It explains the characteristics of Python, such as being interpreted and dynamically typed, and details how to create and manage variables, use different data types, and implement control structures. Additionally, it introduces the principles of object-oriented programming in Python, including classes, objects, inheritance, and encapsulation.

Uploaded by

manjierrasree11
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON VIVA QUESTIONS AND ANSWERS

 INTRODUCTION TO PYTHON

 Python…
 …is a general purpose interpreted programming language.
 …is a language that supports multiple approaches to software design,
 principally structured and object-oriented programming.
 …provides automatic memory management and garbage collection
 …is extensible
 …is dynamically typed

Features of python

i. It is compact and very easy to use OOP language.


ii. It is more capable to express the purpose of the code.
iii. It is interpreted line by line.
iv. No need to download additional libraries.
v. It can run on variety of platform. Thus it is a portable language.
vi. It is free and open source.
vii. Variety of applications
[Link] allows you to split your program into modules that can be reused in other Python programs.

 PYTHON VARIABLES AND ASSIGNMENTS

A variable is a named memory location used to store values.

x = 17 # x gets int value 17


x = 5.3 # x gets float value 5.3

 A variable in Python actually holds a pointer (address) to an object, rather than the object itself.
 You can create a new variable in Python by assigning it a value.
 You don’t have to declare variables, as in many other programming languages.
 An assignment in Python has form:
variable name = value
This means that variable is assigned value. I.e., after the assignment, variable “contains” value.
>>> x = 17.2
>>> y = -39
>>> z = x * y - 2
>>> print ( z )
-672.8

Naming Variables

Below are (most of) the rules for naming variables:


 Variable names must begin with a letter or underscore (“ ”) character.
 After that, use any number of letters, underscores, or digits.
 Case matters: “score” is a different variable than “Score.”
by : Smera N S
 You can’t use reserved words; these have a special meaning to Python and cannot be variable names.

In addition to the rules, there are also some conventions that good programmers follow:

 Variable names should begin with a lowercase letter.


 Choose meaningful names that describe how the variable is used. This helps with program readibility.
 Use max rather than m.
 Use numberOfColumns rather than c.
 One exception is that loop variables are often i, j, etc.
for x in lst : print ( x )
rather than:
for listItem in lst : print ( listItem )

Variable Assignment:

 Assignment Operator:

The equal sign ( = ) is the main Python assignment operator. (The others are augmented assignment
operator.
anInt = -12
aString = 'cart'
aFloat = -3.1415 * (5.0 ** 2)
anotherString = 'shop' + 'ping'
aList = [3.14e10, '2nd elmt of a list', 8.82-4.371j]

Chaining together assignments is:


>>> y = x = x + 1
>>> x, y
(2, 2)

 Augmented Assignment:
the equal sign can be combined with an arithmetic operation and the resulting value reassigned to the
existing
variable. Known as augmented assignment:
x=x+1
... can now be written as ...
x += 1

 Multiple Assignment:
>>> x = y = z = 1
>>> x
1
>>> y
1
>>> z
1

 "Multuple" Assignment:
>>> x, y, z = 1, 2, 'a string'
>>> x
1
>>> y
2
by : Smera N S
>>> z
'a string'
\

Python Reserved Words:


and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import,
in, is, lambda, nonlocal, None, not, or, pass, raise, return, True, try, while, with, yield
IDLE and many IDEs display reserved words in color to help you easily recognize them.

 DATA TYPES IN PYTHON

i. Numbers
ii. Strings
iii. Lists
iv. Dictionaries
v. Tuples
vi. Files
vii. Sets

Numbers : Can be integers, decimals (fixed precision), floating points (variable precision), complex
numbers etc. Simple assignment creates an object of number type such as:
•a=3
• b = 4.56
Strings : A string object is a ‘sequence’, i.e., it’s a list of items where each item has a defined position.
Each character in the string can be referred, retrieved and modified by using its position. This order id
called the ‘index’ and always starts with 0

• String objects support concatenation and repetition operations

Lists and Tuples:

 These are compound data types of Python


 But there is one difference, list can be modified but tuples cannot be modifies.
 A list in the python represents a list of comma-separated values of any data type between square
brackets.
 The following are some examples of List:
by : Smera N S
[1,3,5,7,9]
[“Amit”, “Sumit”, “Rajiv”, “Gaurav”]
[‘Namrata’, 202,404,302]

 Tuples are represented as a list of comma separated values of any data types within parenthesis.

Example:
X= (1, 2, 3, 4, 5, 6, 7, 8)
Y= (‘a’, ‘e’, ‘i’, ‘o’, ‘u’)

 List can be nested also. Example:


Head = [[‘A’, ‘B’, ‘C’, ‘D’, ‘E’,], [0,1,2,3,4,5,6,7]]
List = [‘x’, ‘y’, ‘z’]
 List can be concatenated by using ‘+’ operator i.e.
>>> Head[1]+List would produce
[0,1,2,3,4,5,6,7,’x’, ‘y’, ‘z’]

 To obtain the length of list following len command can be issue:


>>> print len(Head)

 In addition, you can use the augmented addition assignment to add items to the list, but you must
specify a list as the object to be added, as in the following example:
>>>List += [8]

Dictionary: The dictionary is the list of unordered set of comma separated value with the combination
of key: value pair. It is declared within parenthesis
{}. For example:
V = {‘a’:1, ‘e’:2, ‘i’:3, ‘o’:4, ‘u’:5}

 OPERATORS

Python divides the operators in the following groups:

a. Arithmetic operators
b. Assignment operators
c. Comparison operators
d. Logical operators
e. Identity operators
f. Membership operators
g. Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

by : Smera N S
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

by : Smera N S
!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result not(x < 5 and x < 10)
is true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:

Operator Description Example

is Returns True if both variables are the same x is y


object

is not Returns True if both variables are not the x is not y


same object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object
by : Smera N S
Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers

Operator Name Description Example

& AND Sets each bit to 1 if both bits x&y


are 1

| OR Sets each bit to 1 if one of two x|y


bits is 1

^ XOR Sets each bit to 1 if only one of x^y


two bits is 1

~ NOT Inverts all the bits ~x

<< Zero fill Shift left by pushing zeros in x << 2


left shift from the right and let the
leftmost bits fall off

>> Signed Shift right by pushing copies of x >> 2


right the leftmost bit in from the left,
shift and let the rightmost bits fall
off

 DECISION MAKING STATEMENTS AND LOOPS

 Decision making statements

a. If statements
b. If else statement
c. Nested if else statement
d. if-elif-else Ladder

If statements in python

The if keyword is followed by an indented block of statements that are executed if the condition is
assessed and found to be [Link] not, the code skips the if block.

Syntax
if expression:
statement(s)

Example
num = 8if num > 0:
print("The number is positive.")

by : Smera N S
If else statement in python

If the condition in the if block evaluates to false, the if-else statement executes an alternate block of
code.
This block of alternatives is introduced by the else keyword.

Syntax
if expression:
statement(s)
else:
statement(s)

Nested if else statement in Python

Python enables the nesting of decision-making statements, which facilitates the development of
more complex decision logic.A hierarchy of conditions can be created by an if or if-else block within
another if or if-else block.

Syntax
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)else:
statement(s)

Python if-elif-else Ladder

An if-elif-else ladder is an order of if statements connected by elif [Link] enables you to check
for numerous conditions and run separate code blocks based on which condition is met.
Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
elif condition3:
# code block 3
else:
# default code block

by : Smera N S
 LOOPS

[Link]. Name of Loop Type & Description


the loop

1 While loop Repeats a statement or group of statements while a given


condition is TRUE. It tests the condition before executing the
loop body.

2 For loop This type of loop executes a code block multiple times and
abbreviates the code that manages the loop variable.

3 Nested We can iterate a loop inside another loop.


loops

Loop Control Statements

The Loop control statements change the execution from its normal sequence. When the execution
leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports
the following control statements.

break statement
continue statement
pass statement

1. break statement:
Terminates the loop statement and transfers execution to the statement immediately following the
loop.
2. continue statement:
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
3. pass statement:
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute..

 PYTHON FUNCTIONS

 A function is a block of code in Python that performs a particular task.


 It may take zero or more inputs and may or may not return one or more outputs.
 Functions are reusable and can be called from anywhere in the program.

Different Types of Functions in Python

a) Built-in Functions in Python


b) User-defined Functions in Python
c) Recursive Functions in Python

by : Smera N S
. Built-in Functions: These functions are built into the Python language and can be used without the
need for additional code. Some examples of built-in functions are print(), len(), sum(), min(), max(), etc.

·User-defined Functions: You create these functions to perform a specific task. You can define your
functions using the def keyword followed by the function name, parameter(s), and the code block that
performs the desired operation.

·Recursive Functions: These functions call themselves to perform a task repeatedly until a certain
condition is met. Recursive functions can be useful in situations where a problem can be broken
down into smaller sub-problems.

by : Smera N S
MODULE 2

 Python OOPs Concepts

Like other general-purpose programming languages, Python is also an object-oriented language


since its beginning. It allows us to develop applications using an Object-Oriented approach.
In Python, we can easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The object is
related to real-word entities such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve the problem by creating objects.

Major principles of object-oriented programming system are given below.

o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation

Class

The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain an
attribute and method, i.e. an email id, name, age, salary, etc.

Syntax

class ClassName:
<statement-1>
.
.
<statement-N>

Object

The object is an entity that has state and behavior. It may be any real-world object like the mouse,
keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the function
source code.

by : Smera N S
When we define a class, it needs to create an object to allocate the memory. Consider the
following example.

Example:

class car:
def __init__(self,modelname, year):
[Link] = modelname
[Link] = year
def display(self):
print([Link],[Link])

c1 = car("Toyota", 2016)
[Link]()

Method

The method is a function that is associated with an object. In Python, a method is not unique to
class instances. Any object type can have methods.

Inheritance

Inheritance is the most important aspect of object-oriented programming, which simulates the
real-world concept of inheritance. It specifies that the child object acquires all the properties and
behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and behavior of another
class. The new class is known as a derived class or child class, and the one whose properties are
acquired is known as a base class or parent class.

It provides the re-usability of the code.

Polymorphism

Polymorphism contains two words "poly" and "morphs". Poly means many, and morph means
shape. By polymorphism, we understand that one task can be performed in different ways. For
example - you have a class animal, and all animals speak. But they speak differently. Here, the
"speak" behavior is polymorphic in a sense and depends on the animal. So, the abstract "animal"
concept does not actually "speak", but specific animals (like dogs and cats) have a concrete
implementation of the action "speak".

Encapsulation

Encapsulation is also an essential aspect of object-oriented programming. It is used to restrict


access to methods and variables. In encapsulation, code and data are wrapped together within a
single unit from being modified by accident.

by : Smera N S
Data Abstraction

Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonyms
because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities. Abstracting something
means to give names to things so that the name captures the core of what a function or a whole
program does

 Object-oriented vs. Procedure-oriented Programming languages


The difference between object-oriented and procedure-oriented programming is given below:

Index Object-oriented Programming Procedural Programming

1. Object-oriented programming is the problem- Procedural programming uses a list of


solving approach and used where computation instructions to do computation step by step.
is done by using objects.

2. It makes the development and maintenance In procedural programming, It is not easy to


easier. maintain the codes when the project becomes
lengthy.

3. It simulates the real world entity. So real-world It doesn't simulate the real world. It works on
problems can be easily solved through oops. step by step instructions divided into small
parts called functions.

4. It provides data hiding. So it is more secure than Procedural language doesn't provide any
procedural languages. You cannot access private proper way for data binding, so it is less
data from anywhere. secure.

5. Example of object-oriented programming Example of procedural languages are: C,


languages is C++, Java, .Net, Python, C#, etc. Fortran, Pascal, VB etc.

ADVERTISEMENT

by : Smera N S
 Classes and Objects in Python

Classes in Python:

In Python, a class is a user-defined data type that contains both the data itself and the methods
that may be used to manipulate it. In a sense, classes serve as a template to create objects. They
provide the characteristics and operations that the objects will employ.

Creating Classes in Python

In Python, a class can be created by using the keyword class, followed by the class name.

Syntax

class ClassName:

#statement_suite

Objects in Python:

An object is a particular instance of a class with unique characteristics and functions. After a class
has been established, you may make objects based on it.

By using the class constructor, you may create an object of a class in Python. The object's
attributes are initialized in the constructor, which is a special procedure with the name __init__.

Syntax:

# Declare an object of a class


object_name = Class_Name(arguments)

The self-parameter

The self-parameter refers to the current instance of the class and accesses the class variables. We
can use anything instead of self, but it must be the first parameter of any function which belongs
to the class.

_ _init_ _ method

 In order to make an instance of a class in Python, a specific function called __init__ is called.
 Although it is used to set the object's attributes, it is often referred to as a constructor.
 The self-argument is the only one required by the __init__ method. This argument refers to
the newly generated instance of the class. To initialise the values of each attribute
associated with the objects, you can declare extra arguments in the __init__ method.

by : Smera N S
Note: The __init__() function is called automatically every time the class is being used to create a
new object.

The __str__() Function

 The __str__() function controls what should be returned when the class object is represented as a
string.

 If the __str__() function is not set, the string representation of the object is returned:

 Python Constructor

A constructor is a special type of method (function) which is used to initialize the instance
members of the class.

In C++ or Java, the constructor has the same name as its class, but it treats constructor differently
in Python. It is used to create an object.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Constructor definition is executed when we create the object of this class. Constructors also verify
that there are enough resources for the object to perform any start-up task.

Creating the constructor in python

In Python, the method the __init__() simulates the constructor of the class. This method is called
when the class is instantiated. It accepts the self-keyword as a first argument which allows
accessing the attributes or method of the class.

We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a
constructor, even if it simply relies on the default constructor.

Python Non-Parameterized Constructor

The non-parameterized constructor uses when we do not want to manipulate the value or the
constructor that has only self as an argument. Consider the following example.

Example

class Student:
# Constructor - non parameterized
def __init__(self):

by : Smera N S
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link]("John")

Python Parameterized Constructor

The parameterized constructor has multiple parameters along with the self. Consider the
following example.

Example

class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link])
student = Student("John")
[Link]()

Python Default Constructor

When we do not include the constructor in the class or forget to declare it, then that becomes
the default constructor. It does not perform any task but initializes the objects. Consider the
following example.

Example

class Student:
roll_num = 101
name = "Joseph"

def display(self):
print(self.roll_num,[Link])

st = Student()
[Link]()

by : Smera N S
 File Handling
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

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("[Link]")

The code above is the same as:

f = open("[Link]", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error

To open the file, use the built-in open() function.


The open() function returns a file object, which has a read() method for reading the content of
the file:

f = open("[Link]", "r")
print([Link]())

by : Smera N S
Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Open the file "[Link]" and append content to the file:

f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())

Open the file "[Link]" and overwrite the content:

f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()

#open and read the file after the overwriting:


f = open("[Link]", "r")
print([Link]())

Delete a File

To delete a file, you must import the OS module, and run its [Link]() function:

Remove the file "[Link]":

import os
[Link]("[Link]")

 What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

by : Smera N S
Create a Module

To create a module just save the code you want in a file with the file extension .py:

Save this code in a file named [Link]

def greeting(name):
print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example

Import the module named mymodule, and call the greeting function:

import mymodule

[Link]("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):

Example

Save this code in the file [Link]

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

by : Smera N S
Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example

Import and use the platform module:

import platform

x = [Link]()
print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:

Example

List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example

by : Smera N S
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module name when referring to
elements in the module. Example: person1["age"], not mymodule.person1["age"]

 Python 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):
[Link] = fname
[Link] = lname

def printname(self):
print([Link], [Link])

#Use the Person class to create an object, and then execute the printname method:

by : Smera N S
x = Person("John", "Doe")
[Link]()

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:

Example

Create a class named Student, which will inherit the properties and methods from
the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or methods to
the class.

Now the Student class has the same properties and methods as the Person class.

Example

Use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Olsen")
[Link]()

Add the __init__() Function

So far we have created a child class that inherits the properties and methods from its parent.

We want to add the __init__() function to the child class (instead of the pass keyword).

Note: The __init__() function is called automatically every time the class is being used to create a
new object.

Example

Add the __init__() function to the Student class:

class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the parent's __init__() function.

by : Smera N S
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example

class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance of the parent
class, and we are ready to add functionality in the __init__() function.

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:

Example

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)

By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.

Add Properties
Example
Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
[Link] = 2019

In the example below, the year 2019 should be a variable, and passed into the Student class when
creating student objects. To do so, add another parameter in the __init__() function:

Example

Add a year parameter, and pass the correct year when creating objects:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

x = Student("Mike", "Olsen", 2019)

by : Smera N S
Add Methods
Example
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
[Link] = year

def welcome(self):
print("Welcome", [Link], [Link], "to the class of", [Link])

If you add a method in the child class with the same name as a function in the parent class, the
inheritance of the parent method will be overridden.

 Types of Inheritance in Python


Types of Inheritance depend upon the number of child and parent classes involved. There are
four types of inheritance in Python:

i. Single Inheritance:

Single inheritance enables a derived class to inherit properties from a single parent class, thus
enabling code reusability and the addition of new features to existing code.

ii. Multiple Inheritance:

When a class can be derived from more than one base class this type of inheritance is called
multiple inheritances. In multiple inheritances, all the features of the base classes are inherited
into the derived class.

iii. Multilevel Inheritance :

by : Smera N S
In multilevel inheritance, features of the base class and the derived class are further inherited
into the new derived class. This is similar to a relationship representing a child and a
grandfather.

iv. Hierarchical

When more than one derived class are created from a single base this type of inheritance is
called hierarchical inheritance. In this program, we have a parent (base) class and two child
(derived) classes.

v. Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

by : Smera N S
 EXCEPTION HANDLING

Python Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Exception Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.

These exceptions can be handled using the try statement:

Example

The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example

This statement will raise an error, because x is not defined:

print(x)

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block
of code for a special kind of error:

Example

Print one message if the try block raises a NameError and another for other errors:

try:
print(x)

by : Smera N S
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Else

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example

In this example, the try block does not generate any error:

try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

Example

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

This can be useful to close objects and clean up resources:

Example

Try to open and write to a file that is not writable:

try:
f = open("[Link]")
try:
[Link]("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
[Link]()
except:
print("Something went wrong when opening the file")

The program can continue, without leaving the file object open.

by : Smera N S
Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

Raise a TypeError if x is not an integer:

x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

Python Built-in Exceptions


Built-in Exceptions

The table below shows built-in exceptions that are usually raised in Python:

Exception Description

ArithmeticError Raised when an error occurs in numeric calculations

AssertionError Raised when an assert statement fails

AttributeError Raised when attribute reference or assignment fails

Exception Base class for all exceptions

EOFError Raised when the input() method hits an "end of file" condition (EOF)

FloatingPointError Raised when a floating point calculation fails

GeneratorExit Raised when a generator is closed (with the close() method)

by : Smera N S
ImportError Raised when an imported module does not exist

IndentationError Raised when indentation is not correct

IndexError Raised when an index of a sequence does not exist

KeyError Raised when a key does not exist in a dictionary

KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete

LookupError Raised when errors raised cant be found

MemoryError Raised when a program runs out of memory

NameError Raised when a variable does not exist

NotImplementedError Raised when an abstract method requires an inherited class to override the
method

OSError Raised when a system related operation causes an error

OverflowError Raised when the result of a numeric calculation is too large

ReferenceError Raised when a weak reference object does not exist

RuntimeError Raised when an error occurs that do not belong to any specific exceptions

StopIteration Raised when the next() method of an iterator has no further values

SyntaxError Raised when a syntax error occurs

TabError Raised when indentation consists of tabs or spaces

SystemError Raised when a system error occurs

SystemExit Raised when the [Link]() function is called

TypeError Raised when two different types are combined

UnboundLocalError Raised when a local variable is referenced before assignment

UnicodeError Raised when a unicode problem occurs

UnicodeEncodeError Raised when a unicode encoding problem occurs

UnicodeDecodeError Raised when a unicode decoding problem occurs

UnicodeTranslateError Raised when a unicode translation problem occurs

ValueError Raised when there is a wrong value in a specified data type

ZeroDivisionError Raised when the second operator in a division is zero

User Defined Exceptions

Python also allows you to create your own exceptions by deriving classes from the standard
built-in exceptions.

by : Smera N S
Here is an example that has a user-defined MyException class. Here, a class is created that is
subclassed from base Exception class. This is useful when you need to display more specific
information when an exception is caught.

In the try block, the user-defined exception is raised whenever value of num variable is less than
0 or more than 100 and caught in the except block. The variable e is used to create an instance
of the class MyException.

Example

class MyException(Exception):
"Invalid marks"
pass

num = 10try:
if num <0 or num>100:
raise MyExceptionexcept MyException as e:
print ("Invalid marks:", num)else:
print ("Marks obtained:", num)

Output

For different values of num, the program shows the following output −

Marks obtained: 10
Invalid marks: 104
Invalid marks: -10

by : Smera N S

Common questions

Powered by AI

Inheritance in Python allows a child class to inherit attributes and methods from a parent class, enhancing code reuse by enabling new classes to be built on existing ones. This avoids redundancy, promotes efficient code organization, and simplifies maintenance. The 'super()' function plays a crucial role in inheritance by allowing child classes to call methods from their parent class without explicitly naming it. This includes the parent class's __init__() method, which can be called by the child's __init__() to ensure attributes from the parent are properly initialized. This makes inheritance relationships flexible and the codebase more modular and organized .

Dictionaries in Python are collections of key-value pairs, providing a means of storing data that is accessible via unique keys rather than by index. Unlike lists and tuples, dictionaries are unordered and mutable, allowing for dynamic updates to the data structure. Lists are ordered and allow duplicate elements; tuples are immutable and also ordered, but neither supports key-based access like dictionaries. This key-value approach makes dictionaries particularly useful for managing associative arrays and datasets where direct access to data by specific identifiers is necessary, significantly enhancing data retrieval efficiency and context-specific operations .

Control statements manage the flow of loops in Python. 'Break' is used to exit a loop prematurely if a certain condition is met, typically used when a required result is found or an error condition arises during iteration. 'Continue' is used to skip the remainder of the loop's current iteration and immediately proceed to the next iteration, which is useful for bypassing unwanted elements in a sequence. 'Pass' is a placeholder used when a statement is syntactically required but no code needs to be executed; it's often used in scenarios where future implementation is planned but not yet defined. These statements afford precise control over loop execution, facilitating refined logic and efficient program management .

The __init__() method in Python acts as a constructor and is a special method used to initialize the attributes of a class. When a class is instantiated to create an object, the __init__() method is automatically called. It routinely takes 'self' as its first parameter, which represents the newly created instance, and additional parameters can be used to initialize object attributes. This method provides flexibility when instantiating objects with initial conditions or specific parameters, making it a pivotal part of setting up the internal state of new objects .

Lists and tuples are both sequence data types in Python, yet they have key differences. Lists are mutable, which means their elements can be modified, added, or removed, making them suitable for collections of items that may need changing. They are defined using square brackets, e.g., [1, 2, 3]. In contrast, tuples are immutable; once defined, their elements cannot be altered. This makes them ideal for collections of items that should remain constant, which enhances performance and reduces memory overhead due to their fixed nature. Tuples are defined using parentheses, e.g., (1, 2, 3).

In Python, reserved words have special meanings and cannot be used as identifiers (like variable names). IDEs highlight these reserved words to improve readability and help developers quickly identify special keywords and syntactic elements. This visual distinction aids in the avoidance of syntax errors and reinforces the logical structure of the code, thereby enhancing coding practices by promoting clearer code and reducing debugging time .

Augmented assignment operators in Python are used to simplify operations where a value needs to be updated with a combination of arithmetic operations and assignment. For instance, x += 1 is equivalent to x = x + 1, meaning it updates the variable 'x' by adding 1 to its current value and then reassigns the result to 'x'. They differ from standard assignment operations, which simply reassign a new value to the variable without performing an arithmetic operation first .

Python allows multiple assignments in a single statement, where you can assign the same value to multiple variables or assign different values to multiple variables simultaneously. For example, x = y = z = 1 assigns the value 1 to variables x, y, and z in one line. Additionally, the statement x, y, z = 1, 2, 'a string' assigns different values to x, y, and z respectively. This offers the advantage of cleaner and more concise code as it reduces the number of lines and repetition involved in separately assigning values .

Logical operators in Python (and, or, not) are employed to construct complex conditional logic by combining multiple conditions. 'And' returns True only if both conditions are true; 'or' returns True if at least one condition is true; 'not' inverts the truth value of a condition. These operators allow for the creation of intricate decision-making processes within a program. For instance, a program might check if a user is logged in ('and') has the required privileges ('or') the system is in maintenance mode ('not') to determine access rights. This capability makes logical operators fundamental for efficiently managing control flow and conditions in Python applications .

A 'for' loop in Python iterates over a sequence (such as a list, tuple, or string) and executes a block of code for each item in the sequence. This loop is especially useful when the number of iterations is known. Complex control flows can be created by combining 'for' loops with control statements like 'break', 'continue', and 'pass'. 'Break' exits the loop immediately, 'continue' skips the rest of the code inside the loop for the current iteration and proceeds to the next iteration, while 'pass' does nothing and is a placeholder. Such combinations allow developers to fine-tune loop behavior to avoid unnecessary iterations and handle specific conditions effectively .

You might also like