Python Course
1. string- Basic Operations
import string # predefined string constants can be used in common scenarios print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ print(string.digits) # 0123456789 print(string.hexdigits) # 0123456789abcdefABCDEF print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ intro_text = "With over 18 years of experience in IT, I specialize in software development and freelancing, offering tailored solutions that meet the unique needs of your business." print(intro_text) print(intro_text.isalnum()) # False print(intro_text.isalpha()) # False # startswith and endswith print(intro_text.startswith("With")) # True print(intro_text.startswith("The")) # False print(intro_text.endswith("business.")) # True # find, rfind and in print(intro_text.find("18")) # 10 print(intro_text.rfind("18")) # 10 print("18" in intro_text) # True # replace new_intro_text = intro_text.replace("and freelancing", ", freelancing and trainer") print(new_intro_text) # count print(intro_text.count("in")) # 5 # lower and upper print(intro_text.lower()) print(intro_text.upper()) # split and join print(intro_text.split(" ")) letters = ["a","b","c","d"] print(", ". join(letters)) # a, b, c, d
2. datetime – Working with Dates and Times
The datetime module provides classes for manipulating dates and times.
Common Classes:
datetime.date: Handles date (year, month, day)datetime.time: Handles time (hour, minute, second)datetime.datetime: Combines date and timedatetime.timedelta: Represents duration (difference between dates/times)
from datetime import date, datetime, timedelta # Current date and time now = datetime.now() print("Now:", now) # Now: 2023-07-09 10:09:23.635460 # Specific date d = date(2023, 7, 9) print("Specific date:", d) # Specific date: 2023-07-09 # Date difference delta = date(2023, 12, 25) - date(2023, 7, 9) print("Days until Christmas:", delta.days) # Days until Christmas: 169 # Add 10 days to today future = date.today() + timedelta(days=10) print("Date after 10 days:", future) # Date after 10 days: 2023-07-19 # Current UTC time utc_now = datetime.utcnow() formatted_utc = utc_now.isoformat(timespec='seconds') print("Current UTC time:", formatted_utc) # Current UTC time: 2023-07-09T10:09:23
3. calendar – Calendar-related Functions
The calendar module lets you output calendars and check for leap years, weekdays, etc.
Useful Functions:
calendar.month(year, month): Returns a calendar for a monthcalendar.isleap(year): Checks if the year is a leap yearcalendar.weekday(year, month, day): Returns weekday index (0=Monday)calendar.monthcalendar(year, month): Matrix of the month’s calendar
import calendar # Print calendar for July 2023 print(calendar.month(2023, 7)) # Is 2024 a leap year? print("Is 2024 leap year?", calendar.isleap(2024)) # Weekday of a specific date print("Weekday of 9 July 2023:", calendar.weekday(2023, 7, 9))
4. urllib.request – Fetching Data from the Web
The urllib.request module helps in opening and reading URLs.
Common Functions:
urllib.request.urlopen(url): Opens the URLread(): Reads the responsedecode(): Converts bytes to string
import urllib.request # open a connection to a URL using urllib2 web_url = urllib.request.urlopen("https://www.praveenoruganti.in") # get the result code and print it print ("Result code:", web_url.getcode()) # read the data from the URL and print it data = web_url.read() print("Webpage content:") print(data)
5. json Module
The json module in Python allows you to encode (dump) and decode (load) JSON data. It converts JSON strings into Python objects, and vice versa.
import urllib.request import json try: web_url = urllib.request.urlopen("http://uselessfacts.jsph.pl/api/v2/facts/random") print("Result code:", web_url.getcode()) data = web_url.read() theJSON = json.loads(data) print("Random Fact:", theJSON["text"]) except Exception as e: print("Error fetching or parsing JSON:", e)
6. xml.dom.minidom Module
The xml.dom.minidom module in Python — a lightweight Document Object Model (DOM) parser for working with XML.
samplexml.xml
<skills> <skill name="Python"/> <skill name="JavaScript"/> <skill name="HTML"/> </skills>
xml_parsing.py
import xml.dom.minidom try: doc = xml.dom.minidom.parse("samplexml.xml") print("Document Node:", doc.nodeName) print("Root Tag:", doc.firstChild.tagName) skills = doc.getElementsByTagName("skill") print("Skill count:", skills.length) for skill in skills: print("Skill:", skill.getAttribute("name")) except Exception as e: print("Error loading or parsing XML:", e)
7. os – Interacting with the Operating System
The os module provides a way to use operating system-dependent functionality like reading or writing to the file system.
Key Features:
os.getcwd(): Get current working directoryos.listdir(): List files/directoriesos.mkdir(),os.remove(),os.rename()os.path: Common path operations
import os # Get current working directory print("Current directory:", os.getcwd()) # List files in the current directory print("Files:", os.listdir()) # Join paths safely full_path = os.path.join(os.getcwd(), "test.txt") print("Full path:", full_path)
8. sys – System-Specific Parameters and Functions
Useful for interacting with the Python interpreter and command-line arguments.
Key Features:
sys.argv: Access command-line argumentssys.exit(): Exit scriptsys.path: View module search paths
import sys print("Script name:", sys.argv[0]) print("Python version:", sys.version)
9. math – Mathematical Functions
Provides access to basic mathematical functions and constants.
Key Features:
math.sqrt(),math.pow(),math.factorial()Constants:math.pi,math.e
import math print("Square root of 25:", math.sqrt(25)) print("Pi:", math.pi)
10. random – Generating Random Numbers
Useful for simulations, games, or any situation needing randomization.
Key Features:
random.randint(a, b)random.choice(list)random.shuffle(list)
import random print("Random number:", random.randint(1, 10)) print("Random choice:", random.choice(['Praveen', 'Kiran', 'Praneeth']))
11. re – Regular Expressions
Enables powerful pattern matching and text processing.
Key Features:
re.search(),re.match(),re.findall()- Pattern substitution with
re.sub()
import re pattern = r"\d+" text = "There are 24 hours in a day." matches = re.findall(pattern, text) print("Found numbers:", matches)