Python NOTES Unit-4
Python NOTES Unit-4
It is used for:
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping can be very
quick.
Python can be treated in a procedural way, an object-oriented way or a
functional way.
Good to know
The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated with
anything other than security updates, is still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny,
Pycharm, Netbeans or Eclipse which are particularly useful when
managing larger collections of Python files.
With the Python interactive interpreter it is easy to check Python commands. The
Python interpreter can be invoked by typing the command "python" without any
parameter followed by the "return" key at the shell prompt:
Characteristics of Python
Following are important characteristics of Python Programming −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Applications of Python
As mentioned before, Python is one of the most widely used language over the web.
I'm going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs
than shell scripting.
print counter
print miles
print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For
example −
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location. You can also assign multiple objects to multiple
variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign
a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For
example −
del var
del var_a, var_b
Python supports four different numerical types −
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in
the beginning of the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −
#!/usr/bin/python
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example
−
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
A regular expression is a special sequence of characters that helps you match or find
other strings or sets of strings, using a specialized syntax held in a pattern. Regular
expressions are widely used in UNIX world.
The Python module re provides full support for Perl-like regular expressions in Python.
The re module raises the exception re.error if an error occurs while compiling or using
a regular expression.
We would cover two important functions, which would be used to handle regular
expressions. But a small thing first: There are various characters, which would have
special meaning when they are used in regular expression. To avoid any confusion
while dealing with regular expressions, we would use Raw Strings as r'expression'.
1
pattern
This is the regular expression to be matched.
2
string
This is the string, which would be searched to match the pattern at the beginning of string
3
flags
You can specify different flags using bitwise OR (|). These are modifiers, which are listed i
1
group(num=0)
This method returns entire match (or specific subgroup num)
2
groups()
This method returns all matching subgroups in a tuple (empty if there weren't any)
Example
#!/usr/bin/python
import re
Example
Live Demo
#!/usr/bin/python
import re
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting
all occurrences unless max provided. This method returns modified string.
Example
Live Demo
#!/usr/bin/python
import re
Statement:
A statement is an instruction that the Python interpreter can execute. We
have seen two kinds of statements: print and assignment. When you type
a statement on the command line, Python executes it and displays the
result, if there is one. The result of a print statement is a value.
Python Statement
In Python Programming, any executable instruction, that tell the
computer to perform a specification action is refer to as statements.
These statements are used to build program’s main logic. Program
statement can be an input-output statements, arithmetic statements,
control statements, simple assignment statements and any other
statements and it can also includes comments.
Multi-line statement:- In Python, each of the executable statement
must be ended with a newline character. But, if it required you can
extend a statement over multiple lines explicitly with the line
continuation character (\) as follows –
Example 1:-
1x=1+2+3+\
2 4+5+6+\
3 7+8+9
You can also extend a statement over multiple lines implicitly using
surrounding parentheses ( ), brackets [ ] and braces { }.
Example 2:-
1 x = (1 + 2 + 3 +
2 4+5+6+
3 7 + 8 + 9)
Tuple Assignment
Introduction
Tuples are basically a data type in python. These tuples are an ordered
collection of elements of different data types. Furthermore, we represent
them by writing the elements inside the parenthesis separated by
commas. We can also define tuples as lists that we cannot change.
Therefore, we can call them immutable tuples. Moreover, we access
elements by using the index starting from zero. We can create a tuple in
various ways. Here, we will study tuple assignment which is a very
useful feature in python.
Tuple Assignment
In python, we can perform tuple assignment which is a quite useful
feature. We can initialise or create a tuple in various ways. Besides
tuple assignment is a special feature in python. We also call this
feature unpacking of tuple.
COPY CODE
>>>tup
COPY CODE
>>>tup2
COPY CODE
>>>tup3
COPY CODE
>>>tup3 = (55, [6, 9], 67)
>>>tup3
For example,
COPY CODE
>>>tup=(90)
>>>tup
90
>>>type(tup)
<class 'int'>
COPY CODE
>>>tup=(90,)
>>>tup
(90,)
>>>type(tup)
<class 'tuple'>
For example,
COPY CODE
>>>seq
(22, 4, 56)
>>>type(seq)
<class 'tuple'>
Example 1
COPY CODE
>>>print(n1)
99
>>>print(n2)
7
Example 2
COPY CODE
>>>print(english)
99
>>>print(roll no.)
>>>print(GPA)
6.7
>>>print(maths)
90
Example 3
COPY CODE
#this gives an error as the variables on the left are more than
the number of elements in the tuple
(expected 5, got 4)
Python - Basic Operators 18/07/2021
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.
Operator Description
== If the values of two operands are equal, then the condition becomes true.
!= If values of two operands are not equal, then condition becomes true.
<> If values of two operands are not equal, then condition becomes true.
> If the value of left operand is greater than the value of right operand, then condition becomes
true.
< If the value of left operand is less than the value of right operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value of right operand,
<= If the value of left operand is less than or equal to the value of right operand,
number.
and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.
not Logical NOT Used to reverse the logical state of Not(a and b) is false.
its operand.
in Evaluates to true if it
finds a variable in the
x in y, here in results in a 1 if x is a member of sequence y.
specified sequence
and false otherwise.
not in Evaluates to true if it x not in y, here not in results in a 1 if x is not a member of sequence y.
does not finds a
variable in the specified
sequence and false
otherwise.
Python Identity Operators
Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
[ Show Example ]
equal to id(y).
the same object and true
otherwise.
1
**
Exponentiation (raise to the power)
2
~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3
* / % //
Multiply, divide, modulo and floor division
4
+-
Addition and subtraction
5
>> <<
Right and left bitwise shift
6
&
Bitwise 'AND'
7
^|
Bitwise exclusive `OR' and regular `OR'
8
<= < > >=
Comparison operators
9
<> == !=
Equality operators
10
= %= /= //= -= += *= **=
Assignment operators
11
is is not
Identity operators
12
in not in
Membership operators
13
not or and
Logical operators
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of
the line:
Example
print("Hello, World!") #This is a comment
A comment does not have to be text that explains the code, it can also be used
to prevent Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")
Multi Line Comments
Python does not really have a syntax for multi line comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your comment
inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but
then ignore it, and you have made a multiline comment.
Python Module 24/08/2021
What is a Module?
Consider a module to be the same as a code library.
Create a Module
To create a module just save the code you want in a file with the file
extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever
you like.
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create
yourself.
Import From Module
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import only the person1 dictionary from the module:
print (person1["age"])
Note: When importing using the from keyword, do not use the module name
when referring to elements in the module.
Example: person1["age"], not mymodule.person1["age"]
Python Function
A function is a block of code which only runs when it is
called.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Example
This function expects 2 arguments, and gets 2 arguments:
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
my_function("Emil")
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
This way the function will receive a dictionary of arguments, and can access the
items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the
parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Example
def myfunction():
pass
end19-8/2021
Recursion 25/08/2021
Python also accepts function recursion, which means a defined function can call
itself.
The developer should be very careful with recursion as it can be quite easy to
slip into writing a function which never terminates, or one that uses excess
amounts of memory or processor power. However, when written correctly
recursion can be a very efficient and mathematically-elegant approach to
programming.
To a new developer it can take some time to work out how exactly this works,
best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
y = 50
temp = x
x=y
y = temp
print("Value of x:", x)
print("Value of y:", y)
(2)distance of 2 points….
2. import math
p1 = [4, 0]
p2 = [6, 6]
print(distance)
output_list = []
output_list.append(lists[item])
return output_list
# Driver Code
rotate_num = 3
list_1 = [1, 2, 3, 4, 5, 6]
print(rightRotate(list_1, rotate_num))
UNIT-1 END
----------------------------------------------------------------------------------------------------
UNIT-2
Python – LOOPS AND LOOP CONTROL
STATMENT
Date:26/08/2021
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement –
1 while loop
2 for loop
3 nested loops
You can use one or more loop inside any another while, for or loop.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
3 pass statement
Syntax
The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python
uses indentation as its method of grouping statements.
Here, key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body will be skipped and the first statement
after the while loop will be executed. Example
#!/usr/bin/python
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block
is executed. Each item in the list is assigned to iterating_var, and the statement(s)
block is executed until the entire sequence is exhausted.
Example
#!/usr/bin/python
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is as
follows −
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other type
of loop. For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to 100
−
#!/usr/bin/python
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
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.
The most common use for break is when some external condition is triggered requiring
a hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost
loop and start executing the next line of code after the block.
Syntax
The syntax for a break statement in Python is as follows −
break
Flow Diagram
Example
#!/usr/bin/python
It returns the control to the beginning of the while loop.. The continue statement
rejects all the remaining statements in the current iteration of the loop and moves the
control back to the top of the loop.
The continue statement can be used in both while and for loops.
Syntax
Continue
Flow Diagram
Example
Live Demo
#!/usr/bin/python
It is used when a statement is required syntactically but you do not want any command
or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is
also useful in places where your code will eventually go, but has not been written yet
(e.g., in stubs for example) −
Syntax
pass
Example
#!/usr/bin/python
if statement
if..else statements
nested if statements
if-elif ladder
Short Hand if statement
Short Hand if-else statement
if statement
if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition
is true then a block of statement is executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if statement accepts
boolean values – if the value is true then it will execute the block of statements below it
otherwise not. We can use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:
if condition:
statement1
statement2
i = 10
if (i > 15):
Output:
I am Not in if
As the condition present in the if statement is false. So, the block below the if statement
is not executed.
if-else
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else
if the condition is false. Here comes the else statement. We can use the else statement
with if statement to execute a block of code when the condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flow Chart:-
Python3
#!/usr/bin/python
i = 20;
if (i < 15):
else:
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the condition present in the
if statement is false after calling the statement which is not in block(without spaces).
nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes, Python allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if
statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flow chart:-
Python3
#!/usr/bin/python
i = 10
if (i == 10):
# First if statement
if (i < 15):
# Nested - if statement
# it is true
if (i < 12):
else:
Output:
i is smaller than 15
i is smaller than 12 too
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the
top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
Syntax:-
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flow Chart:-
Example:-
Python3
#!/usr/bin/python
i = 20
if (i == 10):
elif (i == 15):
elif (i == 20):
else:
print ("i is not present")
Output:
i is 20
Short Hand if statement
Whenever there is only a single statement to be executed inside the if block then
shorthand if can be used. The statement can be put on the same line as the if statement.
Syntax:
if condition: statement
Example:
Python3
i = 10
Output:
i is less than 15
Short Hand if-else statement
This can be used to write the if-else statements in a single line where there is only one
statement to be executed in both if and else block.
Syntax:
Python3
# Python program to illustrate short hand if-else
i = 10
Output:
True
Fruitful functions
Some of the built-in functions we have used, such as the math functions, have
produced results. Calling the function generates a new value, which we
usually assign to a variable or use as part of an expression.
e = math.exp(1.0)
height = radius * math.sin(angle)
But so far, none of the functions we have written has returned a value.
In this chapter, we are going to write functions that return values, which we
will call fruitful functions, for want of a better name. The first example
is area, which returns the area of a circle with the given radius:
import math
def area(radius):
temp = math.pi * radius**2
return temp
def area(radius):
return math.pi * radius**2
On the other hand, temporary variables like temp often make debugging
easier.
def absoluteValue(x):
if x < 0:
return -x
else:
return x
Since these return statements are in an alternative conditional, only one will
be executed. As soon as one is executed, the function terminates without
executing any subsequent statements.
Code that appears after a return statement, or any other place the flow of
execution can never reach, is called dead code.
def absoluteValue(x):
if x < 0:
return -x
elif x > 0:
return x
This program is not correct because if x happens to be 0, neither condition is
true, and the function ends without hitting a return statement. In this case,
the return value is a special value called None:
Python - Functions
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard
screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
printme() function −
Live Demo
#!/usr/bin/python
Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
Live Demo
#!/usr/bin/python
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this
would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the
function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
Live Demo
#!/usr/bin/python
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
Live Demo
#!/usr/bin/python
#!/usr/bin/python
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an idea on
default arguments, it prints default age if it is not passed −
Live Demo
#!/usr/bin/python
Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and are
not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call. Following is a simple example −
Live Demo
#!/usr/bin/python
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python
#!/usr/bin/python
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −
Global variables
Local variables
# Function to add 2
# to a number
def add(x):
return x + 2
# Function to multiply
# 2 to a number
def multiply(x):
return x * 2
multiply(add(5)))
Output:
Adding 2 to 5 and multiplying the result with 2: 14
Explanation
First the add() function is called on input 5. The add() adds 2 to the input and the output
which is 7, is given as the input to multiply() which multiplies it by 2 and the output is
14.
Recursion in Python
The term Recursion can be defined as the process of defining something in terms of itself.
In simple words, it is a process in which a function calls itself directly or indirectly.
# Recursive function
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) +
recursive_fibonacci(n-2))
n_terms = 10
# check if the number of terms is valid
if n_terms <= 0:
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
Output:
Fibonacci series:
0
1
1
2
3
5
8
13
21
34
Example 2:
The factorial of 6 is denoted as 6! = 1*2*3*4*5*6 = 720.
# recursively.
# Recursive function
def recursive_factorial(n):
if n == 1:
return n
else:
return n * recursive_factorial(n-1)
# user input
num = 6
if num < 0:
elif num == 0:
print("Factorial of number 0 is 1")
else:
Output:
Factorial of number 6 = 720
Python String
In Python, Strings are arrays of bytes representing Unicode characters. However, Python
does not have a character data type, a single character is simply a string with a length of
1. Square brackets can be used to access elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple
quotes.
Python3
# Creation of String
# Creating a String
print(String1)
# Creating a String
print(String1)
# Creating a String
print(String1)
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
# characters of String
String1 = "GeeksForGeeks"
print(String1)
print(String1[0])
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
String Slicing
To access a range of characters in the String, method of slicing is used. Slicing in a String
is done by using a Slicing operator (colon).
Python3
# Python Program to
# Creating a String
String1 = "GeeksForGeeks"
print(String1)
print(String1[3:12])
# Printing characters between
print(String1[3:-2])
Output:
Initial String:
GeeksForGeeks
Python3
# character of a String
String1 = "Hello, I'm a Geek"
print(String1)
# Updating a character
# of the String
String1[2] = 'p'
print(String1)
Error:
Traceback (most recent call last):
File “/home/360bb1830c83a918fc78aa8979195653.py”, line 10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment
Updating Entire String:
Python3
# entire String
String1 = "Hello, I'm a Geek"
print(String1)
# Updating a String
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deletion of a character:
Python3
print(String1)
# Deleting a character
# of the String
del String1[2]
print(String1)
Error:
Traceback (most recent call last):
File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line 10, in
del String1[2]
TypeError: ‘str’ object doesn’t support item deletion
Deleting Entire String:
Deletion of entire string is possible with the use of del keyword. Further, if we try to print
the string, this will produce an error because String is deleted and is unavailable to be
printed.
Python3
# entire String
String1 = "Hello, I'm a Geek"
print(String1)
# Deleting a String
del String1
print(String1)
Error:
Traceback (most recent call last):
File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in
print(String1)
NameError: name ‘String1’ is not defined
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is very
versatile and powerful tool for formatting of Strings. Format method in String contains
curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.
Python3
# Python Program for
# Formatting of Strings
# Default order
print(String1)
# Positional Formatting
print(String1)
# Keyword Formatting
print(String1)
Output:
Print String in default order:
Geeks For Life
Python3
# Formatting of Integers
String1 = "{0:b}".format(16)
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print(String1)
String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)
Output:
Binary representation of 16 is
10000
one-sixth is :
0.17
A string can be left() or center(^) justified with the use of format specifiers, separated by
colon(:).
Python3
# String alignment
String1 = "|{:<10}|{:^10}|
{:>10}|".format('Geeks','for','Geeks')
print(String1)
print(String1)
Output:
Left, center and right alignment with Formatting:
|Geeks | for | Geeks|
# of Integers
Integer1 = 12.3456789
Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35
Formatting in 3.4f format:
The value of Integer1 is 12.3457
Python string encode() function is used to encode the string using the
provided encoding. Python String count() function returns the number
of occurrences of a substring in the given string. Python string
startswith() function returns True if the string starts with the given
prefix, otherwise it returns False.
Note: All string methods returns new values. They do not change the original
string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the
position of where it was found
index() Searches the string for a specified value and returns the
position of where it was found
islower() Returns True if all characters in the string are lower case
rfind() Searches the string for a specified value and returns the
last position of where it was found
rindex() Searches the string for a specified value and returns the
last position of where it was found
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice
versa
Note: All string methods returns new values. They do not change the original
string.
1. Using numpy.array()
This function of the numpy library takes a list as an argument and returns an
array that contains all the elements of the list. See the example below:
7
import numpy as np
my_list = [2,4,6,8,10]
my_array = np.array(my_list)
# printing my_array
print my_array
print type(my_array)
Run
2. Using numpy.asarray()
This function calls the numpy.array() function inside itself. See the definition
below:
The main difference between np.array() and np.asarray() is that the copy flag
is false in the case of np.asarray(), and true (by default) in the case of np.array().
This means that np.array() will make a copy of the object (by default) and
convert that to an array, while np.asarray() will not.
1. Using Exponent
enter a number: 64
square root: 8.0
In above program, first we’re taking a number from user as input and the
entered value will be converted to int from string and will store into variable
called number. Then we are using exponent (**) sign, which is used to find
out the power of a number. But we know that if a number have power ½ or 0.5
then it will represent to the square root of that number. That’s why we are
using 0.5 as power here. So the number**0.5 will give us square root of that
number and will be stored in variable named as sqrt. In last line we’re just
printing the square root of the number.
1
import math
2 number = int(input("enter a number:"))
3
4
sqrt = math.pow(number, 0.5)
print("square root: ", sqrt)
pow() is also a predefined method to find out power of a number, it takes two
arguments as input, first is the number itself and second one is power of that
number. The program is same as first program where we’re using (**) sign to
find out the square root but only different is this that here we’re using a
predefined method pow() instead of (**) sign to get the power of that
number.
If you’ve any problem related with article or have any other possible way to find
square root in python then please let us know in comments.
Program:--
# Python Program to calculate the square root
# prints 12
print(math.gcd(60, 48))
Output
ALGORITHM:
o STEP 1: Declare and initialize an array.
o STEP 2: The variable sum will be used to calculate the sum of the elements.
Initialize it to 0.
o STEP 3: Loop through the array and add each element of the array to the variable
sum as sum = sum + arr[i].
PROGRAM:
# of elements in given array
# driver function
arr = []
# the value
ans = sum(arr)
# display sum
# Example: Mutable vs
# if x in arr:
Immutable
Objects in
# print arr.index(x) Python
21/09/2021
Every variable in
python holds an
# If you want to implement Linear Search in python instance of an
object. There are
two types of objects
in python
# Linearly search x in arr[] i.e. Mutable and I
mmutable objects.
# If x is present then return its location Whenever an object
is instantiated, it is
# else return -1 assigned a unique
object id. The type
of the object is
defined at the
runtime and it can’t
def search(arr, x):
be changed
afterwards.
However, it’s state
can be changed if it
for i in range(len(arr)): is a mutable object.
To summarise the
difference, mutable
objects can change
if arr[i] == x: their state or
contents and
return i immutable objects
can’t change their
return -1 state or content.
Immutable
Objects : These
are of in-built
5.Binary search in python: types like int,
date:16/09/2021 float, bool,
Recursive
Example
def binarySearchAppr (arr, start, end, x):
# check condition
string, unicode, tuple. In simple words, an immutable object can’t be changed after it
is created.
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Error :
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
message[0] = 'p'
print(message)
Error :
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment
Mutable Objects : These are of type list, dict, set . Custom classes are generally
mutable.
print(color)
color[0] = "pink"
color[-1] = "orange"
print(color)
Output:
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
Example
def my_function(food):
for x in food:
print(x)
my_function(fruits)
9. Tuples: 23/09/2021
tuple AssIgnment: One of the unique syntactic features of the Python language is
the ability to have a tuple on the left side of an assignment statement. This allows
you to assign more than one variable at a time when the left side is a sequence.
Tuples
This is an example of a data structure — a mechanism for grouping and organizing data to
make it easier to use.
The pair is an example of a tuple. Generalizing this, a tuple can be used to group any
number of items into a single compound value. Syntactically, a tuple is a comma-separated
sequence of values. Although it is not necessary, it is conventional to enclose tuples in
parentheses:
Tuples are useful for representing what other languages often call records — some related
information that belongs together, like your student record. There is no description of what
each of these fields means, but we can guess. A tuple lets us “chunk” together related
information and use it as a single thing.
Tuples support the same sequence operations as strings. The index operator selects an
element from a tuple.
>>> julia[2]
1967
But if we try to use item assignment to modify one of the elements of the tuple, we get an
error:
So like strings, tuples are immutable. Once Python has created a tuple in memory, it cannot
be changed.
Of course, even if we can’t modify the elements of a tuple, we can always make
the julia variable reference a new tuple holding different information. To construct the new
tuple, it is convenient that we can slice parts of the old tuple and join up the bits to make the
new tuple. So if julia has a new recent film, we could change her variable to reference a new
tuple that used some information from the old one:
To create a tuple with a single element (but you’re probably not likely to do that too often),
we have to include the final comma, because without the final comma, Python treats
the (5) below as an integer in parentheses:
This does the equivalent of seven assignment statements, all on one easy line. One
requirement is that the number of variables on the left must match the number of elements
in the tuple.
In tuple packing, the values on the left are ‘packed’ together in a tuple:
In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the variables/names
on the right:
Once in a while, it is useful to swap the values of two variables. With conventional
assignment statements, we have to use a temporary variable. For example, to swap a and b:
1 temp = a
2 a = b
3 b = temp
(a, b) = (b,
1
a)
The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned
to its respective variable. All the expressions on the right side are evaluated before any of
the assignments. This feature makes tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right have to
be the same:
For example, we could write a function that returns both the area and the circumference of a
circle of radius r:
1
def f(r):
2
""" Return (circumference, area) of a circle of radius r """
3
c = 2 * math.pi * r
4
a = math.pi * r * r
5
return (c, a)
Python Dictionary:
Dictionary in Python is an unordered collection of data values, used to store data values
like a map, which, unlike other Data Types that hold only a single value as an element,
Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more
optimized.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will
be treated distinctly.
Python3
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Python3
Dict = {}
print(Dict)
# Creating a Dictionary
print(Dict)
# Creating a Dictionary
print(Dict)
Output:
Empty Dictionary:
{}
Python3
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Note- While adding a value, if the key-value already exists, the value gets updated
otherwise a new Key with the value is added to the Dictionary.
Python3
Dict = {}
print(Dict)
Dict[2] = 'For'
Dict[3] = 1
print(Dict)
# to a single Key
Dict['Value_set'] = 2, 3, 4
print(Dict)
Dict[2] = 'Welcome'
print(Dict)
print(Dict)
Output:
Empty Dictionary:
{}
Python3
# Creating a Dictionary
print(Dict['name'])
print(Dict[1])
Output:
Accessing a element using key:
For
# method
print(Dict.get(3))
Output:
Accessing a element using get:
Geeks
In order to access the value of any key in the nested dictionary, use indexing [] syntax.
Python3
# Creating a Dictionary
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
In Python Dictionary, deletion of keys can be done by using the del keyword. Using the
del keyword, specific values from a dictionary as well as the whole dictionary can be
deleted. Items in a Nested dictionary can also be deleted by using the del keyword and
providing a specific nested key and particular key to be deleted from that nested
Dictionary.
Note: The del Dict will delete the entire dictionary and hence printing it after deletion
will raise an Error.
Python3
# Initial Dictionary
print(Dict)
del Dict[6]
print(Dict)
# Nested Dictionary
del Dict['A'][2]
print(Dict)
Output:
Initial Dictionary:
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2:
'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'}
Pop() method is used to return and delete the value of the key specified.
Python3
# Creating a Dictionary
# Deleting a key
pop_ele = Dict.pop(1)
Output:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
Value associated to poped key is: Geeks
The popitem() returns and removes an arbitrary element (key, value) pair from the
dictionary.
Python3
# Creating Dictionary
pop_ele = Dict.popitem()
Output:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
The arbitrary pair returned is: (1, 'Geeks')
All the items from a dictionary can be deleted at once by using clear() method.
Python3
# Creating a Dictionary
Dict.clear()
print(Dict)
Output:
Deleting Entire Dictionary:
{}
Dictionary Methods
Methods Description
clear() The clear() method removes all items from the dictionary.
Problem Description
The program takes a list and key as input and finds the index of the key in the list using
linear search.
Problem Solution
1. Create a function linear_search that takes a list and key as arguemnts.
2. A loop iterates through the list and when an item matching the key is found, the
corresponding index is returned.
3. If no such item is found, -1 is returned.
Program/Source Code
Here is the source code of a Python program to implement linear search. The program
output is shown below.
Case 2:
Enter the list of numbers: 5 2 1 5 -3
The number to search for: 2
2 was found at index 1.
Case 3:
Enter the list of numbers: 3 5 6
The number to search for: 2
2 was not found.
Problem Description
The program sorts a list by bubble sort.
Problem Solution
1. Create a function bubble_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from the length of the
list – 1 to 1.
3. Create an inner loop with a loop variable that counts from 0 up to i – 1.
4. Inside the inner loop, if the elements at indexes j and j + 1 are out of order, then swap
them.
5. If in one iteration of the inner loop there were no swaps, then the list is sorted and one
can return prematurely.
Program/Source Code
Here is the source code of a Python program to implement bubble sort. The program output
is shown below.
def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return
Case 2:
Enter the list of numbers: 5 4 3 2 1
Sorted list: [1, 2, 3, 4, 5]
Case 3:
Enter the list of numbers: 7 3 1 -5 2 10
Sorted list: [-5, 1, 2, 3, 7, 10]
OOP Python:
Python is a great programming language that supports OOP. You will use it to define a class
with attributes and methods, which you will then call. Python offers a number of benefits
compared to other programming languages like Java, C++ or R. It's a dynamic language, with
high-level data types
Python Object-Oriented
Programming (OOP):
Tackle the basics of Object-Oriented Programming (OOP)
in Python: explore classes, objects, instance methods,
attributes and much more!
OOP uses the concept of objects and classes. A class can be thought of as a
'blueprint' for objects. These can have their own attributes (characteristics
they possess), and methods (actions they perform).
OOP Example
An example of a class is the class Dog. Don't think of it as a specific dog, or
your own dog. We're describing what a dog is and can do, in general. Dogs
usually have a name and age; these are instance attributes. Dogs can
also bark; this is a method.
When you talk about a specific dog, you would have an object in
programming: an object is an instantiation of a class. This is the basic
principle on which object-oriented programming is based. So my dog Ozzy,
for example, belongs to the class Dog. His attributes are name =
'Ozzy' and age = '2'. A different dog will have different attributes.
OOP in Python
Python is a great programming language that supports OOP. You will use it
to define a class with attributes and methods, which you will then call.
Python offers a number of benefits compared to other programming
languages like Java, C++ or R. It's a dynamic language, with high-level data
types. This means that development happens much faster than with Java or
C++. It does not require the programmer to declare types of variables and
arguments. This also makes Python easier to understand and learn for
beginners, its code being more readable and intuitive.
pass
In this case, you have a (mostly empty) Dog class, but no object yet. Let's
create one!
Instantiating objects
To instantiate an object, type the class name, followed by two brackets. You
can assign this to a variable to keep track of the object.
ozzy = Dog()
self.name = name
self.age = age
You can see that the function now takes two arguments
after self: name and age. These then get assigned
to self.name and self.age respectively. You can now now create a
new ozzy object, with a name and age:
ozzy = Dog("Ozzy", 2)
To access an object's attributes in Python, you can use the dot notation. This
is done by typing the name of the object, followed by a dot and the attribute's
name.
print(ozzy.name)
print(ozzy.age)
Ozzy
2
The str() function is used here to convert the age attribute, which is an
integer, to a string, so you can use it in the print() function.
self.name = name
self.age = age
def bark(self):
print("bark bark!")
The bark method can now be called using the dot notation, after instantiating
a new ozzy object. The method should print "bark bark!" to the screen.
Notice the parentheses (curly brackets) in .bark(). These are always used
when calling a method. They're empty in this case, since the bark() method
does not take any arguments.
ozzy = Dog("Ozzy", 2)
ozzy.bark()
bark bark!
Recall how you printed ozzy earlier? The code below now implements this
functionality in the Dog class, with the doginfo() method. You then
instantiate some objects with different properties, and call the method on
them.
class Dog:
self.name = name
self.age = age
def bark(self):
print("bark bark!")
def doginfo(self):
print(self.name + " is " + str(self.age) + " year(s)
old.")
ozzy = Dog("Ozzy", 2)
filou = Dog("Filou", 8)
ozzy.doginfo()
skippy.doginfo()
filou.doginfo()
As you can see, you can call the doginfo() method on objects with the dot
notation. The response now depends on which Dog object you are calling the
method on.
Since dogs get older, it would be nice if you could adjust their age
accordingly. Ozzy just turned 3, so let's change his age.
ozzy.age = 3
print(ozzy.age)
It's as easy as assigning a new value to the attribute. You could also
implement this as a birthday() method in the Dog class:
class Dog:
self.name = name
self.age = age
def bark(self):
print("bark bark!")
def doginfo(self):
old.")
def birthday(self):
self.age +=1
ozzy = Dog("Ozzy", 2)
print(ozzy.age)
ozzy.birthday()
print(ozzy.age)
Now, you don't need to manually change the dog's age. whenever it is its
birthday, you can just call the birthday() method.
self.name = name
self.age = age
def bark(self):
print("bark bark!")
def doginfo(self):
old.")
def birthday(self):
self.age +=1
self.buddy = buddy
buddy.buddy = self
You can now call the method with the dot notation, and pass it
another Dog object. In this case, Ozzy's buddy will be Filou:
ozzy = Dog("Ozzy", 2)
filou = Dog("Filou", 8)
ozzy.setBuddy(filou)
If you now want to get some information about Ozzy's buddy, you can use
the dot notation twice:. First, to refer to Ozzy's buddy, and a second time to
refer to its attribute.
print(ozzy.buddy.name)
print(ozzy.buddy.age)
Filou
print(filou.buddy.age)
Ozzy
The buddy's methods can also be called. The self argument that gets passed
to doginfo() is now ozzy.buddy, which is filou.
ozzy.buddy.doginfo()
Filou is 8 year(s) old.
INHERITANCE Ii
Data Scien
Inheritance In Python With Examples: All You Need To Know
Python programming language is easy to learn and works on both procedural and object oriented
programming approach. Inheritance is one such concept in object oriented programming. Code
reusability being the forte of inheritance, it helps in a lot of applications when we are working on
Python. Following are the concepts discussed in this article:
What Is Inheritance?
init Function
Types Of Inheritance
o Single Inheritance
o Multiple Inheritance
o Multilevel Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
Python super() Function
Python Method Overriding
What Is Inheritance?
The method of inheriting the properties of parent class into a child class is known as inheritance.
It is an OOP concept. Following are the benefits of inheritance.
1. Code reusability- we do not have to write the same code again and again, we can just
inherit the properties we need in a child class.
2. It represents a real world relationship between parent class and child class.
3. It is transitive in nature. If a child class inherits properties from a parent class, then all
other sub-classes of the child class will also inherit the properties of the parent class.
1 class Parent():
2 def first(self):
print('first function')
3
4
class Child(Parent):
5
def second(self):
6
print('second function')
7
8
ob = Child()
9
ob.first()
10
ob.second()
11
Output:
first function
second function
In the above program, you can access the parent class function using the child class object.
Sub-classing
Calling a constructor of the parent class by mentioning the parent class name in the declaration
of the child class is known as sub-classing. A child class identifies its parent class by sub-
classing.
__init__( ) Function
The __init__() function is called every time a class is being used to make an object. When we
add the __init__() function in a parent class, the child class will no longer be able to inherit the
parent class’s __init__() function. The child’s class __init__() function overrides the parent
class’s __init__() function.
Explore Curriculum
1 class Parent:
self.firstname = fname
3
self.age = fage
4
def view(self):
5
print(self.firstname , self.age)
6
class Child(Parent):
7
def __init__(self , fname , fage):
8
9
Parent.__init__(self, fname, fage)
10
self.lastname = "edureka"
11
def view(self):
12 print("course name" , self.firstname ,"first came", self.age , " years ago
master python")
13
ob = Child("Python" , '28')
14
ob.view()
15
Types Of Inheritance
Depending upon the number of child and parent classes involved, there are four types of
inheritance in python.
Single Inheritance
When a child class inherits only a single parent class.
1 class Parent:
2 def func1(self):
Multiple Inheritance
When a child class inherits from more than one parent class.
1
class Parent:
2
def func1(self):
3
print("this is function 1")
4 class Parent2:
5 def func2(self):
8 def func3(self):
10
ob = Child()
11
ob.func1()
12
ob.func2()
13
ob.func3()
14
Multilevel Inheritance
When a child class becomes a parent class for another child class.
1 class Parent:
2 def func1(self):
7 class Child2(Child):
9 ob = Child2()
ob.func1()
10
ob.func2()
11
ob.func3()
12
Hierarchical Inheritance
Hierarchical inheritance involves multiple inheritance from the same base or parent class.
1 class Parent:
2 def func1(self):
10 ob = Child()
11 ob1 = Child2()
12 ob.func1()
13
ob.func2()
14
Hybrid Inheritance
Hybrid inheritance involves multiple inheritance taking place in a single program.
1
class Parent:
2
def func1(self):
3
print("this is function one")
4
5
class Child(Parent):
6 def func2(self):
9 class Child1(Parent):
10 def func3(self):
12
class Child3(Parent , Child1):
13
def func4(self):
14
print(" this is function 4")
15
16
ob = Child3()
17
ob.func1()
18
1 class Parent:
2
def func1(self):
3
print("this is function 1")
4
class Child(Parent):
5
def func2(self):
6
Super().func1()
7
print("this is function 2")
8
9
ob = Child()
10 ob.func2()
1
class Parent:
2 def func1(self):
5 class Child(Parent):
6 def func1(self):
8
ob = Child()
9
ob.func1()
10
The functionality of the parent class method is changes by overriding the same method in the
child class.
Inheritance is one of the most important concept of OOP. It provides code reusability, readability
and transition of properties which helps in optimized and efficient code building. Python
programming language is loaded with concepts like inheritance. Enormous python applications
calls for increased number of python programmers in the recent market..
class Dog:
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'
As discussed in A Word About Names and Objects, shared data can have possibly
surprising effects with involving mutable objects such as lists and dictionaries. For
example, the tricks list in the following code should not be used as a class variable
because just a single list would be shared by all Dog instances:
1 class Parent:
2
def __init__(self , fname, fage):
3
self.firstname = fname
4
self.age = fage
5
def view(self):
6
print(self.firstname , self.age)
7
class Child(Parent):
8 def __init__(self , fname , fage):
10 self.lastname = "edureka"
11 def view(self):
12 print("course name" , self.firstname ,"first came", self.age , " years ago." , self.las
master python")
13
ob = Child("Python" , '28')
14 ob.view()
15
Unit-5 26/10/2021
What is Python file handling?
Python too supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files. ... Python
treats file differently as text or binary and this is important. Each line of code includes a
sequence of characters and they form text file.
File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting
files.
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not
exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
Because "r" for read, and "t" for text are the default values, you do not need
to specify them.
demofile.txt
The open() function returns a file object, which has a read() method for reading
the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
Run Example »
If the file is located in a different location, you will have to specify the file path,
like this:
Example
Open a file on a different location:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Run Example »
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify
how many characters you want to return:
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
Run Example »
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
Run Example »
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Run Example »
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Run Example »
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Run Example »
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
Run Example »
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Delete a File
To delete a file, you must import the OS module, and run
its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Example
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
Adding the capability of processing Python command line arguments provides a user-
friendly interface to your text-based command line program. It’s similar to what a
graphical user interface is for a visual application that’s manipulated by graphical
elements or widgets.
Python exposes a mechanism to capture and extract your Python command line
arguments. These values can be used to modify the behavior of a program. For
example, if your program processes data read from a file, then you can pass the name
of the file to your program, rather than hard-coding the value in your source code.
1. Syntax errors
2. Logical errors (Exceptions)
Syntax errors
When the proper syntax of the language is not followed then a syntax error is thrown.
Example
Python3
amount = 10000
if(amount>2999)
It returns a syntax error message because after the if statement a colon: is missing. We
can fix this by writing the correct syntax.
logical errors(Exception)
When in the runtime an error that occurs after passing the syntax test is called exception
or logical type. For example, when we divide any number by zero then the
ZeroDivisionError exception is raised, or when we import a module that does not exist
then ImportError is raised.
Example 1:
Python3
marks = 10000
a = marks / 0
print(a)
Output:
In the above example the ZeroDivisionError as we are trying to divide a number by 0.
Example 2: When indentation is not correct.
Python3
if(a<3):
print("gfg")
Output:
Some of the common built-in exceptions are other than above mention exceptions are:
Exception Description
TypeError It occurs when a function and operation are applied in an incorrect type.
Error Handling
When an error and an exception are raised then we handle that with the help of the
Handling method.
Python3
try:
print("code start")
print(1 / 0)
except:
finally:
print("GeeksForGeeks")
Output:
code start
an error occurs
GeeksForGeeks
Raising exceptions for a predefined condition
When we want to code for the limitation of certain conditions then we can raise an
exception.
Example
Python3
try:
amount = 1999
else:
except ValueError as e:
print(e)
Output:
Packages in Python
Introduction
We learned that modules are files containing Python statements and definitions, like
function and class definitions. We will learn in this chapter how to bundle multiple modules
together to form a package.
A package is basically a directory with Python files and a file with the name __init__.py.
This means that every directory inside of the Python path, which contains a file
named __init__.py, will be treated as a package by Python. It's possible to put several
modules into a Package.
Packages are a way of structuring Python’s module namespace by using "dotted module
names". A.B stands for a submodule named B in a package named A. Two different
packages like P1 and P2 can both have modules with the same name, let's say A, for
example. The submodule A of the package P1 and the submodule A of the package P2 can
be totally different. A package is imported like a "normal" module. We will start this chapter
with a simple example.
We will demonstrate with a very simple example how to create a package with some Python
modules. First of all, we need a directory. The name of this directory will be the name of the
package, which we want to create. We will call our package "simple_package". This
directory needs to contain a file with the name __init__.py. This file can be empty, or it
can contain valid Python code. This code will be executed when a package is imported, so it
can be used to initialize a package, e.g. to make sure that some other modules are
imported or some values set. Now we can put all of the Python files which will be the
submodules of our module into this directory. We create two simple files a.py and b.py just
for the sake of filling the package with modules.
We will also add an empty file with the name __init__.py inside of simple_package
directory.
Let's see what happens, when we import simple_package from the interactive Python shell,
assuming that the directory simple_package is either in the directory from which you call
the shell or that it is contained in the search path or environment variable "PYTHONPATH"
(from your operating system):
import simple_package
simple_package/a
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-3-347df8a711cc> in <module>
----> 1 simple_package/a
We can see that the package simple_package has been loaded but neither the module "a"
nor the module "b"! We can import the modules a and b in the following way:
from simple_package import a, b
a.bar()
b.foo()
Hello, function 'bar' from module 'a' calling
Hello, function 'foo' from module 'b' calling
As we have seen at the beginning of the chapter, we can't access neither "a" nor "b" by
solely importing simple_package.
Yet, there is a way to automatically load these modules. We can use the file __init__.py for
this purpose. All we have to do is add the following lines to the so far empty
file __init__.py:
import simple_package.a
import simple_package.b