Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
73 views

Introduction To Programming

This document provides an overview of different programming paradigms and concepts in Python including procedural, object-oriented, and event-driven programming. It also discusses how to install Python and the PyCharm IDE on Windows, describes script and interactive modes for writing Python code, and covers key Python concepts like docstrings, abstraction, polymorphism, encapsulation, inheritance, keywords, and control flow statements.

Uploaded by

Obukohwo Oke
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Introduction To Programming

This document provides an overview of different programming paradigms and concepts in Python including procedural, object-oriented, and event-driven programming. It also discusses how to install Python and the PyCharm IDE on Windows, describes script and interactive modes for writing Python code, and covers key Python concepts like docstrings, abstraction, polymorphism, encapsulation, inheritance, keywords, and control flow statements.

Uploaded by

Obukohwo Oke
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Introduction to Programming

Programming, also known as coding, refers to the process of writing


instructions for computing devices and systems. A computer program
translates those instructions into a language that computers can
understand.  
Procedural Programming
Procedural programming is a programming methodology that uses a list of
instructions in a step-by-step manner for a computer to execute.

In this programming practice, developers write line by line code which


executes a single action each line. In procedural programming first line of
code is executed, then the second, then the third and so on, lines cannot
jump from the 1st to the 7th to achieve something it must first complete 1-6
in order to get to the 7th line.

Event Driven Programming


Event-driven programming is a programming paradigm in which the flow of
the program is determined by events such as user actions, sensor outputs,
or message passing from other programs or threads.

Event driven programming is a very popular programming practice and is


widely used. If you have a phone, microwave, toaster, fire alarm or a PC
you have used this one way or the other. The code will wait for an event
which is either a CLICK of a mouse button, start the engine, detect smoke,
detect heat on the food or whatever then the program will perform a certain
action based on that EVENT.

Object Orientated Programming – OOP


Object-oriented programming refers to the concept in high-level languages
uses Objects and classes in their implementations, it has four major
building blocks which are, Polymorphism, Encapsulation, Abstraction, and
Inheritance.

OOP stands for Object-Oriented Programming.


Procedural programming is about writing procedures or functions that
perform operations on the data, while object-oriented programming is about
creating objects that contain both data and functions.
Object-oriented programming has several advantages over procedural
programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less
code and shorter development time
1
What is Python?
Python is an object-oriented programming language created by Guido Rossum in
1989. It is ideally designed for rapid prototyping of complex applications. It has
interfaces to many OS system calls and libraries and is extensible to C or C++. Many
large companies use the Python programming language, including NASA, Google,
YouTube, BitTorrent, etc. Its latest Version is the Python 3 (Py3).

How to Install Python on Windows [Pycharm IDE]


PyCharm is a cross-platform editor developed by JetBrains. Pycharm
provides all the tools you need for productive Python development.
Below are the detailed steps for installing Python and PyCharm

How to Install Python IDE


Below is a step by step process on how to download and install Python on
Windows:

Step 1) To download and install Python, visit the official website of
Python https://www.python.org/downloads/ and choose your version. We
have chosen Python version 3.6.3

Step 2) Once the download is completed, run the .exe file to install Python. Now
click on Install Now.

2
Step 3) You can see Python installing at this point.

Step 4) When it finishes, you can see a screen that says the Setup was successful.
Now click on “Close”.

How to Install Pycharm


Here is a step by step process on how to download and install Pycharm IDE on
Windows:
Step 1) To download PyCharm visit the
website https://www.jetbrains.com/pycharm/download/ and Click the
“DOWNLOAD” link under the Community Section.

3
Step 2) Once the download is complete, run the exe for install PyCharm. The setup
wizard should have started. Click “Next”.

Step 3) On the next screen, Change the installation path if required. Click “Next”.

Step 4) On the next screen, you can create a desktop shortcut if you want and click
on “Next”.

4
Step 5) Choose the start menu folder. Keep selected JetBrains and click on
“Install”.

Step 6) Wait for the installation to finish.

Step 7) Once installation finished, you should receive a message screen that
PyCharm is installed. If you want to go ahead and run it, click the “Run PyCharm
Community Edition” box first and click “Finish”.

Step 8) After you click on “Finish,” the Following screen will appear.

5
Script Mode
If you need to write a long piece of Python code or your Python script spans
multiple files, interactive mode is not recommended. Script mode is the way to
go in such cases. In script mode, You write your code in a text file then save it
with a  .py  extension which stands for "Python". Note that you can use any
text editor for this, including Sublime, Atom, notepad++, etc.

Interactive Mode
Interactive mode, also known as the REPL provides us with a quick way of
running blocks or a single line of Python code. The code executes via the
Python shell, which comes with Python installation. Interactive mode is handy
when you just want to execute basic Python commands or you are new to
Python programming and just want to get your hands dirty with this beautiful
language.

IDLE
IDLE is Python’s Integrated Development and Learning Environment.
IDLE has the following features:
 coded in 100% pure Python, using the tkinter GUI toolkit
 cross-platform: works mostly the same on Windows, Unix, and macOS
 Python shell window (interactive interpreter) with colorizing of code input, output,
and error messages
 multi-window text editor with multiple undo, Python colorizing, smart indent, call
tips, auto completion, and other features
 search within any window, replace within editor windows, and search through
multiple files (grep)
 debugger with persistent breakpoints, stepping, and viewing of global and local
namespaces
 configuration, browsers, and other dialogs

Docstrings
Python docstrings are the string literals that appear right after the definition of
a function, method, class, or module. Let's take an example.
Example 1: Docstrings
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2

Here, the string literal:


'''Takes in a number n, returns the square of n'''

Inside the triple quotation marks is the docstring of the function  square()  as it
appears right after its definition.

