Learn Python Step by Step Fast and Free

Learn Python Step by Step Fast and Free

Want to learn Python step by step manner fast and free? This blog post will guide you to learn python. Python is a very easy language as compared to its counterparts. Yet it is the most powerful language in the Artificial Intelligence and Machine learning domain. It can also be used to build a quick prototype.

Goals Let’s touch on a few important goals of these tutorials before we get started. For instance, books will skip programming style sections, common pitfalls, debugging, good /bad programming practices and debugging. This tutorial covers best programming practice exercises and programs for you to learn and understand easily.

This Blog Tutorial consists of a lot of daily life example programs for the understanding of concepts, which helps learners to understand in an effective and better way. Provide practice programs at the end of tutorial documents.

Python Introduction

Python is a language of programming that is interpreted in general, interactive, object-oriented, and high-level terms. Guido van Rossum created it during the period from 1985-1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding of Python programming language.

Benefits of Python over other languages:

Python is a scripting language of a high standard, interpreted, interactive and object-oriented. Python is designed to be extremely legible. It frequently uses English keywords where punctuation is used as other languages, and it has fewer syntactical constructions than other languages.

Python is a MUST to become a great Software Engineer, especially when working in the Web Development Domain for students and working professionals. I’ll outline some of the key benefits of learning Python

Today Python has multiple implementations including JPython, scripted for Java Virtual Machine in Java language; Iron Python, written for Common Language Infrastructure in C #, and PyPy, written in Python and translated into C. To be noted, the default and most popular implementation of Python is Python which is written in C and developed by the Python Software Foundation. Though these implementations work in the native language in which they are written, they are also able to interact with other languages by using modules. Most of these modules work on the model of community development and are open source and free of charge.

Applications of Python

  • GUI based desktop applications
  • Image processing and graphic design applications
  • Scientific and computational applications
  • Games
  • Web frameworks and web applications
  • Enterprise and business applications
  • Operating systems
  • Language development
  • Prototyping
  • It can be used as the major source of implementation of Machine Learning Algorithms and for Artificial Intelligence.

How to install Python on PC

Open a browser window and navigate to the Download page for Windows at python.org.

Underneath the heading at the top that says Python Releases for Windows, click on the link for the Latest Python 3 Release – Python 3.x.x. (As of this writing, the latest is Python 3.6.5.)

