Python
Python
Features in Python
Python is a dynamic, high-level, free open source, and interpreted programming language. It
supports object-oriented programming as well as procedural-oriented programming. In
Python, we don’t need to declare the type of variable because it is a dynamically typed
language. For example, x = 10 Here, x can be anything such as String, int, etc. In this article
we will see what characteristics describe the python programming language
1. Free and Open Source
Python language is freely available at the official website and you can download it from the
given download link below click on the Download Python keyword. Download Python Since
it is open-source, this means that source code is also available to the public. So you can
download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as
compared to other languages like C, C#, Javascript, Java, etc. It is very easy to code in the
Python language and anybody can learn Python basics in a few hours or days. It is also a
developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python’s syntax
is really straightforward. The code block is defined by the indentations rather than by
semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-
oriented language and concepts of classes, object encapsulation, etc.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to
remember the system architecture, nor do we need to manage the memory.
Python is a dynamically-typed language. That means the type (for example- int, double,
long, etc.) for a variable is decided at run time not in advance because of this feature we
don’t need to specify the type of variable.
With a new project py script, you can run and write Python codes in HTML with the help of
some simple tags <py-script>, <py-env>, etc. This will help you do frontend development
work in Python like javascript. Backend is the strong forte of Python it’s extensively used for
this work cause of its frameworks like Django and Flask.
15. Allocating Memory Dynamically
In Python, the variable data type does not need to be specified. The memory is
automatically allocated to a variable at runtime when it is given a value. Developers do not
need to write int y = 18 if the integer value 15 is set to y. You may just type y=18.
INSTALLATION
Python is a powerful, general-purpose programming language that is widely used for web
development, data science, artificial intelligence, and scientific computing. If you're new to
programming and want to get started with Python, you'll need to install it on your
computer.
BASIC SYNTAX
The Python syntax defines a set of rules that are used to create a Python Program. The
Python Programming Language Syntax has many similarities to Perl, C, and Java
Programming Languages. However, there are some definite differences between the
languages.
print("Hello, World!")
Hello, World!
INDENTATION
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Eg:
if 5 > 2:
print("Five is greater than two!")
PYTHON VARIABLES
Creating Variables:
Variables do not need to be declared with any particular type, and can even change type
after they have been set.
Eg:
casting
if you want to specify the data type of a variable, this can be done with casting.
eg:
x = str(3)
y = int(3) z = float(3)
You can get the data type of a variable with the type() function.
Eg:
x=5
y = "John"
print(type(x))
print(type(y))
Eg:X = "John"
x = 'John'
Case-Sensitive
Eg:
DATA TYPES
Built-in Data Types: Variables can store data of different types, and different types can do
different things.Python has the following data types built-in by default, in these categories:
You can get the data type of any object by using the type() function:
In Python, the data type is set when you assign a value to a variable:
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
If you want to specify the data type, you can use the following constructor functions:
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = range(6) range
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Operators are used to perform operations on variables and values.In the example below, we
use the + operator to add together two values:
Eg: print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not (x < 5 and x < 10)
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
is not Returns True if both variables are not the same object x is not y
in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x
not in y
<< Zero fill left shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off x << 2
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off x >> 2
8.Operator Precedence
The precedence order is described in the table below, starting with the highest precedence
at the top:
Operator Description
() Parentheses
** Exponentiation
^ Bitwise XOR
| Bitwise OR
== != > >= < <= is is not in not in Comparisons, identity, and membership
operators
and AND
or OR
If two operators have the same precedence, the expression is evaluated from left to right.
Example: Addition + and subtraction - has the same precedence, and therefor we evaluate
the expression from left to right:
print(5 + 4 - 7 + 3)
CASTING
There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
EG:Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
eg:Floats:
x = float(1) y = float(2.8) z = float("3") w = float("4.2")
eg:Strings:
CONDITIONAL STATEMENTS
IF STATEMENT
EG:If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".
if..else Statement
In conditional if Statement the additional block of code is merged as else statement which
is performed when if condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
x =3
if x == 4:
print("Yes")
else:
print("No")
Output:
No
Nested If
You can have if statements inside if statements, this is called nested if statements.
EG:x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
LOOPING STATEMENTS
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
The for loop does not require an indexing variable to set beforehand.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
The while Loop
With the while loop we can execute a set of statements as long as a condition is
true.
Example:
i = 1
while i < 6:
print(i)
i += 1
Nested Loops
A nested loop is a loop inside a loop.The "inner loop" will be executed one time for each
iteration of the "outer loop":
for x in adj:
for y in fruits:
print(x, y)
CONTROLSTATEMENTS
Control statements in Python are a powerful tool for managing the flow of execution. They
allow developers to make decisions based on specific conditions and modify the normal
sequential flow of a program. By using control statements effectively, developers can write
more efficient and effective code.
The break statement is used to terminate a loop, i.e., for loop, while loop, or nested loop.
When a break statement executes inside a loop, it immediately terminates the loop and
transfers control to the statement following the loop.
while condition:
# statements
if condition:
break
In this syntax, the break statement is used inside a loop (while loop or for loop). When the condition
specified in the if statement is true, the break statement is executed, and the control is transferred
to the next statement after the loop. This means that the loop is terminated, and the code execution
continues from the statement after the loop.
if num % 2 == 0:
break
Output:
Continue Statement in Python: The continue statement is used to skip a particular iteration of a
loop when a specific condition is met. When a continue statement is executed inside a loop, it
skips the current iteration of the loop and jumps to the next iteration.
while condition:
if condition:
continue
# statements after the continue statement
In this syntax, when the condition specified in the if statement is true, the continue statement is
executed, and the control is transferred to the next iteration of the loop. This means that the current
iteration is skipped, and the loop continues with the next iteration.
if num % 2 == 0:
continue
print(num)
Output:
1
3
7
9
11
15
The pass statement is a placeholder statement that does nothing. It is used when a statement is
required syntactically, but you don’t want to execute any code. Pass is mostly used as a placeholder
for functions or conditional statements that have not yet been implemented.
while condition:
if condition:
pass
x = 25
if x > 15:
pass
else:
Explanation: In this example, we have a variable called x that has a value of 10. We want to print a
message when the value of x is greater than 5. We use an if statement to check if the value of x is
greater than 5. Inside the if statement, we use the pass statement as a placeholder for the code that
we haven’t written yet. If the value of x is less than or equal to 5, we print a message.
When we run this program, it will not output anything, as the pass statement does nothing.
However, it serves as a placeholder for the code that we will write in the future.
MODULE2
There are two kinds of memory in a computer i.e. Primary and Secondary memory every
file that you saved or anyone saved is on secondary memory cause any data in primary
memory is deleted when the computer is powered off. So when you need to change any
text file or just to work with them in python you need to load that file into primary
memory. Python interacts with files loaded in primary memory or main memory
through “file handlers” ( This is how your operating system gives access to python to
interact with the file you opened by searching the file in its memory if found it returns a
file handler and then you can work with the file ).
Opening a File
It is done using the open() function. No module is required to be imported for this
function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, the full address
of the file should be written in place of the filename. Note: The r is placed before the
filename to prevent the characters in the filename string to be treated as special
characters. For example, if there is \temp in the file address, then \t is treated as the tab
character, and an error is raised of invalid address. The r makes the string raw, that is, it
tells that the string is without any special characters. The r can be ignored if the file is in
the same directory and the address is not being placed.
file1 = open("MyFile1.txt","a")
Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at the
time when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()
file1 = open("MyFile.txt","a")
file1.close()
Writing to a file
file1.write("Hello \n")
file1.writelines(L)
file1 = open("myfile.txt","r+")
print(file1.read())
print()
file1.seek(0)
print(file1.readline())
print()
file1.seek(0)
print(file1.read(9))
print()
file1.seek(0)
print(file1.readline(9))
file1.seek(0)
# readlines function
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Appending to a file
file1.writelines(L)
file1.close()
# Append-adds at last
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print(file1.readlines())
print()
file1.close()
# Write-Overwrites
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print(file1.readlines())
print()
file1.close()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
The sys module in Python provides various functions and variables that are used to manipulate
different parts of the Python runtime environment. It allows operating on the interpreter as it
provides access to the variables and functions that interact strongly with the interpreter. Let’s
consider the below example.
Python sys.version
In this example, sys.version is used which returns a string containing the version of Python
Interpreter with some additional information. This shows how the sys module interacts with the
interpreter. Let us dive into the article to get more information about the sys module.
import sys
print(sys.version)
Output:
3.6.9 (default, Oct 8 2020, 12:12:24)
[GCC 8.4.0]
Input and Output using Python Sys
The sys modules provide variables for better control over input or output. We can even redirect
the input and output to other devices. This can be done using three variables –
Python contains several modules that has a number of built-in functions to manipulate
and process data. Python has also provided modules that help us to interact with the
operating system and the files. These kinds of modules can be used for directory
management also. The modules that provide the functionalities are listed below:
os and os.path
filecmp
tempfile
shutil
The os module is used to handle files and directories in various ways. It provides
provisions to create/rename/delete directories. This allows even to know the current
working directory and change it to another. It also allows one to copy files from one
directory to another. The major methods used for directory management is explained
below.
Creating new directory:
os.mkdir(name) method to create a new directory.
The desired name for the new directory is passed as the parameter.
By default it creates the new directory in the current working directory.
If the new directory has to be created somewhere else then that path has to be
specified and the path should contain forward slashes instead of backward ones.
import os
os.mkdir('new_dir')
# creates in D:\
os.mkdir('D:/new_dir')
Output:
String format : /home/nikhil/Desktop/gfg
Byte string format : b'/home/nikhil/Desktop/gfg'
Renaming a directory:
import os
os.rename('file1.txt','file1_renamed.txt')
If renaming and moving the file to some other directory is required, then the code snippet
should be:
import os
os.renames('file1.txt', 'D:/file1_renamed.txt')
Changing Current Working Directory (CWD):
Every process in the computer system will have a directory associated with it, which is known
as Current Working Directory(CWD).
os.chdir() method is used to change it.
The parameter passed is the path/name of the desired directory to which one wish to shift.
Form example, If we need to change the CWD to my_folder in D:/, then the following code snippet
is used.
import os
# Changing directory
os.chdir('/home/nikhil/Desktop/')
Output:
Current directory : /home/nikhil/Desktop/gfg
Current directory : /home/nikhil/Desktop
For example: Listing the files in the CWD- GeeksforGeeks (root directory)
import os
Output:
The files in CWD are : [‘site folder’, ‘.directory’, ‘proxy.txt’, ‘poem python.txt’, ‘left bar’,
‘images’, ‘Welcome to GeeksforGeeks!\nPosts Add Ne.txt’, ‘trash.desktop’, ‘gfg.py’, ‘Sorry,
you can not update core for some tim.txt’, ‘gfgNikhil Aggarwal.png’, ‘0001.jpg’, ‘gfg’,
‘gfgcerti.png’, ‘raju’, ‘images big’]
Removing a directory
For example, Let us consider a directory K:/files. Now to remove it, one has to ensure
whether it is empty and then proceed for deleting.
import os
dir_li=os.listdir('k:/files')
if len(dir_li)==0:
else:
os.rmdir('k:/files')
To check whether it is a directory:
Given a directory name or Path, os.path.isdir(path) is used to validate whether the path is a
valid directory or not.
It returns boolean values only. Returns true if the given path is a valid directory
otherwise false.
import os
# GeeksforGeeks
cwd='/'
print(os.path.isdir(cwd))
other='K:/'
print(os.path.isdir(other))
Output
True
False
To get size of the directory:
os.path.getsize(path_name) gives the size of the directory in bytes.
OSError is raised if, invalid path is passed as parameter.
import os
print(os.path.getsize(os.getcwd()))
Output
4096
Getting access and modification times:
To get the last accessed time of a directory : os.path.getatime (path)
To get the last modified time of the directory : os.path.getmtime (path)
These methods return the number of seconds since the epoch. To format it, datetime
module’s strftime( ) function can be used.
import os
import datetime as dt
access_time=dt.datetime.fromtimestamp(os.path.getatime(os.getcwd()))
.strftime('%Y-%m-%d %I:%M %p')
modification_time=dt.datetime.fromtimestamp(os.path.getmtime(os.getc
wd())).strftime('%Y-%m-%d %I:%M %p')
Output
Before conversion :
last access time : 1596897099.56
last modification time : 1596897099.56
After conversion :
last access time : 2020-08-08 02:31 PM
last modification time : 2020-08-08 02:31 PM
filecmp module
This module provides various functions to perform comparison between files and directories. To
compare the directories, an object has to be created for the class filecmp.dircmp that describes
which files to ignore and which files to hide from the functions of this class. The constructor has to
be invoked before calling any of the functions of this class. The constructor can be invoked as
given below:
d = filecmp . dircmp( dir_1, dir_2, ignore=[a,b,c]/None, hide=[d,e,f]/None )
Functions for comparing directories:
1. d.report() : Compares the two directories given while invoking the constructor and presents a
summary regarding the list of files in both the directories. In case any identical files are found,
they are also listed. Common sub-directories are also printed in the output.
import filecmp as fc
import os
print("comparison 1 :")
d.report()
2. d.report_partial_closure() : Prints out the comparison between the directories passed and also
the comparisons between the immediate common sub-directories.
import filecmp as fc
import os
print("comparison 2 :")
d.report_partial_closure()
3. d.report_full_closure() : It is same as the previous one, but does the work recursively. It
compares and displays the common sub-directories, identical files and common funny
cases (the two things do not match in type, ie., one is a directory and another is a file.)
import filecmp as fc
import os
print("comparison 3 :")
d.report_full_closure()
tempfile module:
mkdtemp() :
It is used to create a temporary directory by passing the parameters suffix, prefix and dir.
The suffix and prefix corresponds to the naming conventions for the created temp directory.
suffix decides how the file name should end and prefix is decides the beginning of the name
and mostly set to ‘tmp‘.
The dir parameter specifies the path where the temporary directory should be created. By
default the dir is set to the temp directory created by the Operating systems.
This temporary directories are readable, writable and searchable only by the creator using the
creator’s unique ID.
The user who created the temp dir is responsible for deleting the temporary directory upon
completion of the work.
It returns the path of the created new directory.
import tempfile as tf
f = tf.mkdtemp(suffix='', prefix='tmp')
print(f)
Output
/tmp/tmp0ndvk7p_
TemporaryDirectory():
This function makes use of mkdtemp() to create a temporary directory and the same
parameters are passed here also.
The main difference is, the object created as a result acts as a context manager.
The user need not manually delete the created temporary file, it is cleared automatically by
the file system.
To get the name of the newly created temp directory, object.name can be used.
To delete the temporary dir explicitly, cleanup( ) function can be used.
import tempfile as tf
f = tf.TemporaryDirectory(suffix='', prefix='tmp')
f.cleanup()
This module is concerned with number of high-level operations on files and directories. It
allows copying/moving directories from a source to destination.
shutil.copytree(s, d, symlinks=False, ignore=None, copy_function=copy2,
ignore_dangling_symlinks=False):
Recursively copies the source directory (s) to the destination directory (d) provided
that ‘d’ does not already exists.
symlinks are also known as symbolic links which denote some virtual files or reference
folders or folders that located somewhere else. It can take values like true, false or
omitted. If true, the symlinks in source are marked as symlinks in the destination also,
but the associated metadata will not be copied. If the value is false or omitted, the
contents as well as the metadata of the linked file are copied to the destination.
For ignore, a callable that takes the directory being visited and its contents like the
return value of os.listdir() since, copytree() is a recursive functions. The files to be
ignored while copying can be named using this parameter.
The copy2 function is used as the default copy_function because it allows copying
metadata. copy(), copystat() can also be used.
shutil.rmtree(path, ignore_errors=False, onerror=None):
Deletes an entire directory. This overcomes the main disadvantage of os.rmdir() that it
deletes the directory only if it is empty.
The path should be a valid directory. The symlinks to a directory won’t be accepted.
If ignore_error is true, then the errors raised while removing the directory will be
ignored. If false or omitted is given, then the raised errors should be handled by the
ones mentioned in onerror parameter.
onerror is a callable that takes three parameters namely function, path and excinfo.
The first is the function that raises the exception, the next is the path to be passed to
the function and the last is the exception information returned by sys.exc_info().
shutil.move(s,d):
Recursively moves the source directory to the destination specified.
The destination is not supposed to exist already, if exists based on the os.rename()
semantics, it will be overwritten.
CSV
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a
spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each
line of the file is a data record. Each record consists of one or more fields, separated by
commas. The use of the comma as a field separator is the source of the name for this file
format.
To create a CSV file and write data into it using Python, we have to follow a certain
set of instructions:
Open the CSV file in writing (w mode) with the help of open() function
Create a CSV writer object by calling the writer() function of the csv module
Write data to CSV file by calling either the writerow() or writerows() method of the CSV
writer object
Finally, close the CSV file
CSV module is used to read/ write CSV files in Python. To use the csv module in our
program we have to first import using the following statement:
Import csv
Before learning about different types of functions let us study in brief about dialects,
Dialects are used to group multiple formatting patterns like delimiter, skipinitialspace,
quoting, and escapechar into a single dialect name, thus removing redundancy when
working with multiple files. We will learn more about dialects later in this article.
Different types of functions in the csv module are as follows:
csv.field_size_limit - This function returns the current maximum field size allowed by the
parser.
csv.get_dialect - It returns the dialect associated with a name.
csv.list_dialects - It returns the names of all registered dialects.
csv.reader - This function reads the data from a CSV file.
csv.register_dialect - It associates dialect with a name, and the name must be a string or a
Unicode object.
csv.writer - This function writes the data to a CSV file.
csv.unregister_dialect - It deletes the dialect, which is associated with the name from the
dialect registry. If a name is not a registered dialect name, then an error is raised.
csv.QUOTE_ALL - It instructs the writer objects to quoting all fields. Msc Computer Science
STAS EDAPPALLY 3
csv.QUOTE_MINIMAL - It instructs the writer to quote only those fields containing special
characters such as quote char, delimiter, etc.
csv.QUOTE_NONNUMERIC - It instructs the writer objects to quote all the non-numeric
fields.
csv.QUOTE_NONE - It instructs the writer object never to quote the fields.
The ‘with‘ keyword is used along with the open() method as it simplifies exception handling
and automatically closes the CSV file.
Writing to CSV file
csv.writer class is used to insert data to the CSV file. This class returns a writer object which
is responsible for converting the user’s data into a delimited string. A CSV file object should
be opened with newline=” otherwise, newline characters inside the quoted fields will not be
interpreted correctly.
csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().
writerow(): This method writes a single row at a time. Field row can be written using this method.
Syntax: writerow(fields)
writerows(): This method is used to write multiple rows at a time. This can be used to write rows
list.
Syntax: writerows(rows)
Python String
Python does not have a character data type, a single character is simply a string with a
length of 1.
Example:
"Geeksforgeeks" or 'Geeksforgeeks' or "a"
print('A')
Output:
A Computer Science portal for geeks
Creating a String in Python
Strings in Python can be created using single quotes or double quotes or even triple
quotes. Let us see how we can define a string in Python.
Example:
In this example, we will demonstrate different ways to create a Python String. We will
create a string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“””
“””). The triple quotes can be used to declare multiline strings in Python.
# Creation of String
# Creating a String
print(String1)
# Creating a String
print(String1)
# Creating a String
String1 = '''Geeks
For
Life'''
print(String1)
In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to
be passed as an index, float or other types that will cause a TypeError.
Example:
In this example, we will define a string in Python and access its characters using positive and
negative indexing. The 0th element will be the first character of the string whereas the -1th
element is the last character of the string.
# characters of String
String1 = "GeeksForGeeks"
print(String1)
print(String1[0])
print(String1[-1])
The replace() method replaces a specified phrase with another specified phrase.
Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
Syntax:string.replace(oldvalue, newvalue, count)
Parameter Values
Parameter Description
count Optional. A number specifying how many occurrences of the old value you want to replac
occurrences
Example:
x = txt.replace("bananas", "apples")
print(x)
The len() function returns the number of items in an object.When the object is a string,
the len() function returns the number of characters in the string.
Syntax:len(object)
Parameter Values
Parameter Description
The lower() method returns a string where all characters are lower case.Symbols and Numbers are
ignored.
Syntax:string.lower()
Parameter Values
No parameters
Example
x = txt.lower()
print(x)
The upper() method returns a string where all characters are in upper case.
Syntax:string.upper()
Parameter Values
No parameters
Example
print(x)
The split() method splits a string into a list.You can specify the separator, default separator is any
whitespace.
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax:string.split(separator, maxsplit)
Parameter Values
Parameter Description
separator Optional. Specifies the separator to use when splitting the string. By default any whitespa
maxsplit Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences"
Python | Get the substring from given string using list slicing
What is substring?
A substring is a portion of a string. Python offers a variety of techniques for producing
substrings, as well as for determining the index of a substring and more.
String Slicing in Python
How String slicing in Python works
For understanding slicing we will use different methods, here we will cover 2 methods of string
slicing, one using the in-build slice() method and another using the [:] array slice. String slicing in
Python is about obtaining a sub-string from the given string by slicing it respectively from start to
end.
The slice() constructor creates a slice object representing the set of indices specified by
range(start, stop, step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the
slicing of object stops. step: It is an optional argument that determines the increment between
each index for slicing. Return Type: Returns a sliced object containing elements in the given range
only.
Example:
# Python program to demonstrate
# string slicing
# String slicing
String = 'ASTRING'
s1 = slice(3)
s2 = slice(1, 5, 2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
SR
GITA
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string using list slicing and Array slicing both syntax-wise and execution-
wise. A start, end, and step have the same mechanism as the slice() constructor.
Below we will see string slicing in Python with examples.
# string slicing
# String slicing
String = 'GEEKSFORGEEKS'
print(String[:3])
Output:
GEE
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
Example
print("Hello")
print('Hello')
Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:
Example
a = "Hello"
print(a)
Multiline Strings
Example
Like many other popular programming languages, strings in Python 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.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
for x in "banana":
print(x)
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Use it in an if statement:
Example
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Example
Example
1) Binary to Decimal
For Binary to Decimal conversion, the binary number uses weights assigned to each bit position. like
a=1001
a = 1*23 +0*22+0*21+1*20
a= (8+0+0+1) = 9
Output:
2) Binary to Octal
First convert binary number to decimal number by assigning weight to each binary bit.
a = 1 0 0 1
a =1*23 + 0*22+ 0*21 +1*20
a= (8+0+0+1) = 9
Now, 9 can be converted into octal by dividing it by 8 until we get the
remainder between (0-7).
(1001)2 = (9)10 = (11)8
Output:
3) Binary to Hexadecimal
First convert binary number to decimal number by assigning weight to each binary bit.
a = 100101
a =1*25+0*24+0*23+1*22+0*21+1*20
a= (32+0+0+4+0+1) = 37
As 100101 in binary is represented as 37 in decimal we can convert 37 into Hexadecimal by dividing
it by 16.
Output:
1) Octal to Binary:
Octal numbers are converted to binary numbers by replacing each octal digit with a three-bit binary
number. In python bin( ) function is used to convert octal number to binary number. The value is
written with ‘0o’ as a prefix which indicates that the value is in the octal form.
Output:
2) Octal to Decimal:
An octal number can be converted into a decimal number by assigning weight to each position. In
python int( ) function is used to convert octal to decimal numbers. Two arguments are get passed,
the first is a string of octal numbers, and the second is the base of the number system specified in
the string.
(342)8 = 3* 82 + 4*81 + 2*80
= 3*64 + 4*8 + 2*1
= 226
(342)8 = (226)1
Output:
3) Octal to Hexadecimal:
An Octal number can be converted into a hexadecimal number by converting the number into a
decimal and then a decimal number to hexadecimal. In python hex( ) function is used to convert
octal to hexadecimal numbers.
b = (456)8
(456)8 = 4*82 + 5*81+ 6*80
(456)8 = (302)10 = (12E)16
Output:
1) Hexadecimal to Binary:
The hexadecimal number is converted into a Binary number by replacing each hex digit with its
binary equivalent number.
a = FACE
F = (15)10 = (1111)2
A = (1)10 = (0001)2
C = (12)10 = (1100)2
E =(14)10 = (1110)2
(FACE)16 = (1111000111001110)2
Output:
The hexadecimal number is converted to an octal number by first converting that number to its
equivalent binary number and then to a binary number to an octal number.
Eg.)
(94AB)16 = (1001 0100 1010 1011)2
= 001 001 010 010 101 011
= (112253)8
a
Output:
3) Hexadecimal to Decimal:
Hexadecimal number is converted into decimal number by assigning weight (16) to each hex digit.
Output:
Python has a set of built-in methods that you can use on strings.
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
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
replace() Returns a string where a specified value is replaced with a specified value
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
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
zfill() Fills the string with a specified number of 0 values at the beginning
Note: All string methods returns new values. They do not change the original string.
MODULE 3
LIST
Lists are used to store multiple items in a single variable.Lists are one of 4 built-in data types
in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all
with different qualities and usage. Lists are created using square brackets:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.List items are indexed, the
first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will
not change.If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order of the items
will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
List Length
To determine how many items a list has, use the len() function:
Example
Example
type()
From Python's perspective, lists are defined as objects with the data type 'list':
<class 'list'>
Example
It is also possible to use the list() constructor when creating a new list.
Example
LIST OPERATORS
The list is a data structuring method that allows storing the integers or the characters in an order
indexed by starting from 0. List operations are the operations that can be performed on the data in
the list data structure. A few of the basic list operations used in Python programming are extend(),
insert(), append(), remove(), pop(), slice, reverse(), min() & max(), concatenate(), count(), multiply(),
sort(), index(), clear(), etc.
The Python List is one of the built-in data types of Python and the most flexible one.
These are involved in the storage of the collection of data sets.
The elements of a list are in a defined order, and you can modify these elements.
Either add, remove, or change the elements in the list.
It is easy to create the Python list; add some elements in square brackets, separating
each element by comma and assigning it to a variable.
Python Lists allow you to perform various functions apart from simple operations
like adding or deleting. You can remove any element irrespective of the position,
reverse the order of the list, print the results in a specific sequence, and sort or even
empty the elements in the list.
List Operations in Python
Some of the most widely used list operations in Python include the following:
1. append()
The append() method adds elements at the end of the list. This method can only add a
single element at a time. You can use the append() method inside a loop to add multiple
elements.
myList.append(4)
myList.append(5)
myList.append(6)
myList.append(i)
print(myList)
2. extend()
The extend() method adds more than one element at the end of the list. Although it can add
more than one element, unlike append(), it adds them at the end of the list like append().
Code:
myList.extend([4, 5, 6]
myList.append(i)
print(myList)
3. insert()
The insert() method can add an element at a given position in the list. Thus, unlike append(),
it can add elements at any position, but like append(), it can add only one element at a time.
This method takes two arguments. The first argument specifies the position, and the second
argument specifies the element to be inserted.
Code:
4. remove()
The remove() method removes an element from the list. Only the first occurrence of the same
element is removed in the case of multiple occurrences.
Code:
5. pop()
The method pop() can remove an element from any position in the list. The parameter supplied to
this method is the element index to be removed.
Code:
6. slice
The slice operation is used to print a section of the list. The slice operation returns a specific range of
elements. It does not modify the original list.
Code:
7. reverse()
You can use the reverse() operation to reverse the elements of a list. This method modifies the
original list. We use the slice operation with negative indices to reverse a list without modifying the
original. Specifying negative indices iterates the list from the rear end to the front end of the list.
Code:
print(myList)
8. len()
The len() method returns the length of the list, i.e., the number of elements in the list.
Code:
The min() method returns the minimum value in the list. The max() method returns the maximum
value in the list. Both methods accept only homogeneous lists, i.e., lists with similar elements.
Code:
myList = [1, 2, 3, 4, 5, 6, 7]
print(min(myList))
print(max(myList))
Output:
10. count()
The function count() returns the number of occurrences of a given element in the list.
Code:
myList = [1, 2, 3, 4, 3, 7, 3, 8, 3]
print(myList.count(3))
11. concatenate
The concatenate operation merges two lists and returns a single list. The concatenation is performed
using the + sign. It’s important to note that the individual lists are not modified, and a new combined
list is returned.
Code:
12. multiply
Python also allows multiplying the list n times. The resultant list is the original list iterated n times.
Code:
13. index()
The index() method returns the position of the first occurrence of the given element. It takes two
optional parameters – the beginning index and the end index. These parameters define the start and
end position of the search area on the list. When you supply the begin and end indices, the element
is searched only within the sub-list specified by those indices. When not supplied, the element is
searched in the whole list.
Code:
Code:
yourList = [4, 2, 6, 5, 0, 1]
yourList.sort()
print(yourList)
15. clear()
This function erases all the elements from the list and empties them.
Code:
Syntax:
list.copy()
Code:
even_numbers = [2, 4, 6, 8]
value = even_numbers.copy()
print('Copied List:', value)
TUPLE
mytuple = ("apple", "banana", "cherry")
Tuples are used to store multiple items in a single variable.Tuple is one of 4 built-in data types in
Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different
qualities and usage.A tuple is a collection which is ordered and unchangeable.Tuples are written
with round brackets.
Eg:
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.Tuple items are indexed, the first
item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order
will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has
been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuples allow duplicate values:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
To create a tuple with only one item, you have to add a comma after the item, otherwise Python will
not recognize it as a tuple.
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
thistuple = ("apple")
print(type(thistuple))
Example
String, int and boolean data types:
Example
A tuple with strings, integers and boolean values:
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a
Python list in terms of indexing, nested objects, and repetition but the main difference between
both is Python tuple is immutable, unlike the Python list which is mutable.
There are various ways by which you can create a tuple in Python. They are as follows:
Using round brackets
With one item
Tuple Constructor
Create Tuples using Round Brackets ()
To create a tuple we will use () operators.
print(var)
DICTIONARY
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionaries are used to store data values in key:value pairs.A dictionary is a collection which is
ordered*, changeable and do not allow duplicates.Dictionaries are written with curly brackets, and
have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.Dictionary items are
presented in key:value pairs, and can be referred to by using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Ordered or Unordered?
When we say that dictionaries are ordered, it means that the items have a defined order, and that
order will not change.Unordered means that the items does not have a defined order, you cannot
refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary
has been created.
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
Print the number of items in the dictionary:
print(len(thisdict))
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
<class 'dict'>
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
Example
Using the dict() method to make a dictionary:
myDictionary := {};
The following statement is not valid:
takesADictionaryArgument({});
Example:
ADDING KEYS: To insert new keys/values into a Dictionary, use the square brackets and the
assignment operator. With that, the update() method can also be used. Remember, if the
key is already in the dictionary, its value will get updated, else the new pair gets inserted.
Let us now insert new key:value into the Dictionary. We have first displayed the Dictionary before
updating the values. Here, we have inserted a new key:value pair
Python Functions
A function is a block of code which only runs when it is called.You can pass data, known as
parameters, into a function.A function can return data as a result. Python functions are techniques
used to combine a set of statements within a program. Functions also let programmers compute a
result-value and give parameters that serve as function inputs that may change each time the code
runs. Functions prove to be a useful tool when the operations are coded in it and can be used in a
variety of scenarios.Functions are an alternative method of cutting-and-pasting codes rather than
typing redundant copies of the same instruction or operation, which further reduces the future work
for programmers. They are the most basic structure of a program, and so Python provides this
technique for code re-use. The keyword 'def' introduces a function definition. The statements that
form the body of the function starts from the next line of function definition and needs indentation.
The execution of the function introduces a new symbol table that is used for the function's local
variable. In other words, all the variables that are assigned to the function store their value in the
local symbol table. So global variables cannot be assigned with a value within a function; unless it is
named under 'global' statement. To accept any number of keyword arguments, the arguments have
to start with *. A * argument can appear only in the last position of function's argument. A fine
concept of a function definition is that arguments can still appear after the * argument.
Creating a Function
EG:
def my_function():
print("Hello from a function")
Calling a Function
EG: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:
EG:def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.
EG:
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
EG:
my_function("Emil")
Arbitrary Arguments, *args
If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.This way the function will receive a tuple of
arguments, and can access the items accordingly:
EG: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.
Eg:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition.This way the function will
receive a dictionary of arguments, and can access the items accordingly:
Eg: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"])
Return Values
EG:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
RECURSIVE FUNCTION
In Python, we know that a function can call other functions. It is even possible for
the function to call itself. These types of construct are termed as recursive
functions.
The following image shows the working of a recursive function called recurse .
1. Actual Parameters :
The arguments that are passed in a function call are called actual arguments. These arguments are
defined in the calling function. These are the variables or expressions referenced in the parameter
list of a subprogram call. There is no need to specify datatype in actual parameter.
Example :
// X and Y NUMBER ARE ACTUAL PARAMETERS
SQL> CREATE OR REPLACE FUNCTION FUNC1(X NUMBER,
Y NUMBER)
2 RETURN NUMBER IS
3 R NUMBER;
4 BEGIN
5 R:=X+Y;
6 RETURN(R);
7 END;
8 /
FUNCTION CREATED.
SQL>|
2. Formal Parameters :
These are the variables or expressions referenced in the parameter list of a subprogram
specification. The datatype of the receiving value must be defined. The scope of formal arguments
is local to the function definition in which they are used.
Example :
SQL> DECLARE
2 N1 NUMBER:=10;
3 N2 NUMBER:=20;
4 S NUMBER;
5 BEGIN
6 S:=FUNC1(N1, N2);
7 DBMS_OUTOUT.PUT_LINE('RESULT IS: '||S);
8 END;
9 /
These are the variables or expressions These are the variables or expressions
referenced in the parameter list of a referenced in the parameter list of a
subprogram call. subprogram specification.
Actual Parameters are the parameters Formal Parameters are the parameters
which are in calling subprogram. which are in called subprogram.
There is no need to specify datatype in The datatype of the receiving value must
actual parameter. be defined.
Actual Parameters Formal Parameters
What is a Module?
Consider a module to be the same as a code library.A file containing a set of functions you want to
include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .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")
Note: When using a function from a module, use the syntax: module_name.function_name.
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):
Example
Save this code in the file 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)
There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
Import From Module
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
print (person1["age"])
When the modules are imported by the users, the Python interpreter will search for the module in
the current directory. If the module is not found in the directory, the interpreter will search every
directory present in the shell variable known as PYTHONPATH. If the interpreter is unable to find it in
the shell, then it will check the default path. In UNIX, this default path is: /usr/local/lib/python/.The
search path of the module is stored in the system module sys as the sys.path variable. This variable
contains the current directory, that is, PYTHONPATH, and the installation-dependent default.
Types of namespaces :
When Python interpreter runs solely without any user-defined modules, methods, classes, etc.
Some functions like print(), id() are always present, these are built-in namespaces. When a user
creates a module, a global namespace gets created, later the creation of local functions creates
the local namespace. The built-in namespace encompasses the global namespace and the global
namespace encompasses the local namespace.
The built-in namespace: contains the names of all of Python’s built-in objects. These are
available at all times when Python is running.
The Global Namespace
The global namespace contains any names defined at the level of the main program. Python creates
the global namespace when the main program body starts, and it remains in existence until the
interpreter terminates.Strictly speaking, this may not be the only global namespace that exists. The
interpreter also creates a global namespace for any module that your program loads with
the import statement.
As you learned in the previous tutorial on functions, the interpreter creates a new namespace
whenever a function executes. That namespace is local to the function and remains in existence until
the function terminates.
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends, the
lifetime of that namespace comes to an end. Hence, it is not possible to access the inner
namespace’s objects from an outer namespace.
Variable Scope
The existence of multiple, distinct namespaces means several different instances of a particular
name can exist simultaneously while a Python program runs. As long as each instance is in a
different namespace, they’re all maintained separately and won’t interfere with one another.
The scope of a name is the region of a program in which that name has meaning. The interpreter
determines this at runtime based on where the name definition occurs and where in the code the
name is referenced.
Python Packages
We usually organize our files in different folders and subfolders based on some criteria, so that they
can be managed easily and efficiently. For example, we keep all our games in a Games folder and we
can even subcategorize according to the genre of the game or something like this. The same analogy
is followed by the packages in Python.
What is a Python Package?
Python modules may contain several classes, functions, variables, etc. whereas Python packages
contain several modules. In simpler terms, Package in Python is a folder that contains various
modules as files.
Creating Package
Let’s create a package in Python named mypckg that will contain two modules mod1 and mod2. To
create this module follow the below steps:
Mod1.py
Mod1.py
def gfg():
print("Welcome to GFG")
Mod2.py
Understanding __init__.py
__init__.py helps the Python interpreter recognize the folder as a package. It also specifies the
resources to be imported from the modules. If the __init__.py is empty this means that all the
functions of the modules will be imported. We can also specify the functions from each module to
be made available.
For example, we can also create the __init__.py file for the above module as:
__init__.py
This __init__.py will only allow the gfg and sum functions from the mod1 and mod2 modules to be
imported.
We can import these Python modules using the from…import statement and the dot(.) operator.
Syntax:
import package_name.module_name
Example 1:
We will import the modules from the above-created package and will use the functions inside those
modules.
date – An idealized naive date, assuming the current Gregorian calendar always was, and always
will be, in effect. Its attributes are year, month, and day.
time – An idealized time, independent of any particular day, assuming that every day has exactly
24*60*60 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
datetime – Its a combination of date and time along with the attributes year, month, day, hour,
minute, second, microsecond, and tzinfo.
timedelta – A duration expressing the difference between two date, time, or datetime instances
to microsecond resolution.
tzinfo – It provides time zone information objects.
timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC
(New in version 3.2).
Initializing the constructor and passing arguments in the format year, month, and date.
# Python program to
# outside range
To return the current local date today() function of the date class is used. today() function comes
with several attributes (year, month, and day). These can be printed individually.
# Python program to
# print current date
from datetime import date
# calling the today
# function of date class
today = date.today()
print("Today's date is", today)
We can get the year, month, and date attributes from the date object using the year, month and
date attribute of the date class. from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)
We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp
is the number of seconds from 1st January 1970 at UTC to a particular date.
We can convert date object to a string representation using two functions isoformat() and strftime().
fromisoformat() Returns a date object from the string representation of the date
Returns a date object from the proleptic Gregorian ordinal, where January
fromordinal()
1 of year 1 has ordinal 1
Function Name Description
isoweekday() Returns the day of the week as an integer where Monday is 1 and Sunday is 7
replace() Changes the value of the date object with the given parameter
strftime() Returns a string representation of the date with the given format
Return the proleptic Gregorian ordinal of the date, where January 1 of year
toordinal()
1 has ordinal 1
weekday() Returns the day of the week as integer where Monday is 0 and Sunday is 6
All the arguments are optional. tzinfo can be None otherwise all the attributes must be integer in the
following range –
Description
Function Name
fromisoformat() Returns a time object from the string representation of the time
Description
Function Name
isoformat() Returns the string representation of time from the time object
replace() Changes the value of the time object with the given parameter
strftime() Returns a string representation of the time with the given format
The year, month, and day arguments are mandatory. tzinfo can be None, rest all the attributes must
be an integer in the following range –
Note – Passing an argument other than integer will raise a TypeError and passing arguments outside
the range will raise ValueError.
You can print the current date and time using the Datetime.now() function. now() function returns
the current local date and time.
Convert Python Datetime to String
We can convert Datetime to string in Python using the datetime.strftime and datetime.isoformat
methods.
combine() Combines the date and time objects and return a DateTime object
fromisoformat() Returns a datetime object from the string representation of the date and time
Returns a date object from the proleptic Gregorian ordinal, where January 1 of
fromordinal()
year 1 has ordinal 1. The hour, minute, second, and microsecond are 0
isoweekday() Returns the day of the week as integer where Monday is 1 and Sunday is 7
strftime() Returns a string representation of the DateTime object with the given format
Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
toordinal()
has ordinal 1
Function Name Description
weekday() Returns the day of the week as integer where Monday is 0 and Sunday is 6
Constructor syntax:
Date and Time differences can also be found using this class.
Operator Description
Multiplication
Multiplies timedelta object with float or int
(*)
Floor division Divides the timedelta object with float or int and return the int of floor value of the
(//) output
Modulo (%) Divides two timedelta object and returns the remainder
Operator Description
abs(timedelta) Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta)
repr(timedelta) Returns the string representation in the form of the constructor call
Formatting DateTime can be very necessary as the date representation may differ from place to
place. In some countries, it can be yyyy-mm-dd and in other countries, it can be dd-mm-yyyy. To
format Python Datetime strptime and strftime functions can be used.
A strftime() method converts the given date, time, or DateTime object to the string representation
of the given format.
Python DateTime.tzinfo()
The datetime.now() function contains no information regarding time zones. It only makes use of the
current system time. Tzinfo is an abstract base class in Python. It cannot be directly instantiated. A
concrete subclass must derive from this abstract class and implement the methods offered by it.
Example
The tzinfo class instance can be provided to the DateTime and time object constructors. It is used in
scenarios such as converting local time to UTC or accounting for daylight savings time.
import datetime as dt
from dateutil import tz
tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname()
print("datetime.now() :", tz_string)
NYC = tz.gettz('Europe / Berlin')
dt1 = dt.datetime(2022, 5, 21, 12, 0)
dt2 = dt.datetime(2022, 12, 21, 12, 0, tzinfo=NYC)
print("Naive Object :", dt1.tzname())
print("Aware Object :", dt2.tzname())
Timezones in DateTime can be used in the case where one might want to display time according to
the timezone of a specific region. This can be done using the pytz module of Python. This module
serves the date-time conversion functionalities and helps users serving international client bases.
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
end_fill() None Close the polygon and fill with the current fill color
After importing the turtle library and making all the turtle functionalities available to us, we need
to create a new drawing board(window) and a turtle. Let’s call the window as wn and the turtle as
skk. So we code as:
wn = turtle.Screen()
wn.bgcolor("light green")
wn.title("Turtle")
skk = turtle.Turtle()
Now that we have created the window and the turtle, we need to move the turtle. To move
forward 100 pixels in the direction skk is facing, we code:
skk.forward(100)
We have moved skk 100 pixels forward, Awesome! Now we complete the program with the done()
function and We’re done!
turtle.done()
So, we have created a program that draws a line 100 pixels long. We can draw various shapes and
fill different colors using turtle methods. There’s plethora of functions and programs to be coded
using the turtle library in python. Let’s learn to draw some of the basic shapes.
Shape 1: Square
for i in range(4):
skk.forward(50)
skk.right(90)
turtle.done()
Output:
Shape 2: Star
star.right(75)
star.forward(100)
for i in range(4):
star.right(144)
star.forward(100)
turtle.done()
Output:
Shape 3: Hexagon
num_sides = 6
side_length = 70
angle = 360.0 / num_sides
for i in range(num_sides):
polygon.forward(side_length)
polygon.right(angle)
turtle.done()
Output:
Shape 4: parallelogram
import turtle
Output:
Shape 5 : Circle
import turtle
# Set up the turtle screen and set the background color to white
screen = turtle.Screen()
screen.bgcolor("white")
# Create a new turtle and set its speed to the fastest possible
pen = turtle.Turtle()
pen.speed(0)
turtle is an inbuilt module in python. It provides drawing using a screen (cardboard) and turtle (pen).
To draw something on the screen, we need to move the turtle. To move turtle, there are some
functions i.e forward(), backward(), etc.
To fill the colors in the shapes drawn by turtle, turtle provides three functions –
fillcolor(): This helps to choose the color for filling the shape. It takes the input parameter as the
color name or hex value of the color and fills the upcoming closed geographical objects with the
chosen color. Color names are basic color names i.e. red, blue, green, orange.The hex value of color
is a string(starting with ‘#’) of hexadecimal numbers i.e. #RRGGBB. R, G, and B are the hexadecimal
numbers (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F).
begin_fill(): This function tells turtle that all upcoming closed graphical objects needed to be filled by
the chosen color.
end_fill(): this function tells turtle to stop the filling upcoming closed graphical objects.
import turtle
200
import turtle
t = turtle.Turtle()
col = input("Enter the color name or hex value of color(# RRGGBB): ")
t.fillcolor(col)
t.begin_fill()
t.forward(s)
t.right(-120)
t.end_fill()
import turtle
t = turtle.Turtle()
col = input("Enter the color name or hex value of color(# RRGGBB): ")
t.fillcolor(col)
t.begin_fill()
for _ in range(6):
t.forward(s)
t.right(-60)
t.end_fill()
Input :
100
#113300
Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it!
We can use many turtle functions which can move the turtle around. Turtle comes in the turtle
library. The turtle module can be used in both object-oriented and procedure-oriented ways.
Some of the commonly used methods which are also used here are:
forward(length): moves the pen in the forward direction by x unit.
backward(length): moves the pen in the backward direction by x unit.
right(angle): rotate the pen in the clockwise direction by an angle x.
left(angle): rotate the pen in the anticlockwise direction by an angle x.
penup(): stop drawing of the turtle pen.
pendown(): start drawing of the turtle pen.
In this article, we will draw various shape inside a similar shape like drawing triangles inside
triangle.
Triangle inside Triangle
Follow the below steps:
Define an instance for turtle.
For a square execute a loop 3 times (sides).
In every iteration move turtle 120 units forward.
This will make up a Triangle.
This is made multiple times to form triangles inside the triangle using a function.
Below is the python implementation.
import turtle
# for triangle
def form_tri(side):
for i in range(3):
my_pen.fd(side)
my_pen.left(120)
side -= 10
tut = turtle.Screen()
tut.bgcolor("green")
tut.title("Turtle")
my_pen = turtle.Turtle()
my_pen.color("orange")
tut = turtle.Screen()
side = 300
for i in range(10):
form_tri(side)
side -= 30
Image Formats
Image Format describes how data related to the image will be stored. Data can be stored in
compressed, Uncompressed, or vector format. Each format of the image has a different advantage
and disadvantage. Image types such as TIFF are good for printing while JPG or PNG, are best for
the web.
TIFF(.tif, .tiff) Tagged Image File Format this format store image data without losing any data.
It does not perform any compression on images, and a high-quality image is obtained but the
size of the image is also large, which is good for printing, and professional printing.
JPEG (.jpg, .jpeg) Joint Photographic Experts Group is a loss-prone (lossy) format in which data
is lost to reduce the size of the image. Due to compression, some data is lost but that loss is
very less. It is a very common format and is good for digital cameras, nonprofessional prints, E-
Mail, Powerpoint, etc., making it ideal for web use.
GIF (.gif) GIF or Graphics Interchange Format files are used for web graphics. They can be
animated and are limited to only 256 colors, which can allow for transparency. GIF files are
typically small in size and are portable.
PNG (.png) PNG or Portable Network Graphics files are a lossless image format. It was
designed to replace gif format as gif supported 256 colors unlike PNG which support 16 million
colors.
Bitmap (.bmp) Bit Map Image file is developed by Microsoft for windows. It is same as TIFF
due to lossless, no compression property. Due to BMP being a proprietary format, it is
generally recommended to use TIFF files.
EPS (.eps) Encapsulated PostScript file is a common vector file type. EPS files can be opened in
applications such as Adobe Illustrator or CorelDRAW.
RAW Image Files (.raw, .cr2, .nef, .orf, .sr2) These Files are unprocessed and created by a
camera or scanner. Many digital SLR cameras can shoot in RAW, whether it be a .raw, .cr2, or
.nef. These images are the equivalent of a digital negative, meaning that they hold a lot of
image information. These images need to be processed in an editor such as Adobe Photoshop
or Lightroom. It saves metadata and is used for photography.
What is meant by image saved with transparency? Images saved with transparency look good on
colored background whereas images without transparency will have a white background which
will be visible on colored background.
Python Image Manipulation Tools
The world of today is brimming with data, and images are the bulk of this data. But in order
to be utilized in any way, the digital images need to be processed and analysed to enhance
the quality of their images or gain information that could be utilized.
Common image processing tasks comprise display; simple manipulations such as flipping,
cropping, etc. Image segmentation, feature extractions, classification images restoration,
also image recognition. Python is a great option for these kinds of tasks in image processing
because of its rising popularity as a science-based programming language, as well as the
open access to a variety of state-of-the-art image processing tools within its library.
This article examines the top 10 most frequently utilized Python libraries to perform image
manipulation tasks. These libraries offer a simple and intuitive method to alter images and
comprehend the data behind them.
1. scikit-image
Scikit-image can be described as an open-source Python program that uses NumPy arrays. It is a tool
for implementing algorithms and utilities that can be used in research, education as well as industrial
applications. It's an easy and simple library, even for those unfamiliar with the Python ecosystem.
The code is of high-quality that and has been peer-reviewed and written by a large group of
volunteers.
Resources
Scikit-image is thoroughly explained with plenty of examples and real-world use instances.
Usage
It is loaded in the skimage, and the majority of functions are contained in submodules.
2.NumPy
NumPy is one of the most important libraries used in Python programming. It also supports arrays.
An image is essentially an array of NumPy that is standard and contains the pixels that makeup data.
Thus, by using standard NumPy techniques, like cutting, masking, or fancy indexing, it is possible to
alter the pixel values in an image. It can also be loaded with the skimage program and displayed with
Matplotlib.
Usage
image1 = data.camera()
type(image1)
nmp.ndarray
#Image is a NumPy array:
3. SciPy
SciPy SciPy is another one of Python's primary science modules (like NumPy) and can be utilized to
perform basic operations on images and for processing. Particularly it is a submodule called
scipy.ndimage (in SciPy v1.1.0) that provides functions that operate on the n-dimensional NumPy
arrays. The package is currently stocked with functions for non-linear and linear filtering, B-spline
interpolation, binary morphology as well as the measurement of objects.
Usage
4. PIL/Pillow
PIL (Python Imaging Library) is a library that is free for Python. It is a library for Python programming
language that provides support for opening, manipulating and saving various formats for images.
However, its development has slowed, and its last release was in 2009. There is, however, an
alternative, Pillow, which is an actively developed alternative to PIL, which is simpler to install, works
on all the major platforms, and also supports Python 3. The library provides basic image processing
functions that include points, filters, the convolution kernels built-in, as well as colour space
conversions.
Usage
Usage
Making use of Blending of Images using Pyramids within OpenCV Python, you can create the
"Orapple":
6. SimpleCV
SimpleCV is a different open-source framework for creating applications for computer vision. It
provides access to a variety of powerful computer vision software libraries like OpenCV, but you
don't need to know bit depths and colour spaces, file formats, as well as colour spaces. The learning
curve of SimpleCV is significantly less than that of OpenCV and (as its tagline states), "its computer
vision made easy." A few advantages of SimpleCV include:
7. Mahotas
Mahotas can be described as yet another software for image and computer vision available for
Python. It has traditional image processing tools like filtering and morphological processes in
addition to modern computer vision tools for feature computation, including interest point
detection and local descriptors. The interface is Python which is suitable for development speed.
However, the algorithms are written using C++ and tuned to speed. Mahotas library is extremely
fast, with minimal code and minimal dependencies. Read the official publication to gain more
insight.
Resources
This documentation includes installation instructions as well as examples and some guides to help
you start using Mahotas quickly.
Usage
The Mahotas library relies on simple code to complete tasks. For instance, it does an excellent job of
solving the finding Wally problem, using only a small quantity of programming.
8. SimpleITK
ITK (Insight Segmentation and Registration Toolkit) is "open-source, cross-platform software that
offers developers an extensive collection of tools to aid in the analysis of images. SimpleITK is an
esoteric layer built on the top of ITK designed to ease quick prototyping and education and
[andinterpreters." The toolkit also includes image analysis, with various components supporting
general filtering functions such as image segmentation, image filtering, and registration. SimpleITK
was written in C++, but it's compatible with a vast number of programming languages like Python.
Resources
There are many Jupyter Notebooks showing how SimpleITK can be used in research and education.
Notebooks show how to use SimpleITK to perform interactive image analysis with it Python as well
as R Programming languages.
Usage
Visualization of a strict CT/MR registration procedure created with Python and SimpleITK. Python:
9. pgmagick
Resources
10. Pycairo
Pycairo Pycairo HTML0 is an array of Python bindings for the Cairo graphics library. Cairo is
a 2D graphics library that allows the creation of vector graphics. Vector graphics are
attractive since they don't lose clarity when resized or altered. Pycairo can invoke Cairo
commands using Python.
Resources
Its Pycairo GitHub repository is a useful resource that provides detailed instructions
regarding installation and use. It also has a starting guide that includes an overview of
Pycairo.
Usage
The drawing of lines and basic forms and radial gradients using Pycairo:
MODULE 5
This article aims to read configuration files written in the common .ini configuration file format.
The configparser module can be used to read configuration files.
Code #1 : Configuration File
abc.ini ;
Sample configuration file
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
# Setting related to debug configuration
[debug]
pid-file = /tmp/spam.pid
show_warnings = False
log_errors = true
[server]
nworkers: 32
port: 8080
root = /www/root
signature:
Output :
['config.ini']
Sections : ['installation', 'debug', 'server']
Installation Library : '/usr/local/lib'
Log Errors debugged ? : True
Port Server : 8080
Worker Server : 32
One can also modify the configuration and write it back to a file using the cfg.write() method.
Configuration files are well suited to specify configuration data to your program. Within each
config file, values are grouped into different sections (e.g., “installation”, “debug” and
“server”).
Each section then has a specific value for various variables in that section. For the same
purpose, there are some prominent differences between a config file and using a Python
source file.
First, the syntax is much more permissive and “sloppy.”
Names used in a config file are also assumed to be case-insensitive as shown in the code below –
configur.get('installation','PREFIX')
configur.get('installation','prefix')
When parsing values, methods such as getboolean() look for any reasonable value. For example,
these are all equivalent.
log_errors = true
log_errors = TRUE
log_errors = Yes
log_errors = 1
The most noteworthy contrast between a config record and Python code is that, in contrast to
scripts, configuration files are not executed in a top-down way. Rather, the file is read completely.
On the off chance that variable substitutions are made, they are done later after the fact. For
instance, it doesn’t make a difference that the prefix variable is allocated after different variables
that happen to utilize it.
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
Multiple configuration files can be read together and their results can be merged into a single
configuration using ConfigParser, which makes it so special to use.
Example – A user made their own configuration file that looks as.
; ~/.config.ini
[installation]
prefix = /Users/beazley/test
[debug]
log_errors = False
This file can be merged with the previous configuration by reading it separately
How To Write Logs To A File With Python?
You can use basic config. If you configure the attribute filename, logs will be automatically saved to
the file you specify. You can also configure the attribute filemode. Setting the value to w will
overwrite the file after every entry.
import logging
logging.basicConfig(filename="logs.log", filemode="w", format="%(name)s → %(levelname)s:
%(message)s")
logging.warning("warning")
OUTPUT
root → WARNING: warning
You can also use the provided classes - loggers and handlers:
logger = logging.getLogger(__name__)
FileOutputHandler = logging.FileHandler('logs.log')
logger.addHandler(FileOutputHandler)
logger.warning("Warning.")
You will create a logger and a handler. When creating a handler, assign the class FileHandler and a
file name as an attribute. Then set the handler to a logger:
Output
Warning.
Python File Operations - Read and Write to files with Python
In the previous tutorial, we used console to take input. Now, we will be taking input using a file. That
means, we will read from and write into files. To do so, we need to maintain some steps. Those are
1. Open a file
2. Take input from that file / Write output to that file
3. Close the file
We will also learn some useful operations such as copy file and delete file.
The open() function in Python accepts two arguments. The first one is the file name along with the
complete path and the second one is the file open mode.
Below, I’ve listed some of the common reading modes for files:
‘r’ : This mode indicate that file will be open for reading only
‘w’ : This mode indicate that file will be open for writing only. If file containing containing that name
does not exists, it will create a new one
‘a’ : This mode indicate that the output of that program will be append to the previous output of
that file
‘r+’ : This mode indicate that file will be open for both reading and writing
Additionally, for the Windows operating system, you can append ‘b’ for accessing the file in binary.
This is is because Windows differentiates between a binary text file and a regular text file.
Suppose, we place a text file name ‘file.txt’ in the same directory where our code is placed. Now we
want to open that file.However, the open(filename, mode) function returns a file object. With that
file object you can proceed your further operation.
#directory: /home/imtiaz/code.py
text_file = open('file.txt','r')
print('Second Method')
print(text_file2)
Copy
Second Method
>>>
Copy
Python offers various methods to read and write to files where each functions behaves differently.
One important thing to note is the file operations mode. To read a file, you need to open the file in
the read or write mode. While to write to a file in Python, you need the file to be open in write
mode.
Here are some of the functions in Python that allow you to read and write to files:
read() : This function reads the entire file and returns a string
readline() : This function reads lines from that file and returns as a string. It fetch the line n, if it is
been called nth time.
readlines() : This function returns a list where each element is single line of that file.
readlines() : This function returns a list where each element is single line of that file.
write() : This function writes a fixed sequence of characters to a file.
writelines() : This function writes a list of string.
append() : This function append string to the file instead of overwriting the file.
Let’s take an example file “abc.txt”, and read individual lines from the file with a for loop:
#open the file
text_file = open('/Users/pankaj/abc.txt','r')
Now, that we know how to read a file in Python, let’s move ahead and perform a write operation
here with the writelines() function.
#iterate 4 times
for i in range (1, 5):
print("Please enter data: ")
line = input() #take input
word_list.append(line) #append to the list
Output
We can use the shutil module to copy files in Python. This utility allows us to perform copy and
move operations in Python on different files. Let’s work on this with an example:
import shutil
shutil.copy2('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copy2.txt')
shutil.copyfile('/Users/pankaj/abc.txt', '/Users/pankaj/abc_copyfile.txt')
Copy
Python’s shutil module offers the remove() method to delete files from the file system. Let’s take a
look at how we can perform a delete operation in Python.
import shutil
import os
os.remove('/Users/pankaj/abc_copy2.txt')
Copy
When you open a file in Python, it’s extremely important to close the file after you make the
changes. This saves any changes that you’ve previously made, removes the file from the memory,
and prevents any further reads or writes within the program.
If we continue on from our previous examples where we read files, here’s how you’d close the file:
text_file = open('/Users/pankaj/abc.txt','r')
# some file operations here
text_file.close()
Copy
Additionally, you can avoid closing files manually if you use the with block. As soon as the with block
is executed, the files are closed and are no longer available for reading and writing.
6. Python FileNotFoundError
It’s common to receive the FileNotFoundError when working with files in Python. It can be easily
avoided by providing complete file paths when creating the file object.
Copy
To fix the FileNotFoundError, you simply need to verify that the path you’ve mentioned for the file
open method is correct.
Python offers several methods for file handling. In addition to the standard operations like reading
and writing to the files, there are methods to manipulate the file pointer effectively.
In this tutorial, you’ll learn how to use the seek() function to move the position of a file
pointer while reading or writing a file.
Learn to use the seek() method to move the file cursor ahead or backward from the current
position
Learn to move the file pointer to that start or end of the file
Learn to move the file pointer backward from the end of the file
Get the current position of the file handle
The seek() function sets the position of a file pointer and the tell() function returns the current
position of a file pointer.
A file handle or pointer denotes the position from which the file contents will be read or written.
File handle is also called as file pointer or cursor.
For example, when you open a file in write mode, the file pointer is placed at the 0th position, i.e., at
the start of the file. However, it changes (increments) its position as you started writing content into
it.
Or, when you read a file line by line, the file pointer moves one line at a time.
Sometimes we may have to read only a specific portion of the file, in such cases use
the seek() method to move the file pointer to that position.
For example, use the seek() function to do the file operations like: –
To change the file handle’s position use seek() method. As we discussed, the seek() method sets the
file’s current position, and then we can read or write to the file from that position.
Syntax:
f.seek(offset, whence)
How many points the pointer will move is computed from adding offset to a reference point; the
reference point is given by the whence argument.
f.seek(5) Move file pointer five characters ahead from the beginning of a file.
f.seek(5, 1) Move file pointer five characters ahead from the current position.
f.seek(-5, 1) Move file pointer five characters behind from the current position.
f.seek(-5, 2) Move file pointer in the reverse direction. Move it to the 5th character from the end of the file
File seek function
Example
Consider the following example where we are reading a text file contents with the offset as 6. It
means we will start reading the file directly from the 6th character.
text file
Output
line
Second line
Third line
Fourth line
Fifth line
Sixth line
Seventh line
Eighth line