Note: We can also use triple  """  quotations to create docstrings.

6
Abstraction
Abstraction in Python is a programming methodology in which details of the programming
codes are hidden away from the user, and only the essential things are displayed to the user.
Abstraction is concerned with ideas rather than events. It’s like a user running a program (Web
Browser) without seeing the background codes

Polymorphism
Polymorphism means existing in many forms. Variables, functions, and objects can exist in
multiple forms in Java and Python. There are two types of polymorphism which are run time
polymorphism and compile-time polymorphism. Run time can take a different form while the
application is running and compile-time can take a different form during compilation.

Encapsulation
This is a programming style where implementation details are hidden. It reduces software
development complexity greatly. With Encapsulation, only methods are exposed. The
programmer does not have to worry about implementation details but is only concerned with
the operations Encapsulation also ensures that your data is hidden from external modification.
Encapsulation is also known as Data-Hidden. 
Encapsulation can be viewed as a shield that protects data from getting accessed by outside
code. 

Inheritance
In Python, codes are written in objects or blocks if you are adopting OOP methodology. Objects
can interact with one another by using the properties of each block or extending the
functionalities of a block through inheritance.  Inheritance ensures that codes are reused. The
properties of a class can be inherited and extended by other classes or functions. There are two
types of classes. One is the Parent or base class, and the other is the child class which can
inherit the properties of the parent class. Inheritance is a major pillar in Object-Oriented
programming.

Python Keywords
Python keywords are special reserved words that have specific meanings and
purposes and can’t be used for anything but those specific purposes. These
keywords are always available—you’ll never have to import them into your code.
List of keywords in python:
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not

7
Python str()
Python str() function returns the string version of the object. Parameters: object: The
object whose string representation is to be returned. encoding: Encoding of the given
object.

What are control flow statements in Python?


A program’s control flow is the order in which the program’s code executes.
The control flow of a Python program is regulated by conditional statements, loops, and
function calls.
Python has three types of control structures:
 Sequential - default mode
 Selection - used for decisions and branching
 Repetition - used for looping, i.e., repeating a piece of code multiple times.
1. Sequential
Sequential statements are a set of statements whose execution process happens in a
sequence. The problem with sequential statements is that if the logic has broken in any
one of the lines, then the complete source code execution will break.

2. Selection/Decision control statements


In Python, the selection statements are also known as Decision control
statements or branching statements.
The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.
Some Decision Control Statements are:
 Simple if
 if-else
 nested if
 if-elif-else

8
Simple if: If statements are control flow statements that help us to run a particular
code, but only when a certain condition is met or satisfied. A simple if only has one
condition to check.

if-else: The if-else statement evaluates the condition and will execute the body of if if
the test condition is True, but if the condition is False, then the body of else is executed.

nested if: Nested if statements are an if statement inside another if statement.

9
if-elif-else: The if-elif-else statement is used to conditionally execute a statement or a
block of statements.

3. Repetition
A repetition statement is used to repeat a group(block) of programming instructions.
In Python, we generally have two loops/repetitive statements:
 for loop
 while loop
for loop: A for loop is used to iterate over a sequence that is either a list, tuple,
dictionary, or a set. We can execute a set of statements once for each item in a list, tuple,
or dictionary.

while loop: In Python, while loops are used to execute a block of statements repeatedly


until a given condition is satisfied. Then, the expression is checked again and, if it is still
true, the body is executed again. This continues until the expression becomes false.

10
What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented
programming.
Look at the following illustration to see the difference between class and
objects:

Class: Fruit
Objects: Apple, Banana, Mango

Another example:

Class: Car
Objects: Volvo, Audi, Toyota

So, a class is a template for objects, and an object is an instance of a


class.
When the individual objects are created, they inherit all the variables and
functions from the class.

A class describes the contents of the objects that belong to it: it describes
an aggregate of data fields (called instance variables), and defines the
operations (called methods).

An object is an element (or instance) of a class; objects have the


behaviors of their class. The object is the actual component of programs,
while the class specifies how instances are created and how they behave.

Functions/Methods
Methods are functions that belongs to the class. a method is an action
which an object is able to perform.

A function is simply a “chunk” of code that you can use over and over
again, rather than writing it out multiple times. Functions enable
programmers to break down or decompose a problem into smaller chunks,
each of which performs a particular task.

11
Hello World: Create your First Python Program
Creating First Program
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To
create a new project, click on “Create New Project”.

Step 2) You will need to select a location.

1. You can select the location where you want the project to be created. If you
don’t want to change location than keep it as it is but at least change the
name from “untitled” to something more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
3. Next Click the “Create” Button.

12
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.

Step 4) A new pop up will appear. Now type the name of the file you want (Here we
give “HelloWorld”) and hit “OK”.

Step 5) Now type a simple program – print (‘Hello World!’).

Step 6) Now Go up to the “Run” menu and select “Run” to run your program.

13
Step 7) You can see the output of your program at the bottom of the screen.

The output of the code would be

Python print() function


The print() function in Python is used to print a specified message on the screen.
The print command in Python prints strings or objects which are converted to a
string while printing on a screen.

Syntax:

print(object(s))

How to Print a simple String in Python?


More often then not you require to Print strings in your coding construct.

Here is how to print statement in Python 3:

Example: 1 - To print the Welcome to K2Concept, use the Python print


statement as follows:

print ("Welcome to K2 CONCEPT")

Output:
Welcome to K2 CONCEPT

14
How to print blank lines
Sometimes you need to print one blank line in your Python program. Following is
an example to perform this task using Python print format.

Example: Let us print 8 blank lines. You can type:


print (8 * "\n")
or:
print ("\n\n\n\n\n\n\n\n\n")

Python Variables: How to Define/Declare String Variable Types


What is a Variable in Python?
A Python variable is a reserved memory location to store values. In other words, a
variable in a python program gives data to the computer for processing.

Python Variable Types


Every value in Python has a datatype. Different data types in Python are Numbers,
List, Tuple, Strings, Dictionary, etc. Variables in Python can be declared by any
name or even alphabets like a, aa, abc, etc.
How to Declare and use a Variable
Let see an example. We will define variable in Python and declare it as “a” and print
it.
a=100
print (a)
Re-declare a Variable
You can re-declare Python variables even after you have declared once.
Here we have Python declare variable initialized to f=0.
Later, we re-assign the variable f to value “K2Concept”

# Declare a variable and initialize it


f=0
print f

# re-declaring the variable works


f = “csc202”

Python String Concatenation and Variable


Let’s see whether you can concatenate different data types like string and number
together. For example, we will concatenate “CSC” with the number “202”.
Declaring variables in Python requires declaring the number as string otherwise it
will show a TypeError

Once the integer is declared as string, it can concatenate both “CSC” + str(“202”)=
“CSC202” in the output.

15
a="CSC"
b = 202

print(a+str(b))

Python Variable Types: Local & Global


There are two types of variables in Python, Global variable and Local variable.
When you want to use the same variable for rest of your program or module you
declare it as a global variable, while if you want to use the variable in a specific
function or method, you use a local variable while Python variable declaration.
Let’s understand this Python variable types with the difference between local and
global variables in the below program.
1. Let us define variable in Python where the variable “f” is global in scope and is
assigned value 101 which is printed in output
2. Variable f is again declared in function and assumes local scope. It is assigned
value “I am learning Python.” which is printed out as an output. This Python
declare variable is different from the global variable “f” defined earlier
3. Once the function call is over, the local variable f is destroyed. When we again,
print the value of “f” is it displays the value of global variable f=101

# Declare a variable and initialize it


f = 101
print(f)
# Global vs. local variables in functions
def someFunction():
f = 'I am learning Python'
print(f)
someFunction()
print(f)

Delete a variable
You can also delete Python variables using the command del “variable name”.
In the below example of Python delete variable, we deleted variable f, and when
we proceed to print it, we get error “variable name is not defined” which means
you have deleted the variable.
f = 11;
print(f)
del f
print(f)

Summary:
 Variables are referred to “envelop” or “buckets” where information can be
maintained and referenced. Like any other programming language Python also uses
a variable to store the information. Variables can be declared by any name or even
alphabets like a, aa, abc, etc. Variables can be re-declared even after you have
declared them for once

16
 Python constants can be understood as types of variables that hold the value which
can not be changed. Usually Python constants are referenced from other files. Python
define constant is declared in a new or separate file which contains functions,
modules, etc.
 Types of variables in Python or Python variable types : Local & Global
 Declare local variable when you want to use it for current function
 Declare Global variable when you want to use the same variable for rest of the
program
 To delete a variable, it uses keyword “del”.

Python Operators: Arithmetic, Logical, Comparison, Assignment, Bitwise &


Precedence

What are Logical Operators in Python?


Logical Operators in Python are used to perform logical operations on the values
of variables. The value is either true or false. We can figure out the conditions by
the result of the truth values. There are mainly three types of logical operators in
python : logical AND, logical OR and logical NOT. Operators are represented by
keywords or special

Arithmetic Operators - Arithmetic Operators perform various arithmetic


calculations like addition, subtraction, multiplication, division, %modulus,
exponent, etc. There are various methods for arithmetic calculation in Python like
you can use the eval function, declare variable & calculate, or call functions.
Example: For arithmetic operators we will take simple example of addition where
we will add two-digit 4+5=9
x= 4
y= 5
print(x + y)

Similarly, you can use other arithmetic operators like for multiplication(*), division
(/), substraction (-),modulus (%), exponential(**) etc.

Comparison Operators- Comparison Operators In Python compares the values


on either side of the operand and determines the relation between them. It is also
referred to as relational operators. Various comparison operators in python are
( ==, != , <>, >,<=, etc.)
Example: For comparison operators we will compare the value of x to the value of
y and print the result in true or false. Here in example, our value of x = 4 which is
smaller than y = 5, so when we print the value as x>y, it actually compares the value
of x to y and since it is not correct, it returns false.
x=4
y=5
print(('x > y is',x>y))
Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)
Python Assignment Operators
17
Assignment Operators in Python are used for assigning the value of the right
operand to the left operand. Various assignment operators used in Python are (+=,
– = , *=, /= , etc.).
Example: Python assignment operators is simply to assign the value, for example

num1 = 4
num2 = 5
print(num1 + num2)

Logical Operators or Bitwise Operators


Logical operators in Python are used for conditional statements are true or false.
Logical operators in Python are AND, OR and NOT. For logical operators following
condition are applied.
 For AND operator – It returns TRUE if both the operands (right side and left
side) are true
 For OR operator- It returns TRUE if either of the operand (right side or left
side) is true
 For NOT operator- returns TRUE if operand is false

Example: Here in example we get true or false based on the value of a and b
a = True
b = False
print(('a and b is', a and b))
print(('a or b is', a or b))
print(('not a is', not a))

Membership Operators
These operators test for membership in a sequence such as lists, strings or tuples.
There are two membership operators that are used in Python. (in, not in). It gives
the result based on the variable present in specified sequence or string
Example: For example here we check whether the value of x=4 and value of y=8 is
available in list or not, by using in and not in operators.

x=4
y=8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print("Line 1 - x is available in the given list")
else:
print("Line 1 - x is not available in the given list")
if ( y not in list ):
print("Line 2 - y is not available in the given list")
else:
print("Line 2 - y is available in the given list")

18
 Declare the value for x and y
 Declare the value of list
 Use the “in” operator in code with if statement to check the value of x existing in
the list and print the result accordingly
 Use the “not in” operator in code with if statement to check the value of y exist in
the list and print the result accordingly
 Run the code- When the code run it gives the desired output

Identity Operators
Identity Operators in Python are used to compare the memory location of two
objects. The two identity operators used in Python are (is, is not).
 Operator is: It returns true if two variables point the same object and false
otherwise
 Operator is not: It returns false if two variables point the same object and
true otherwise
Following operands are in decreasing order of precedence.
Operators in the same box evaluate left to right

x = 20
y = 20
if ( x is y ):
print("x & y SAME identity")
y=30
if ( x is not y ):
print("x & y have DIFFERENT identity")

19
Operator precedence
The operator precedence determines which operators need to be evaluated first.
To avoid ambiguity in values, precedence operators are necessary. Just like in
normal multiplication method, multiplication has a higher precedence than
addition. For example in 3+ 4*5, the answer is 23, to change the order of
precedence we use a parentheses (3+4)*5, now the answer is 35. Precedence
operator used in Python are (unary + – ~, **, * / %, + – , &) etc.
v=4
w=5
x=8
y=2
z=0
z = (v+w) * x / y;
print("Value of (v+w) * x/ y is ", z)

Python Conditional Statements: IF…Else, ELIF & Switch Case

What are Conditional Statements in Python?


Conditional Statement in Python perform different computations or actions
depending on whether a specific Boolean constraint evaluates to true or false.
Conditional statements are handled by IF statements in Python.

20
What is Python If Statement?
Python if Statement is used for decision-making operations. It contains a body of
code which runs only when the condition given in the if statement is true. If the
condition is false, then the optional else statement runs which contains some code
for the else condition.
When you want to justify one condition while the other condition is not true, then
you use Python if else statement.
Python if Statement Syntax:
if expression
Statement
else
Statement

#Example file for working with conditional statement


def main():
x, y = 2,8

if(x < y):


st= "x is less than y"
print(st)

main()

 We define two variables x, y = 2, 8


 The if Statement in Python checks for condition x<y which is True in this
case
 The variable st is set to “x is less than y.”
 The line print st will output the value of variable st which is “x is less than y”,

How to use “elif” condition


To correct the previous error made by “else condition”, we can
use “elif” statement. By using “elif” condition, you are telling the program to print
out the third condition or possibility when the other condition goes wrong or
incorrect.

#Example file for working with conditional statement


def main():
x,y =8,8
if(x < y):
st= "x is less than y"
elif (x == y):
st= "x is same as y"
else:
st="x is greater than y"
print(st)

main()
21
Python Nested if Statement
Following example demonstrates nested if Statement Python

total = 100
#country = "US"
country = "AU"
if country == "US":
if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
if country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")

Switch Case Statement in Python


What is Switch statement?
A switch statement is a multiway branch statement that compares the value of a
variable to the values specified in case statements.
Python language doesn’t have a switch statement.
Python uses dictionary mapping to implement Switch Case in Python

Summary:
A conditional statement in Python is handled by if statements and we saw various
other ways we can use conditional statements like Python if else over here.
 “if condition” – It is used when you need to print out the result when one of
the conditions is true or false.
 “else condition”- it is used when you want to print out the statement when
your one condition fails to meet the requirement
 “elif condition” – It is used when you have third possibility as the outcome.
You can use multiple elif conditions to check for 4th,5th,6th possibilities in your
code
 We can use minimal code to execute conditional statements by declaring all
condition in single statement to run the code
 Python If Statement can be nested

22
What is Loop?
Loops can execute a block of code number of times until a certain condition is met.
Their usage is fairly common in programming. Unlike other programming language
that have For Loop, while loop, dowhile, etc.

What is For Loop?


For loop is used to iterate over elements of a sequence. It is often used when you
have a piece of code which you want to repeat “n” number of time.
What is While Loop?
While Loop is used to repeat a block of code. Instead of running the code block
once, It executes the code block multiple times until a certain condition is met.

How to use “While Loop”


While loop does the exactly same thing what “if statement” does, but instead of
running the code block once, they jump back to the point where it began the code
and repeats the whole process again.
Syntax
while expression
Statement

#Example file for working with loops


#
x=0
#define a while loop
while(x <4):
print(x)
x = x+1

How to use “For Loop”


In Python, “for loops” are called iterators.
Just like while loop, “For Loop” is also used to repeat the program.
But unlike while loop which depends on condition true or false. “For Loop”
depends on the elements it has to iterate.

Example:
#Example file for working with loops
x=0
#define a while loop
# while(x <4):
# print x
# x = x+1

#Define a for loop


for x in range(2,7):
print(x)

23
For Loop iterates with number declared in the range.
For example,
For Loop for x in range (2,7)
When this code is executed, it will print the number between 2 and 7 (2,3,4,5,6). In
this code, number 7 is not considered inside the range.
For Loops can also be used for a set of other things and not just number. We will
see thin in next section.

How to use For Loop for String


In this step, we will see how “for loops” can also be used for other things besides
numbers.
Example:
#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"]
For m in Months:
print(m)

Output
Jan
Feb
Mar
April
May
June

How to use break statements in For Loop


Breakpoint is a unique function in For Loop that allows you to break or terminate
the execution of the for loop

Example:
#use a for loop over a collection
#Months = ["Jan","Feb","Mar","April","May","June"]
#for m in Months:
#print m

# use the break and continue statements


for x in range (10,20):
if (x == 15): break
print(x)
Output
10
11
12
13
14

24
In this example, we declared the numbers from 10-20, but we want that our for
loop to terminate at number 15 and stop executing further. For that, we declare
break function by defining (x==15): break, so as soon as the code calls the number
15 it terminates the program Code Line 10 declare variable x between range (10,
20)

How to use “continue statement” in For Loop


Continue function, as the name indicates, will terminate the current iteration of the
for loop BUT will continue execution of the remaining iterations.
Example
#use a for loop over a collection
#Months = ["Jan","Feb","Mar","April","May","June"]
#for m in Months:
#print m

# use the break and continue statements


for x in range (10,20):
if (x % 5 == 0) : continue
print(x)

Output
11
12
13
14
16
17
18
19
Continue statement can be used in for loop when you want to fetch a specific value
from the list.
In our example, we have declared value 10-20, but between these numbers we only
want those number that are NOT divisible by 5 or in other words which don’t give
zero when divided by 5.
So, in our range (10,11, 12….19,20) only 3 numbers falls (10,15,20) that are divisible
by 5 and rest are not.
So except number 10,15 & 20 the “for loop” will not continue and print out those
number as output.

What is enumerate() in Python?


enumerate() IN PYTHON is a built-in function used for assigning an index to each
item of the iterable object. It adds a loop on the iterable objects while keeping
track of the current item and returns the object in an enumerable form. This object
can be used in a for loop to convert it into a list by using list() method.

25
Example: Enumerate function is used for the numbering or indexing the members
in the list.
Suppose, we want to do numbering for our month ( Jan, Feb, Marc, ….June), so we
declare the variable i that enumerate the numbers while m will print the number of
month in list.
#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"]
for i, m in enumerate (Months):
print(i,m)

# use the break and continue statements

#for x in range (10,20):


#if (x == 15): break
#if (x % 5 == 0) : continue
#print x
Output
0 Jan
1 Feb
2 Mar
3 April
4 May
5 June
When code is executed the output of the enumerate function returns the months
name with an index number like (0-Jan), (1- Feb), (2- March), etc.
 declares the list of months [ Jan, Feb,…Jun]
 declares variable i and m for For Loop
 will print the result and again enter the For Loop for the rest of the months to
enumerate

26
OOPs in Python
OOPs in Python is a programming approach that focuses on using objects and
classes as same as other general programming languages. The objects can be any
real-world entities. Python allows developers to develop applications using the
OOPs approach with the major focus on code reusability. It is very easy to create
classes and objects in Python.

What is a Class?
A Class in Python is a logical grouping of data and functions. It gives the freedom to
create data structures that contains arbitrary content and hence easily accessible.

27
For example, for any bank employee who want to fetch the customer details online
would go to customer class, where all its attributes like transaction details,
withdrawal and deposit details, outstanding debt, etc. would be listed out.

How Inheritance works


Inheritance is a feature used in object-oriented programming; it refers to defining a
new class with less or no modification to an existing class. The new class is
called derived class and from one which it inherits is called the base. Python
supports inheritance; it also supports multiple inheritances. A class can inherit
attributes and behavior methods from another class called subclass or heir class.

Python Inheritance Syntax


class DerivedClass(BaseClass):
body_of_derived_class

Python Constructors
A constructor is a class function that instantiates an object to predefined values.
It begins with a double underscore (_). It __init__() method

Summary: “Class” is a logical grouping of functions and data. Python class


provides all the standard features of Object Oriented Programming.

What is Polymorphism?
Polymorphism can be defined as a condition that occurs in many different forms. It
is a concept in Python programming wherein an object defined in Python can be
used in different ways. It allows the programmer to define multiple methods in a
derived class, and it has the same name as present in the parent class. Such
scenarios support method overloading in Python.
In this Python Polymorphism tutorial, you will learn:

Polymorphism in Operators
An operator in Python helps perform mathematical and several other
programming tasks. For example, the ‘+’ operator helps in performing addition
between two integer types in Python, and in the same way, the same operator
helps in concatenating strings in Python programming.
Let us take an example of + (plus) operator in Python to display an application of
Polymorphism in Python as shown below:
Python Code:
p = 55
q = 77
r = 9.5
g1 = "K2"
g2 = "Concept!"
print("the sum of two numbers",p + q)
print("the data type of result is",type(p + q))

28
print("The sum of two numbers",q + r)
print("the data type of result is", type (q + r))
print("The concatenated string is", g1 + g2)
print("The data type of two strings",type(g1 + g2))

Output:
the sum of two numbers 132
the data type of result is <class 'int'>

The sum of the two numbers 86.5


the data type of result is <class 'float'>

The concatenated string is K2Concept!


The data type of two strings <class 'str'>

Polymorphism and Inheritance


Inheritance in Python can be defined as the programming concept wherein a child
class defined inherit properties from another base class present in Python.

What is a Mutable Object?


Mutable in Python can be defined as the object that can change or be regarded as
something changeable in nature. Mutable means the ability to modify or edit a
value.
Mutable objects in Python enable the programmers to have objects that can
change their values. They generally are utilized to store a collection of data. It can
be regarded as something that has mutated, and the internal state applicable
within an object has changed.

What are Immutable objects?


Immutable objects in Python can be defined as objects that do not change their
values and attributes over time.
These objects become permanent once created and initialized, and they form a
critical part of data structures used in Python.
Python is used in numbers, tuples, strings, frozen sets, and user-defined classes
with some exceptions. They cannot change, and their values and it remains
permanent once they are initialized and hence called immutable.
In Python, everything is an object
In the Python programming language, everything can be regarded as an object
comprising lists, integers, and functions. This feature can be compared with other
programming languages which support objects.

Mutable objects in Python


In a mutable object, the object’s value changes over a period of time.
In this example, we have explained mutable objects in Python, and this utilizes lists
as an application of mutable objects as shown below: –

29
Python Code:
mut_list = [1, 2, 3]
print("The list in Python",mut_list)
mut_list[0] = 'Gurru99'
mut_list
print("The list in Python after changing value",mut_list)
Output:
The list in Python [1, 2, 3]
The list in Python after changing value ['Gurru99', 2, 3]
As we can see in the above-given example, the mutable list in Python had values of
1,2,3. The first element of the mutable list is changed from 1 to K2Concept, and it
does not create a new object when a new value is initialized.
Here we can use the id method to utilize it. Following illustrates the use of the id
method for mutable objects as shown below: –

Python Code:
mut_list = [1, 2, 3]
print("The list in Python",mut_list)
print("the id of the list is ",id(mut_list))
mut_list[0] = 'Gurru99'
mut_list
print("The mut list in Python after changing value",mut_list)
print("the id of the list is post change in value",id(mut_list))

Output
The list in Python [1, 2, 3]
the id of the list is 139931568729600
The list in Python after changing value ['Gurru99', 2, 3]
the id of the list is post change in value 139931568729600
The following figure illustrates the mutable object in Python as shown below: –
Immutable objects in Python
Immutable objects in Python are objects wherein the instances do not change over
the period. Immutable instances of a specific type, once created, do not change,
and this can be verified using the id method of Python.
Let us take an example of integer type objects in Python that illustrates the
concept of immutable objects in Python as shown below: –
Python Code:
a=244
print("the number before change is",a)
print("the id of number before change is",id(a))
a=344
print("the number after change is",a)
print("the id of number after change is",id(a))
Output
the number before a change is 244
30
the id of number before change is 9796768
the number before change is 344
the id of number before change is 140032307887024
It could be seen above that there is change in “a.” Let’s study how the mechanism
works:
 There is no change in the object’s value when the initialization of “a” with
344.
 Instead, a new object is created and is bounded with “a.”
 The other object assigned as 244 would no longer be accessible.
 The above example utilized an integer object.
At a=244, a new object is created and referenced to “a” as shown below: –

Post using a=344, there is a new object referenced with “a”. The following diagram
represents the same: –

Therefore, whenever there is the assignment of a new value to the name of int type,
there is a change in the binding of the name with another object. The same
principle aligns with tuples, strings, float, and Boolean hence termed immutable.

Mutable vs. Immutable objects


Here are major differences between Mutable and Immutable Objects:
Mutable object Immutable object
The object state can be changed The object state cannot be
once created changed once created
Mutable objects are not regarded as Immutable objects are regarded
thread-safe in nature. as thread-safe in nature.
The mutable objects are not made
It is critical to make classes final
final, and hence the programmer can
when there is the creation of the
keep changing mutable objects and
immutable object
use the same objects.

31
What is Python Main Function?
Python main function is a starting point of any program. When the program is run,
the python interpreter runs the code sequentially. Main function is executed only
when it is run as a Python program. It will not run the main function if it is imported
as a module.

What is Function in Python?


A Function in Python is a piece of code which runs when it is referenced. It is used
to utilize the code in more than one place in a program. It is also called method or
procedure. Python provides many inbuilt functions like print(), input(), compile(),
exec(), etc. but it also gives freedom to create your own functions.

How to define and call a function in Python


Function in Python is defined by the “def ” statement followed by the function
name and parentheses ( () )

Example: Let us define a function by using the command ” def func1():” and call
the function. The output of the function will be “I am learning Python function”.

32
The function print func1() calls our def func1(): and print the command ” I am
learning Python function None.”
There are set of rules in Python to define a function.
 Any args or input parameters should be placed within these parentheses
 The function first statement can be an optional statement- docstring or the
documentation string of the function
 The code within every function starts with a colon (:) and should be indented
(space)
 The statement return (expression) exits a function, optionally passing back a
value to the caller. A return statement with no args is the same as return
None.

Significance of Indentation (Space) in Python
Before we get familiarize with Python functions, it is important that we understand
the indentation rule to declare Python functions and these rules are applicable to
other elements of Python as well like declaring conditions, loops or variable.
Python follows a particular style of indentation to define the code, since Python
functions don’t have any explicit begin or end like curly braces to indicate the
start and stop for the function, they have to rely on this indentation. Here we
take a simple example with “print” command. When we write “print” function right
below the def func 1 (): It will show an “indentation error: expected an indented
block“.

33
Now, when you add the indent (space) in front of “print” function, it should print as
expected.

At least, one indent is enough to make your code work successfully. But as a
best practice it is advisable to leave about 3-4 indent to call your function.
It is also necessary that while declaring indentation, you have to maintain the
same indent for the rest of your code. For example, in below screen shot when
we call another statement “still in func1” and when it is not declared right below
the first print statement it will show an indentation error “unindent does not
match any other indentation level.”

Now, when we apply same indentation for both the statements and align them in
the same line, it gives the expected output.
34
How Function Return Value?
Return command in Python specifies what value to give back to the caller of the
function.
Let’s understand this with the following example
Step 1) Here – we see when function is not “return”. For example, we want the
square of 4, and it should give answer “16” when the code is executed. Which it
gives when we simply use “print x*x” code, but when you call function “print
square” it gives “None” as an output. This is because when you call the function,
recursion does not happen and fall off the end of the function. Python returns
“None” for failing off the end of the function.

Step 2) To make this clearer we replace the print command with assignment
command. Let’s check the output.

35
When you run the command “print square (4)” it actually returns the value of the
object since we don’t have any specific function to run over here it returns “None”.
Step 3) Now, here we will see how to retrieve the output using “return” command.
When you use the “return” function and execute the code, it will give the output
“16.”

Step 4) Functions in Python are themselves an object, and an object has some
value. We will here see how Python treats an object. When you run the command
“print square” it returns the value of the object. Since we have not passed any
argument, we don’t have any specific function to run over here it returns a default
value (0x021B2D30) which is the location of the object. In practical Python
program, you probably won’t ever need to do this.

36
Arguments in Functions
The argument is a value that is passed to the function when it’s called.
In other words on the calling side, it is an argument and on the function side it is a
parameter.
Let see how Python Args works –
Step 1) Arguments are declared in the function definition. While calling the
function, you can pass the values for that args as shown below

Step 2) To declare a default value of an argument, assign it a value at function


definition.

Example: x has no default values. Default values of y=0. When we supply only one
argument while calling multiply function, Python assigns the supplied value to x
while keeping the value of y=0. Hence the multiply of x*y=0

Step 3) This time we will change the value to y=2 instead of the default value y=0,
and it will return the output as (4×2)=8.

37
Step 4) You can also change the order in which the arguments can be passed in
Python. Here we have reversed the order of the value x and y to x=4 and y=2.

Step 5) Multiple Arguments can also be passed as an array. Here in the example we
call the multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args)
function; it prints out the output as (1,2,3,4,5)

38
Python abs()
Python abs() is a built-in function available with the standard library of python. It
returns the absolute value for the given number. Absolute value of a number is the
value without considering its sign. The number can be integer, floating point
number or complex number. If the given number is complex, then it will return its
magnitude.
Syntax:
abs(value)
Parameters: (value)
The input value to be given to abs() to get the absolute value. It can be an integer, a
float, or a complex number.
Return Value:
It will return the absolute value for the given number.
 If the input is an integer, the return value also will be an integer.
 If the input is a float, the return value will also be float.
 If the input is a complex number, the return value will be the magnitude of
the input.
Examples:
Code Example 1: Integer and Float number
To get the absolute value of an integer and float number check this code:
# testing abs() for an integer and float

int_num = -25

float_num = -10.50

print("The absolute value of an integer number is:", abs(int_num))


print("The absolute value of a float number is:", abs(float_num))
Output:
The absolute value of an integer number is: 25
39
The absolute value of a float number is: 10.5
Example 2: Complex Number
To get absolute value of complex number
# testing abs() for a complex number

complex_num = (3+10j)

print("The magnitude of the complex number is:", abs(complex_num))


Output:
The magnitude of the complex number is: 10.44030650891055
Summary:
 Abs() is a built-in function available with python, and it will return you the
absolute value for the input given.
 Value is an input value to be given to abs() to get the absolute value. It can
be an integer, a float, or a complex number.
 The abs() method takes one argument, i.e. the value you want to get the
absolute.
 The abs function returns the absolute value for the given number.

Round()
Round() is a built-in function available with python. It will return you a float
number that will be rounded to the decimal places which are given as input.
If the decimal places to be rounded are not specified, it is considered as 0, and it
will round to the nearest integer.
Syntax:
round(float_num, num_of_decimals)
Parameters
 float_num: the float number to be rounded.
 num_of_decimals: (optional) The number of decimals to be considered
while rounding. It is optional, and if not specified, it defaults to 0, and the
rounding is done to the nearest integer.
Description
The round() method takes two argument
 the number to be rounded and
 the decimal places it should consider while rounding.
The second argument is optional and defaults to 0 when not specified, and in such
case, it will round to the nearest integer, and the return type will also be an integer.
When the decimal places, i.e. the second argument, is present, it will round to the
number of places given. The return type will be a float.
If the number after the decimal place given
 >=5 than + 1 will be added to the final value
 <5 than the final value will return as it is up to the decimal places mentioned.
Return value
It will return an integer value if the num_of_decimals is not given and a float value
if the num_of_decimals is given. Please note the value will be rounded to +1 if the

40
value after the decimal point is >=5 else it will return the value as it is up to the
decimal places mentioned.

What is Python Range?


Python range() is a built-in function available with Python from Python(3.x), and it
gives a sequence of numbers based on the start and stop index given. In case the
start index is not given, the index is considered as 0, and it will increment the value
by 1 till the stop index.
For example range(5) will output you values 0,1,2,3,4 .The Python range()is a very
useful command and mostly used when you have to iterate using for loop.
Syntax
range(start, stop, step)
Parameters
 start: (optional) The start index is an integer, and if not given, the default
value is 0.
 stop: The stop index decides the value at which the range function has to
stop. It is a mandatory input to range function. The last value will be always
1 less than the stop value.
 step: (optional).The step value is the number by which the next number is
range has to be incremented, by default, it is 1.
Return value:
The return value is a sequence of numbers from the given start to stop index.
Python range() Function and history
Python range() has been introduced from python version 3, before that xrange()
was the function.
Using range()
This example shows how to print the values from 0-9 using range().
The value used in range is 10, so the output is 0 1 2 3 4 5 6 7 8 9
Since the start is not given the start is considered as 0 and the last value is given till
9. The last value is always 1 less than the given value i.e. stop-1.
for i in range(10):
print(i, end =" ")
Output:
0123456789
Using start and stop in range()
In the code, the start value is 3, and stop value is 10. Here the start index is 3, so the
sequence of numbers will start from 3 till the stop value. The last value in the
sequence will be 1 less than the stop value 10-1 = 9.
for i in range(3, 10):
print(i, end =" ")
Output:
3456789
Using start, stop and step
The start value is 3, so the sequence of numbers will start at 3. The stop value is 10,
so the sequence of numbers will stop at (10-1) i.e 9. The step is 2, so each value in

41
the sequence will be incremented by 2. If the step value is not given, the value for
step defaults to 1.
for i in range(3, 10, 2):
print(i, end =" ")
Output:
3579
So far, we have seen how range() function gives the incremented value for the stop
value given. Let us now try an example to get the decremented value in the range
given.
Incrementing the values in range using a positive step.
The parameter step in range() can be used to increment /decrement the values. By
default, it is a positive value 1. So it will always give incremented values.
The step value has to be positive incase you want to want incremented values as
ouput.
for i in range(1, 30, 5):
print(i, end =" ")
Output:
1 6 11 16 21 26
Reverse Range: Decrementing the values using negative step.
The parameter step with negative value in range() can be used to get decremented
values. In the example below the step value is negative so the output will be in
decremented from the range value given.
for i in range(15, 5, -1):
print(i, end =" ")
Output:
15 14 13 12 11 10 9 8 7 6
The start value is 15, the stop value is 5 and the step value is negative number i.e -1.
With above inputs range() function will decrement the value from 15 onwards till it
reaches the stop value , but here the difference is the last value will be stop + 1.

Using for-loop with Python range()


In this example we will use a array of numbers and, let us see how to use the iterate
the array inside for-loop using range()
Example:
arr_list = ['Mysql', 'Mongodb', 'PostgreSQL', 'Firebase']

for i in range(len(arr_list)):
print(arr_list[i], end =" ")
Output:
MysqlMongodb PostgreSQL Firebase
In above example we have used len(arr_list) as the stop value. The for loop will
iterate till the stop value i.e the length of the array and that will be 4, as we have
four items in the arr_list. The start value will be 0 and step will be 1.So the values
will start from 0 and will stop at 3 i.e length of array -1 meaning 4 -1 = 3.

How to Access Range Elements


42
You can make use of a for-loop to get the values from the range or use the index to
access the elements from range().
Using for-loop
Example:
for i in range(6):
print(i)
Output:
0
1
2
3
4
5

Some common mathematical functions in python

This module provides access to the mathematical functions defined by the C standard.

These functions cannot be used with complex numbers; use the functions of the same
name from the cmath module if you require support for complex numbers. The
distinction between functions which support complex numbers and those which don’t is
made since most users do not want to learn quite as much mathematics as required to
understand complex numbers. Receiving an exception instead of a complex result
allows earlier detection of the unexpected complex number used as a parameter, so
that the programmer can determine how and why it was generated in the first place.

The following functions are provided by this module. Except when explicitly noted
otherwise, all return values are floats.

math.ceil(x)
Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a
float, delegates to x.__ceil__(), which should return an Integral value.

math.comb(n, k)
Return the number of ways to choose k items from n items without repetition and
without order.

Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n.

Also called the binomial coefficient because it is equivalent to the coefficient of k-th term
in polynomial expansion of the expression (1 + x) ** n.

Raises TypeError if either of the arguments are not integers. Raises ValueError if either
of the arguments are negative.

math.copysign(x, y)
Return a float with the magnitude (absolute value) of x but the sign of y. On platforms
that support signed zeros, copysign(1.0, -0.0) returns -1.0.

math.fabs(x)
Return the absolute value of x.

43
math.factorial(x)
Return x factorial as an integer. Raises ValueError if x is not integral or is negative.

math.floor(x)
Return the floor of x, the largest integer less than or equal to x. If x is not a float,
delegates to x.__floor__(), which should return an Integral value.

math.gcd(*integers)
Return the greatest common divisor of the specified integer arguments. If any of the
arguments is nonzero, then the returned value is the largest positive integer that is a
divisor of all arguments. If all arguments are zero, then the returned value is 0. gcd()
without arguments returns 0.

math.isfinite(x)
Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is
considered finite.)

math.isinf(x)
Return True if x is a positive or negative infinity, and False otherwise.

math.isnan(x)
Return True if x is a NaN (not a number), and False otherwise.

math.isqrt(n)
Return the integer square root of the nonnegative integer n. This is the floor of the exact
square root of n, or equivalently the greatest integer a such that a² ≤ n.

For some applications, it may be more convenient to have the least integer a such that
n ≤ a², or in other words the ceiling of the exact square root of n. For positive n, this can
be computed using a = 1 + isqrt(n - 1).

math.lcm(*integers)
Return the least common multiple of the specified integer arguments. If all arguments
are nonzero, then the returned value is the smallest positive integer that is a multiple of
all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without
arguments returns 1.

math.perm(n, k=None)
Return the number of ways to choose k items from n items without repetition and with
order.

Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n.

If k is not specified or is None, then k defaults to n and the function returns n!.

Raises TypeError if either of the arguments are not integers. Raises ValueError if either
of the arguments are negative.

math.log(x[, base])
With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as
log(x)/log(base).

44
math.log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is
accurate for x near zero.

math.log2(x)
Return the base-2 logarithm of x. This is usually more accurate than log(x, 2).

See also int.bit_length() returns the number of bits necessary to represent an integer in
binary, excluding the sign and leading zeros.
math.log10(x)
Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).

math.pow(x, y)
Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard
as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even
when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer
then pow(x, y) is undefined, and raises ValueError.

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use
** or the built-in pow() function for computing exact integer powers.

math.sqrt(x)
Return the square root of x.

Trigonometric functions
math.acos(x)
Return the arc cosine of x, in radians. The result is between 0 and pi.

math.asin(x)
Return the arc sine of x, in radians. The result is between -pi/2 and pi/2.

math.atan(x)
Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2.

math.cos(x)
Return the cosine of x radians.

math.sin(x)
Return the sine of x radians.

math.tan(x)
Return the tangent of x radians.

Angular conversion
math.degrees(x)
Convert angle x from radians to degrees.

math.radians(x)
Convert angle x from degrees to radians.

Hyperbolic functions
Hyperbolic functions are analogs of trigonometric functions that are based on
hyperbolas instead of circles.

math.acosh(x)
45
Return the inverse hyperbolic cosine of x.

math.asinh(x)
Return the inverse hyperbolic sine of x.

math.atanh(x)
Return the inverse hyperbolic tangent of x.

math.cosh(x)
Return the hyperbolic cosine of x.

math.sinh(x)
Return the hyperbolic sine of x.

math.tanh(x)
Return the hyperbolic tangent of x.

Constants
math.pi
The mathematical constant π = 3.141592…, to available precision.

math.e
The mathematical constant e = 2.718281…, to available precision.

math.nan
A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan').

46

You might also like