0% found this document useful (0 votes)
25 views14 pages

Introduction To Python

The document provides an introduction to Python, highlighting its simplicity, versatility, and the use of the CSV module for handling data in CSV format. It outlines key functions such as csv.reader() and csv.writer() for reading and writing CSV files, along with basic programming constructs like input(), print(), while loops, and error handling. Additionally, it includes a source code example for a personalized to-do list application that utilizes these concepts.

Uploaded by

cuteff24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views14 pages

Introduction To Python

The document provides an introduction to Python, highlighting its simplicity, versatility, and the use of the CSV module for handling data in CSV format. It outlines key functions such as csv.reader() and csv.writer() for reading and writing CSV files, along with basic programming constructs like input(), print(), while loops, and error handling. Additionally, it includes a source code example for a personalized to-do list application that utilizes these concepts.

Uploaded by

cuteff24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

INTRODUCTION TO PYTHON

Python is a high-level, interpreted, and general-purpose programming


language. It was developed by Guido van Rossum and released in 1991.
Python is renowned for its simplicity and readability, which makes it
an excellent choice for both beginners and experienced developers.
Python emphasizes code readability and the use of whitespace, which
helps to reduce the complexity of the code. This makes Python
particularly popular for rapid development in fields such as web
development, data analysis, artificial intelligence, scientific computing,
automation, and more.

The core philosophy of Python is captured in the "Zen of Python,"


which states that there should be one—and preferably only one—
obvious way to do something. This makes Python an ideal language for
people who are new to programming and helps developers write clean
and understandable code.

Python is known for its versatility. It can be used for small projects, as
well as large-scale applications. Additionally, Python has a rich
ecosystem of libraries and frameworks that further extend its
functionality. Libraries like numpy and pandas are extensively used for
data analysis, while frameworks like Django and Flask make it easy to
build web applications.

Python’s built-in support for various file formats, such as CSV


(Comma-Separated Values), makes it particularly useful for data
processing tasks.
INTRODUCTION TO CSV FILES

CSV (Comma-Separated Values) is a simple text file format used to


store data in a tabular structure (i.e., rows and columns). Each row in
the file represents a data record, and each column within that row
represents a field of data. The values are separated by commas (or
another delimiter), making it easy to store and exchange data between
different programs, such as spreadsheets, databases, and statistical
analysis software.

CSV files are lightweight, human-readable, and can be created or edited


using any text editor or spreadsheet software. Python provides a built-
in csv module that simplifies the process of reading and writing CSV
files. This module allows users to parse, process, and manipulate CSV
data easily.

The CSV format is widely used due to its simplicity and ease of
integration with various applications. In Python, the csv module makes
it straightforward to handle CSV files by providing methods for reading
and writing the data as lists or dictionaries.

In essence, CSV files are a great choice for quick, simple data storage
and sharing, but their limitations must be considered when handling
more sophisticated data management tasks.
MODULES USED IN PYTHON

1. CSV Module

The CSV module is part of Python's standard library and is specifically


designed for reading and writing CSV (Comma Separated Values)
files. CSV is a common format for storing tabular data, and the CSV
module provides an easy way to interact with these types of files.

KEY FUNCTIONS AND METHODS

csv.reader(): This function is used to read data from a CSV file. It


parses each line of the file and converts it into a list of values, with each
value representing a column in that row. The function can be
configured to handle various delimiters, but by default, it assumes that
the values are separated by commas.

csv.writer(): This function is used to write data to a CSV file. It allows


you to write a list of values (each representing a row in the CSV file).
Each value is automatically separated by commas.

USE IN THE PROGRAM:

The csv.reader() function is used to read the records from the CSV file
and display them to the user.

The csv.writer() function is used to add new records to the CSV file or
overwrite the file with updated data when a record is edited or deleted.

2. input() Function

The input() function is built into Python and is used to prompt the user
for input from the command line or console. This function always
returns the input as a string, which can then be processed or converted
into other data types if needed.
3. print() Function

The print() function is another built-in Python function that outputs data
to the console. It is used to display information or feedback to the user
during the execution of the program. The print() function is commonly
used in interactive applications to guide users, display results, or
confirm actions.

4. while Loop (Control Flow)

The while loop is a fundamental control flow statement in Python. It


repeatedly executes a block of code as long as the condition provided
evaluates to True. If the condition becomes False, the loop exits, and
the program continues with the next line of code.

5. try and except (Error Handling)

Python provides the try and except blocks to handle exceptions (errors).
This allows the program to gracefully handle errors and avoid crashes,
instead of letting the program terminate unexpectedly.
SOURCE CODE