Scroll to the bottom and select either Windows x86-64 executable installer for 64-bit or Windows x86 executable installer for 32-bit. (See below.


Download the Setup from the website and then run this setup to install.

Step 1:

Click on the link and download it and then install it.

Why Switch to Python?

  • Python is Interpreted − The interpreter processes Python at runtime. You don’t have to compile your program before it is executed. This is akin to PERL and PHP.
  • Python is interactive − In fact, you can sit at a Python prompt and interact directly with the interpreter to write your programmes.
  • Python is Object-Oriented − Python supports object-oriented programming style or technique
  • This supports practical and organized methods of programming and OOP.
  • It can be used as a scripting language, or it can be compiled to byte-code for large application construction.
  • It provides dynamic data types of very high level and supports the dynamic type check.
  • It supports the automatic collection of the garbage.
  • Easy to integrate with C, C++, COM, ActiveX, CORBA, and Java.

Writing First Program of Python

print ("Hello, Python!");

in this example, this is the basic syntax of python which can be used to display some syntax on the user screen.

Note: Python is not like C++ and other languages it is more user-friendly and more versatile in terms of syntax.

More details on Python:

Python is a high-level scripting language, which is interpreted, interactive and object-oriented. Python is intended to be very easy to read. It frequently uses English keywords where punctuations are used as other languages and have fewer syntaxis buildings than other languages.

Python Identifiers


  • A Python identifier is a name used to identify a variable, function, class, module or another object. An identifier starts with a letter A to Z or a to z. it can be the name or anything.
  • An uppercase letter begins with the class names. All other IDs begin with a case letter.
  • Starting an ID with one lead underscore shows that the ID is private.
  • The start of a two-principal underscores identifier means a very private identification.
  • If two trailing underscores end with the identifier, the identifier is a special name defined by language.

Keywords of Python Like we also discussed in C++ and C.

learn python keywords
learn python keywords

Comments in Python

Unlike C++ or C, it is not like that it has different Syntax in Python for Comments. The comment begins with a hash sign (#) which is not within a string literal. All characters after the # and until the physical line end are included in the comments and are ignored by the Python interpreter.


# First comment
print "Hello, Python!" # second comment
# This is a comment.
# This is a comment, too welcome to Python.
# Hello World of Python My name is Animesh.

Variables in Python

No explicit declaration for memory space reserves is required for the python variables. When you assign a value to a variable, the declaration occurs automatically. To assign values to variables, the same sign (=) is used.

The operand on the left-hand side of the variable is the name of the variable and on the right-hand side is the value of the variable.


counter = 100 # An integer assignment
miles = 1000.0 # A floating-point
name = "John" # A string
print counter
print miles
print name

Multiple Assignment In Python

You can assign a single value simultaneously to multiple variables with Python.


a,b,c = 1,2,"Animesh"

How to assign Numbers in Python

You can assign a single value simultaneously to multiple variables with Python.


var1 = 1
var2 = 10

Example with Output Solution

# Output: 107
# Output: 253 (251 + 2)
print(0xFB + 0b10)
# Output: 13


How to work with String in Python?

In quotation marks, pythons are identified as a contiguous set of characters. For pairs of single and double quotes, Python allows. String subsets may be taken from the slice([] and[ :]) operator using indexes from 0 at the start of the string and from-1 at the end of the string.


str = 'Hello World!'
print str # Prints complete string on screen
print str[0] # Prints first character of the string on screen
print str[2:5] # Prints characters starting from 3rd to 5th on compiler screen
print str[2:] # Prints string starting from 3rd character on screen
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string

Hello World!
llo World!
Hello World!Hello World!
Hello World!TEST

Types of Operator in Python

Python Supports different type of operators such as the list is as below:

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators


Arithmetic Operators in Python

These operators compare and decide on the relation between the values on both sides of them. It is also known as relational operators

Python Assignment Operators

Python Logical Operators

Note: This following table shows operators precedence in Python.

Python Lists

The most versatile compound data types in Python are lists. A list of items included in a square bracket, separated by commas ([ ]). The lists of arrays in C are somewhat similar. One difference is that all items in a list can be of different types of data.

See also  Nearshore vs Offshore: Which One is Best for Software Development Beyond 2020?


list = [ 'abcd', 786 , 2.23, 'Animesh’, 70.2 ]
tinylist = [123, 'Animesh']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists

[‘abcd’, 786, 2.23, ‘Animesh’, 70.2]
[786, 2.23]
[2.23, ‘Animesh ‘, 70.2]
[123, ‘Animesh ‘, 123, ‘Animesh ‘]
[‘abcd’, 786, 2.23, ‘Animesh ‘, 70.2, 123, ‘Animesh ‘].

Python Dictionary

Dictionaries of Python’s are a type of Table hash. They work like associative arrays or hazards in Perl and are made up of key-value pairs. Almost every Python type can be a dictionary key, but usually are a number or a string. Values may be any arbitrary Python object, on the other hand.


Dict {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'Animesh ','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values

This is one
This is two
{‘dept’: ‘sales’, ‘code’: 6734, ‘name’: ‘Animesh ‘}
[‘dept’, ‘code’, ‘name’]
[‘sales’, 6734, ‘Animesh ‘]

Python – Functions


A function is a group of statements that exist within a program for the purpose of performing a specific task.

Why we use Functions:

  • Code Reuse – Functions also reduce the duplication of code within a program. If a specific operation is performed in several places in a program, a function can be written once to perform that operation, and then be executed any time it is needed. This benefit of using functions is known as code reuse because you are writing the code to perform a task once and then
    reusing it each time you need to perform the task.
  • Better Testing – When each task within a program is contained in its own function, testing and debugging becomes simpler.
  • Programmers can test each function in a program individually, to determine whether it correctly performs its operation. This makes it easier to isolate and fix errors.
  • Faster Development- Suppose a programmer or a team of programmers is developing multiple programs. They discover that each of the programs performs several common tasks, such as asking for a username and a password, displaying the current time, and so on. It doesn’t make sense to write the code for these tasks multiple times. Instead, functions can be written for the commonly needed tasks, and those functions can be incorporated into each program that needs them.
  • Easier Facilitation of Teamwork – Functions also make it easier for programmers to work in teams. When a program is developed as a set of functions that each performs an individual task, then different programmers can be assigned the job of writing different functions.
learn Python Functions
learn Python Functions

How to name Functions in Python:

Before we discuss the process of creating and using functions, we should mention a few things about function names. Just as you name the variables that you use in a program, you also name the functions. A function’s name should be descriptive enough so that anyone
reading your code can reasonably guess what the function does. Python requires that you follow the same rules that you follow when naming variables, which we recap here:

  • You cannot use one of Python’s keywords as a function name. (See Table 1-2 for a list of the keywords.)
  • A function name cannot contain spaces.
  • The first character must be one of the letters a through z, A through Z, or an underscore character (_).
  • After the first character you may use the letters a through z or A through Z, the digits 0 through 9, or underscores.
  • Uppercase and lowercase characters are distinct.


Defining of a function


def functionname( parameters ):
return [expression]
learn python function structure
learn python function structure


def printme( str ):
"This prints a passed string into this function"
print str

Calling Function in Python

  • Blocks of functions start with a def keyword followed by the parenthesis and function name)).
  • In these parentheses should be placed any input parameters or arguments. In these parentheses, you can also define parameters.
  • The first function statement can be an optional statement -the function documentation string or docstring.
  • Each function starts with the code block


def function name (parameters):
"function docstring"
function suite
return [expression]
how to call a function in Python?
how to call a function in Python?

This is the further examples of functions

how to call a function in Python?
how to call a function in Python?
function chain in Python?
function chain in Python?


def printme( str ):
"This prints a passed string into this function"
print str

# Function definition is here

def printme( str ):
"This prints a passed string into this function"
print str

# Now you can call printme function

printme("I'm the first call to user-defined function!")
printme("Again, a second call to the same function")

I’m the first call to user-defined function!
Again, a second call to the same function

An argument is any piece of data that is passed into a function when the function is called. A parameter is a variable that receives an argument

Pass by reference in Python:

that is passed into a function.

Pass by reference in Python
Pass by reference in Python
Pass by reference in Python
Pass by reference in Python

Python is different. As we know, in Python, “Object references are passed by value”.

A function receives a reference to (and will access) the same object in memory as used by the caller. However, it does not receive the box that the caller is storing this object in; as in pass-by-value, the function provides its own box and creates a new variable for itself. Let’s try appending again:

Both the function and the caller refer to the same object in memory, so when the append function adds an extra item to the list, we see this in the caller too! They’re different names for the same thing; different boxes containing the same object. This is what is meant by passing the object references by value – the function and caller use the same object in memory but accessed through different variables. This means that the same object is being stored in multiple different boxes, and the metaphor kind of breaks down. Pretend its quantum or something.

But the key is that they really are different names and different boxes. In pass-by-reference, they were essentially the same box. When you tried to reassign a variable, and put something different into the function’s box, you also put it into the caller’s box, because they were the same box. But, in pass-by-object-reference:

Pass by reference in Python
Pass by reference in Python

Pass by Value in Python

In pass-by-value, the function receives a copy of the argument objects passed to it by the caller, stored in a new location in memory. The function then effectively supplies its own box to put the value in, and there is no longer any relationship between either the variables or the objects referred to by the function and the caller. The objects happen to have the same value, but they are totally separate, and nothing that happens to one will affect the other. If we again try to reassign:

Pass by Value in Python
Pass by Value in Python

Decision Making in Python

It is similar to other languages like C++ and JAVA but the syntax is a little bit different.

IF Statement in Python:

Basic Definition:

  • The if the statement is used to create a decision structure, which allows a program to have more than one path of execution.
  • The if statement causes
    one or more statements to execute only when a Boolean expression is true.

The Pictures following shows the examples and concept of if statement in Python:

IF Statement in Python:
IF Statement in Python:
IF Statement in Python:
IF Statement in Python:

Note: the following 2 tables show the arithmetic operators which can be widely used in if statement, so you can see and keep in mind about this, can be used in further examples.

IF Statement and operators in Python:
IF Statement and operators in Python:
IF Statement and operators in Python:
IF Statement and operators in Python:
IF Statement and operators in Python
IF Statement and operators in Python

Nested if statement if Python

Nested IF Statement in Python
Nested IF Statement in Python


# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if
num = float(input("Enter a number please : "))
if num >= 0:
if num == 0:
print("Positive number")
print("Negative number")

Enter a number: 5
Positive number

Python if/else statement

An if-else statement will execute one block of statements if its condition is true, or another block if its condition is false

The previous section introduced the single alternative decision structure (the if statement), which has one alternative path of execution. Now we will look at the dual alternative decision structure, which has two possible paths of execution—one path is taken if a condition
is true, and the other path is taken if the condition is false. S flowchart for a dual alternative decision structure.

  • The decision structure in the flowchart tests the condition temperature 40. If this condition is true, the statement print(”A little cold, isn’t it?”) is performed.
  • If the condition is false, the statement print(”Nice weather we’re having.”) is performed
IF Else Statement in Python
IF Else Statement in Python

Note: this picture shows the if/else example to make it clearer and more confident.

IF Else Statement in Python
IF Else Statement in Python


# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")

3 is a positive number
This is always printed
This is also always printed.


# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
print("Negative number")

Negative number

See also  Ruby on Rails Vs Python - Which Framework is Best for 2021

Comparing Strings in Python


Python allows you to compare strings. This allows you to create decision structures that test the value of a string.


name1 = 'Animesh'
name2 = 'India'
if name1 == name2:
print('The names are the same.')
print('The names are NOT the same.')

The names are NOT the same

Example 2:

# This program compares two strings.
# Get a password from the user.
password = input('Enter the password: ')
# Determine whether the correct password
# was entered.
if password == 'animesh':
print('Password accepted.')
print('Sorry, that is the wrong password.')


Enter the password: animeshsssss e
Sorry, that is the wrong password.

Nested Decision Structures and the if-elif-else Statement

This is a new topic in this language this is not available is C++ and JAVA.


To test more than one condition, a decision structure can be nested inside another decision structure.

Nested Decision Structures and the if-elif-else Statement
Nested Decision Structures and the if-elif-else Statement

The flowchart in the figure starts with a sequence structure. Assuming you have an outdoor thermometer in your window, the first step is Go to the window, and the next step is Read thermometer. A decision structure appears next, testing the condition outside. If this is true, the action Wear a coat is performed. Another sequence-structure appears next. The step Open the door is performed, followed by Go outside.

Nested Decision Structures and the if-elif-else Statement
Nested Decision Structures and the if-elif-else Statement
Nested Decision Structures and the if-elif-else Statement
Nested Decision Structures and the if-elif-else Statement


if score >= A_SCORE:
print('Your grade is A.')
elif score >= B_SCORE:
print('Your grade is B.')
elif score >= C_SCORE:
print('Your grade is C.')
elif score >= D_SCORE:
print('Your grade is D.')
print('Your grade is F.')

The OR Operator in Python

The or operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true when either of the subexpressions is true. The following is an example of an if statement that uses the or operator: if temperature 20 or temperature 100:print (‘The temperature is too extreme’.

The OR Operator in Python
The OR Operator in Python

Boolean Variables

A Boolean variable can reference one of two values: True or False. Boolean variables are commonly used as flags, which indicate whether specific conditions exist.

hungry = True
sleepy = False

Decision Statements in Python

The while Loop


A condition-controlled loop causes a statement or set of statements to repeat as long as a condition is true.

The while loop gets its name from the way it works: while a condition is true, do some task. The loop has two parts: (1) a condition that is tested for a true or false value, and (2) a statement or set of statements that is repeated as long as the condition is true.

The while Loop in Python
The while Loop in Python

How it all works The while Loop in Python?

The while Loop in Python
The while Loop in Python


The while Loop in Python
The while Loop in Python


count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye! Animesh"

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye! Animesh

Use of if/else in while loop in Python

count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
print count, " is not less than 5"

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

The for Loop in Python

A Count-Controlled Loop

Note: it is the most versatile loop in programming.


A count-controlled loop iterates a specific number of times.In Python, you use the for the statement to write a count-controlled loop. For loop iteration over a sequence, a list, a tuple, a dictionary, a set or a string, is used. This is not so much as the keyword in other programming languages as it does in other object-orientated programs. By means of a loop, a group of statements can be executed, once in a list for every item.

How does it work in python?

A Count-Controlled Loop in Python
A Count-Controlled Loop in Python


for letter in 'Python': # First Example
print 'Current Letter :', letter
fruits = ['banana', 'apple', 'peach']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit
print "Good bye! Animesh"

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter: o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : peach
Good bye! Animesh

Nested for loop in python


A loop within a loop in called nested loop.


for num1 in range(3):
for num2 in range(10, 14):
print(num1, ",", num2)

0 , 10
0 , 11
0 , 12
0 , 13
1 , 10
1 , 11
1 , 12
1 , 13
2 , 10
2 , 11
2 , 12
2 , 13

While loop can also be nested by code like within a loop

Let’s take an example:

i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1
print "Good bye! Animesh"

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye! Animesh

Python – Strings

Cords are one of Python’s most common types. We can simply create characters by putting them in quotes. Single quotes are treated in Python as double-quotes. Strings are just as easy as assigning a variable value.


var1 = 'Hello World!'
var2 = "Python Programming"

Accessing Values in Strings

A character type is not supported by Python; these are considered as length strings one and thus a substring. Use square brackets to slice with the index or index to access substrates to get your substrate.


var1 = 'Hello World!'
var2 = "Python Programming"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]

Updating Strings

By (re)assigning a variable to a different string you can “update” an existing string. The new value can be associated with its preceding value or a whole new string.


var1 = 'Hello World! Animesh India'
print "Updated String :- ", var1[:6] + 'Python'

Object-Oriented Programming

History of Python and OOPS:

We’ll learn about the fundamentals of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc. Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language. We’ll learn about the fundamentals of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc. Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

  • Python class and object:
  • Python supports both functional and object-based programming. Python promotes features such as higherorder functions, function types and lambdas, makes it a great choice for working in a functional programming style.


What is OOP?

In the object-oriented style of programming, you can divide a complex problem into smaller sets by creating objects.



It means reusing some of the facilities rather than building them again and again. This is done by using a class. We can use ‘ n ‘ so many times as we need.

Data Redundancy

This is a condition created at the data storage area (you can say Databases) where the same piece of data is processed in two separate places. Data redundancy is, therefore, one of the greatest advantages of OOP. If a user wants similar functionality in multiple classes, he/she can go ahead by writing and inherit common class definitions for similar functionalities.

Code Maintenance

This feature is more necessary for any programming language, it helps users to rework in many ways. Maintaining and modifying existing codes with new changes is always easy and time-saving.


Using the mechanism of data hiding and abstraction, we filter out limited exposure data, which means that we maintain security and provide the necessary data to view.

Design Benefits

If you are practising OOPs, the design benefit that the user will have is to design and fix things easily and eliminate (if any) risks. After a time when the program has reached some critical limits, it is easier to program all non-OOPs separately.

Reuse of code through inheritance

How to make a Python class?

In Python, you need to define a class before you create objects. A class is an Object Template. We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object. Since many houses can be made from the same description, we can create many objects from a class.

Object Properties:

Any entity having condition and behaviour is known as an object. A chair, pen, table, keypad, bike, etc., for example. That can be either physical or logical.

An Object can be defined as an instance of a class. An object has an address and takes up some memory space. Objects can communicate without knowing the particulars of the data or code of each other. The only thing necessary is the type of message that is accepted, and the type of response that the objects return.

Class Properties in Python

A class can be considered a blueprint that can be used to create as many objects as you want. We have a class website, for example, which has two data members (also known as fields, instance variables, and object state). This is just a blueprint, it does not represent any website, however, we can create Website objects (or instances) representing the websites using this. We created two objects, and we provided separate properties to the objects using constructor while creating objects.

Python is a programming language with multiple paradigms. In other words, it supports various approaches to programming.

The generation of objects is a popular approach to solving a problem with programming. This is called object-based programming.

  • Object

An object (instance) is an instantiation of a class. When class is defined, only the description for the object is defined. Therefore, no memory or storage is allocated.

See also  Python in Hindi: 5 Minutes Detailed Overview


class ParrotBird:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
# instantiate the Parrot class
blu = Parrot("Blue", 10)
woo = Parrot("Woooo", 15)
# access the class attributes
print("Blue is a {}".format(blu.__class__.species))
print("Woooo is also a {}".format(woo00.__class__.species))
# access the instance attributes
print("{} is {} years old".format( blue.name, blue.age))
print("{} is {} years old".format( woooo.name, woooo.age))

Blu is a bird
Woooo is also a bird
Blue is 109 years old
Woooo is 45 years old

Inheritance in Python

Heritage is a way to create a new class without changing it to use existing class details. The newly formed class is a derived class. The existing class is likewise a basic class (or class of parents).


class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
print("Penguin is ready")
def whoisThis(self):
def run(self):
print("Run faster")
peggy = Penguin()


Bird is ready
Penguin is ready
Swim faster
Run faster

Encapsulation in Python

We can limit access to methods and variables by using Python’s OOP. This prevents direct modification of data known as encapsulation. We use underscore as a prefix in the Python, i.e. the single ” ” or double ” ” attribute.


class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
# change the price
c.__maxprice = 1000
# using setter function

Selling Price: 900
Selling Price: 900
Selling Price: 1000

Polymorphism in Python

Polymorphism is the ability (in OOP) for multiple form (data types) to use the common interface.If there are multiple forms (rectangle, square, circle), we need to color one shape. We could nevertheless use the same way to color any form. The term “polymorphism” is used to this concept.


class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object

Parrot can fly
Penguin can’t fly

Points to remember:

  • The programming gets easy and efficient.
  • The class is sharable, so codes can be reused.
  • The productivity of programmers increases
  • Data is safe and secure with data abstraction.

Practice Questions of Python/ HandsOn Exercises on Python

Areas of Rectangles
The area of a rectangle is the rectangle’s length times its width. Write a program that asks for the length and width of two rectangles. The program should tell the user which rectangle has the greater area, or if the areas are the same.
Mass and Weight
Scientists measure an object’s mass in kilograms and its weight in newtons. If you know the amount of mass of an object in kilograms, you can calculate its weight in newtons with the following formula:
weight mass 9.8
Write a program that asks the user to enter an object’s mass, and then calculates its weight. If the object weighs more than 1,000 newtons, display a message indicating that it is too heavy. If the object weighs less than 10 newtons, display a message indicating that it is too light.
Magic Dates
The date June 10, 1960, is special because when it is written in the following format, the month times the day equals the year:
Design a program that asks the user to enter a month (in numeric form), a day, and a two-digit year. The program should then determine whether the month times the day equals the year. If so, it should display a message saying the date is magic. Otherwise, it should display a message saying the date is not magic.
Color Mixer
The colours red, blue, and yellow are known as the primary colours because they cannot be made by mixing other colours. When you mix two primary colours, you get a secondary colour, as shown here:

  • When you mix red and blue, you get purple.
  • When you mix red and yellow, you get orange.
  • When you mix blue and yellow, you get green.

Counting Game

Create a change-counting game that gets the user to enter the number of coins required to make exactly one dollar. The program should prompt the user to enter the number of pennies, nickels, dimes, and quarters. If the total value of the coins entered is equal to one dollar, the program should congratulate the user for winning the game. Otherwise, the program should display a message indicating whether the amount entered was more than or less than one dollar.

Analyse the problem, design unambiguous and precise algorithm and code for each of the following problems.

  1. Compute the cost per square foot of living space for a house, given the dimensions (Length, Width) of the house, the number of stories, the size of the non-living space (garage, closets), the total cost of the house.
  2. Given a positive integer number, find whether the number is even or odd.
  3. Given a positive integer number, find display if the number is a prime number.
  4. Find the slope of a line through two points using formula m =. The values of y1, y2, x1 and x2 are given. If x1 equals x2, the line is vertical and the slope is undefined. If y1 equals y2, the line is horizontal.
  5. Write code to calculate and print the diameter, the circumference, or the area of a circle given the radius. The input is two data items. The first is a character – ‘D’ (for diameter), ‘C’ for circumference, or ‘A’ for the area – to indicate the calculation needed. The next data value is a floating-point number indicating the radius of the particular circle.
  6. A company manufactures a line of traffic cones. It requires painting its cones in different colours. The company has hired you to write a program that will compute the surface area of the cone, and the cost of painting it, given its radius, height and the cost per square foot of three different colours of paint. The surface area of the cone can be calculated using formula
  7. Mother had just filled the cookie jar when the three children went to bed. That night one child woke up, ate half of the cookies and went back to bed. Later, the second child woke up, ate half of the remaining cookies and went back to bed. Still later, the third child woke up, ate half of the remaining cookies, leaving 5 cookies in the jar. How many cookies were in the jar, to begin with? Find a generic solution to this problem.
  8. Find and display the sum of numbers from 1 to n where n is input by the user.
  9. Display a line of n stars.
  10. Input an integer value and if the input value is equivalent to the value of a British coin, print it out in words. Otherwise, it should print an error message.

Input Print

1 One Penny

2 Two Penny

5 Five Penny

10 Ten Pence

50 Fifty Pence

  1. Add a series of numbers input by the user and find the average of these numbers. It is not known in advance how many values will be input.
  2. Display the status of the students (Pass or Fail) based on the marks entered by the user. It is not known in advance how many marks will be entered.
  3. Find the hypotenuse of the right-angled triangle given its two sides using Pythagorean Theorem.
  4. Write a program that reads the lengths of the sides of a triangle from the user and computes and displays the area of the triangle using Heron’s formula. The Heron’s formula is:

Where A, B, C are three sides of a triangle and S is half perimeter and is calculated by

  1. Given the cost of a sales item, calculate the amount of sales tax and total cost of the sales item including tax assuming 7% sales tax.
  2. A person’s weekly pay is Rs. 2500/-. He is scheduled to receive a 3% pay raise next week. Calculate the amount of his new salary.
  3. In a video store, a daily rental fee of a video is Rs. 50/-. Customers are charged a late fee of Rs. 20/- per day when the video is returned past the due date. Assume that a customer can return only one video at a time, calculate the amount the customer owes when he/she returns the video.
  4. Given a positive integer number N, find display all the prime number that is less than or equal to N.
  5. A woman is going shopping to buy fifteen items only. Find the total cost of these fifteen items given the price of each item. Also, display the highest price and the lowest price.
  6. A perfect number is a positive integer such that the sum of proper divisors equals the number. Thus 28 = 1 + 2 + 4 + 7 + 14 is a perfect number. If the sum of proper divisors is less than the number, it is deficient. If the sum exceeds the number, it is abundant. Write a program that allows the user to enter a positive integer N and then displays all perfect, deficient, and abundant numbers less than or equal to N.


Share and Enjoy !

Leave a Reply

Your email address will not be published. Required fields are marked *