0% found this document useful (0 votes)
16 views

Introduction on Python

The document provides an introduction to Python, covering its definition, tools, and common packages used for various applications such as web development and data science. It details specific modules like OS, Time, Datetime, RE, openpyxl, Argparse, and Schedule, along with examples of their usage. Additionally, it includes installation instructions for packages and highlights the functionality of each module.

Uploaded by

Harsha Vardhan T
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Introduction on Python

The document provides an introduction to Python, covering its definition, tools, and common packages used for various applications such as web development and data science. It details specific modules like OS, Time, Datetime, RE, openpyxl, Argparse, and Schedule, along with examples of their usage. Additionally, it includes installation instructions for packages and highlights the functionality of each module.

Uploaded by

Harsha Vardhan T
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Introduction to Python

Objective
• What is python?
• Python Tools
• Common Packages
What is Python?
• Open source
• Support for various libraries/modules
• Object oriented programming language
• Simple to understand and code
• Application: Web Development, Machine Learning, mobile
applications, general scripting, data science
Tools
• IDLE - https://www.python.org/downloads/
• Spyder - https://www.anaconda.com/download/
• Jupyter - https://jupyter.org/install
• PyCharm - https://www.jetbrains.com/pycharm/download/
• IntelliJ - https://www.jetbrains.com/idea/download/
Common packages
➢ datetime
➢ time Installation:
➢ re (regex functions) • Open command prompt and change
➢ sys directory to ‘pip’ folder found inside
➢ os the python directory
➢ schedule
• Type
pip install <package_name>
➢ apschedule
• Call the package at the beginning of
➢ csv each scripts as follows
➢ openpyxl import <package_name>
➢ gzip
➢ argparse
➢ Pandas
➢ tulipy
➢ numpy
OS module
• The OS module in python provides functions for interacting with the operating
system. OS, comes under Python's standard utility modules. This module provides
a portable way of using operating system dependent functionality.

➢os.getcwd(): Function os.getcwd(), returns the Current Working Directory(CWD)


of the file used to execute the code, can vary from system to system.

import os
print(os.getcwd())
OUTPUT: \Users\GFG\Desktop\ModuleOS
➢os.popen(): This method opens a pipe to or from command. The return value can
be read or written depending on whether mode is ‘r’ or ‘w’.
file = os.popen(fd, 'w')
file.write("Hello")
Note: Output for popen() will not be shown, there would be direct changes into the
file.

➢os.rename(): A file old.txt can be renamed to new.txt, using the function


os.rename(). The name of the file changes only if, the file exists and user has
sufficient privilege permission to change the file.

import os
fd = "GFG.txt"
os.rename(fd,'New.txt')
Time Module
• Python has defined a module, “time” which allows us to handle various operations
regarding time, its conversions and representations, which find its use in various
applications in life.
➢ctime(sec) :- This function returns a 24 character time string but takes seconds as
argument and computes time till mentioned seconds. If no argument is passed,
time is calculated till present.
import time
print ("Time calculated using ctime() is : ", end="")
print (time.ctime())
OUTPUT:
Time calculated using ctime() is : Mon sep 5 07:47:02 2020
➢sleep(sec) :- This method is used to hault the program execution for the time
specified in the arguments
import time
print ("Start Execution : ",end="")
print (time.ctime())
time.sleep(4)
print ("Stop Execution : ",end="")
print (time.ctime())
OUTPUT:
Start Execution : Mon sep 5 07:59:03 2020
Stop Execution : Mon sep 5 07:59:07 2020
Datetime Module
• Datetime module supplies classes to work with date and time. These classes provide a number of
functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so
when you manipulate them, you are actually manipulating objects and not string or timestamps.

Classes of Datetime:
➢ 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.
➢ timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC
(New in version 3.2).
Re Module
Module Regular Expressions(RE) specifies a set of strings(pattern) that matches it.
➢ Function compile():Regular expressions are compiled into pattern objects, which have methods for
various operations such as searching for pattern matches or performing string substitutions.
import re
p = re.compile('[a-e]')
# findall() searches for the Regular Expression and return a list upon finding
print(p.findall("Aye, said Mr. Gibenson Stark"))
OUTPUT:['e', 'a', 'd', 'b', 'e', 'a']

➢ Few other usage:


p = re.compile('\d') --> [0-9]
p = re.compile('\d+') -->\d+ will match a group on [0-9], group of one or greater size
p = re.compile('\w') --> \w is equivalent to [a-zA-Z0-9_].
p = re.compile('\w+') --> \w+ matches to group of alphanumeric character
p = re.compile('\W') -->\W matches to non alphanumeric characters.

➢Function split():Split string by the occurrences of a character or a pattern, upon


finding that pattern, the remaining characters from the string are returned as part
of the resulting list.

from re import split


print(split('\w+', 'On 12th Jan 2016, at 11:02 AM'))
OUTPUT:['On', '12th', 'Jan', '2016', 'at', '11', '02', 'AM']
openpyxl Module
openpyxl is a Python library for reading and writing Excel (with extension
xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and
modify Excel files.

Use this command to install openpyxl module :


sudo pip3 install openpyxl

➢Determine total number of columns


import openpyxl
path = "C:\\Users\\Admin\\Desktop\\demo.xlsx"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
print(sheet_obj.max_column)
➢ Print first column value

import openpyxl
path = "C:\\Users\\Admin\\Desktop\\demo.xlsx"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
m_row = sheet_obj.max_row
for i in range(1, m_row + 1):
cell_obj = sheet_obj.cell(row = i, column = 1)
print(cell_obj.value)
Argparse Module
• The argparse module in Python helps create a program in a command-line-
environment in a way that appears not only easy to code but also improves
interaction. The argparse module also automatically generates help and usage
messages and issues errors when users give the program invalid arguments.
Steps for Using Argparse
➢Creating a Parser:
➢Adding Arguments
➢Parsing Arguments
➢ To find the sum of command-line arguments using argparse
import argparse
# Initialize the Parser
parser = argparse.ArgumentParser(description ='Process some integers.')
# Adding Arguments
parser.add_argument('integers', metavar ='N',
type = int, nargs ='+',
help ='an integer for the accumulator')
parser.add_argument(dest ='accumulate',
action ='store_const',
const = sum,
help ='sum the integers')
args = parser.parse_args()
print(args.accumulate(args.integers))
OUTPUT:
Schedule Module
Schedule is in-process scheduler for periodic jobs that use the builder
pattern for configuration. Schedule lets you run Python functions (or any
other callable) periodically at pre-determined intervals using a simple,
human-friendly syntax.
$ pip install schedule
➢schedule.every(interval=1) : Calls every on the default scheduler
instance. Schedule a new periodic job.
➢schedule.run_pending() : Calls run_pending on the default scheduler
instance. Run all jobs that are scheduled to run.
➢schedule.run_all(delay_seconds=0) : Calls run_all on the default
scheduler instance. Run all jobs regardless if they are scheduled to run or
not.
➢schedule.idle_seconds() : Calls idle_seconds on the default scheduler
instance.
➢schedule.next_run() : Calls next_run on the default scheduler instance.
Datetime when the next job should run.
➢schedule.cancel_job(job) : Calls cancel_job on the default scheduler
instance. Delete a scheduled job.
Reference
• https://www.geeksforgeeks.org/

You might also like