import csv
from datetime import datetime
# Display menu
def display_menu():
print("\nPersonalized To-Do List")
print("1. Add Task")
print("2. View All Tasks")
print("3. Edit Task")
print("4. Delete Task")
print("5. Filter Tasks by Priority")
print("6. Filter Tasks by Deadline")
print("7. Exit")
# Add a task
def add_task(filename):
task_name = input("Enter task name: ")
priority = input("Enter priority (High/Medium/Low): ").capitalize()
deadline = input("Enter deadline (YYYY-MM-DD): ")
try:
datetime.strptime(deadline, '%Y-%m-%d') # Validate date format
except ValueError:
print("Invalid date format. Please enter in YYYY-MM-DD.")
return
with open(filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([task_name, priority, deadline])
print("Task added successfully!")
# View all tasks
def view_tasks(filename):
print("\n--- To-Do List ---")
try:
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
print(f"Task: {row[0]}, Priority: {row[1]}, Deadline: {row[2]}")
except FileNotFoundError:
print("No tasks found. Add a task first!")
print("--- End of List ---")
# Edit a task
def edit_task(filename):
task_name = input("Enter the task name to edit: ")
updated = False
tasks = []
try:
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
if row[0].lower() == task_name.lower():
print(f"Editing task: {row[0]}")
row[1] = input(f"Enter new priority (current: {row[1]}): ").capitalize()
row[2] = input(f"Enter new deadline (current: {row[2]}): ")
updated = True
tasks.append(row)
except FileNotFoundError:
print("No tasks found. Add a task first!")
return
if updated:
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerows(tasks)
print("Task updated successfully!")
else:
print("Task not found!")
# Delete a task
def delete_task(filename):
task_name = input("Enter the task name to delete: ")
tasks = []
deleted = False
try:
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
if row[0].lower() != task_name.lower():
tasks.append(row)
else:
deleted = True
except FileNotFoundError:
print("No tasks found. Add a task first!")
return
if deleted:
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerows(tasks)
print("Task deleted successfully!")
else:
print("Task not found!")
# Filter tasks by priority
def filter_by_priority(filename):
priority = input("Enter priority to filter (High/Medium/Low): ").capitalize()
print(f"\n--- Tasks with {priority} Priority ---")
found = False
try:
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
if row[1] == priority:
print(f"Task: {row[0]}, Priority: {row[1]}, Deadline: {row[2]}")
found = True
except FileNotFoundError:
print("No tasks found. Add a task first!")
return
if not found:
print(f"No tasks found with {priority} priority.")
print("--- End of List ---")
# Filter tasks by deadline
def filter_by_deadline(filename):
deadline = input("Enter deadline to filter tasks before (YYYY-MM-DD): ")
try:
deadline_date = datetime.strptime(deadline, '%Y-%m-%d')
except ValueError:
print("Invalid date format. Please enter in YYYY-MM-DD.")
return
print(f"\n--- Tasks Due Before {deadline} ---")
found = False
try:
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
task_deadline = datetime.strptime(row[2], '%Y-%m-%d')
if task_deadline <= deadline_date:
print(f"Task: {row[0]}, Priority: {row[1]}, Deadline: {row[2]}")
found = True
except FileNotFoundError:
print("No tasks found. Add a task first!")
return
if not found:
print("No tasks found before the given deadline.")
print("--- End of List ---")
# Main function
def main():
filename = 'todo_list.csv'
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == '1':
add_task(filename)
elif choice == '2':
view_tasks(filename)
elif choice == '3':
edit_task(filename)
elif choice == '4':
delete_task(filename)
elif choice == '5':
filter_by_priority(filename)
elif choice == '6':
filter_by_deadline(filename)
elif choice == '7':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice! Please try again.")
if __name__ == "__main__":
main()
OUTPUT
1)ADDING TASKS TO THE CSV FILE
2) VIEWING ALL TASKS

3) EDITING THE RECORDS


5) FILTERING THE RECORDS BY PRIORITY
6) FILTERING RECORD BY DEADLINES

7) EXITING THE PROGRAM


BIBLIOGRAPHY

1) SUMITA ARORA :"Computer Science with Python for Class 12"


Publisher: Dhanpat Rai & Co.

2) Python IDLE (Integrated Development and Learning Environment)

3) Google Chrome :Used to research Python concepts, file handling


techniques, and project ideas.

4) Project guidelines :CBSE Computer Science Practical Manual

5)Addition references :W3Schools: A comprehensive online resource


for Python tutorials and examples.
Website: https://www.w3schools.com/python

You might also like