Python Mini-Project: To-Do List Application

Version 1: Basic Command-Line To-Do List

# Basic Command-Line To-Do List - Version 01

todos = []

while True:
user_prompt = input('\nType Add, Show, Edit, Complete, Exit: ').strip()

match user_prompt:
case 'Add':
todo = input('Enter a todo to add: ')
todos.append(todo)
case 'Show':
for index, item in enumerate(todos):
print(f'{index+1}:{item}')
case 'Edit':
number = int(input('Enter index of todo to edit like 0,1 and so on: '))
new_todo = input('Enter new todo to replace: ')
todos[number-1] = new_todo
case 'Complete':
number = int(input('Enter the index to todo to removed since completed: '))
todos.pop(number-1)
case 'Exit':
break
case _:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Project_01.py


Type Add, Show, Edit, Complete, Exit: Add
Enter a todo to add: Go to market
Type Add, Show, Edit, Complete, Exit: Add
Enter a todo to add: Buy Grocery
Type Add, Show, Edit, Complete, Exit: Show
1:Go to market
2:Buy Grocery
Type Add, Show, Edit, Complete, Exit: Edit
Enter index of todo to edit like 0,1 and so on: 2
Enter new todo to replace: Buy Vegetable
Type Add, Show, Edit, Complete, Exit: Show
1:Go to market
2:Buy Vegetable
Type Add, Show, Edit, Complete, Exit: Complete
Enter the index to todo to removed since completed: 1
Type Add, Show, Edit, Complete, Exit: Show
1:Buy Vegetable
Type Add, Show, Edit, Complete, Exit: Exit
Bye thanks !!!

Difference Between match-case and if-else (Simple Explanation)

1. if-else (Conditional Statements)

  • Checks multiple conditions one by one.
  • Used when conditions involve comparisons (>, <, ==, etc.).
  • Works well when dealing with complex logic.

2. match-case (Pattern Matching)

  • Works like a switch statement in other languages.
  • Compares a variable against fixed values or patterns.
  • Best for handling multiple fixed choices (like menu options or commands).

When to Use Each?

βœ… Use if-else when:

  • You need to check conditions like greater than, less than, or logical conditions.
  • Example: Checking age to decide eligibility for voting.
age = 18

if age >= 18:
print("You can vote!")
else:
print("You cannot vote.")

βœ… Use match-case when:

  • You are handling multiple fixed values (like menu choices, error codes, or user inputs).
  • Example: Handling user input in a menu-based system.
choice = "start"

match choice:
case "start":
print("Game Started")
case "pause":
print("Game Paused")
case "exit":
print("Exiting Game")
case _:
print("Invalid Choice")

Key Takeaway:

  • Use if-else for conditions that require comparisons.
  • Use match-case when checking fixed values for better readability and efficiency.

# Basic Command-Line To-Do List - Version 02

todos = []

while True:
user_prompt = input('\nType Add, Show, Edit, Complete, Exit: ').strip()

match user_prompt:
case 'Add' | 'add':
todo = input('Enter a todo to add: ')
todos.append(todo)
case 'Show' | 'show':
for index, item in enumerate(todos):
print(f'{index+1}:{item}')
case 'Edit' | 'edit':
number = int(input('Enter index of todo to edit like 0,1 and so on: '))
new_todo = input('Enter new todo to replace: ')
todos[number-1] = new_todo
case 'Complete' | 'complete':
number = int(input('Enter the index to todo to removed since completed: '))
todos.pop(number-1)
case 'Exit' | 'exit':
break
case _:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Project_01.py

Type Add, Show, Edit, Complete, Exit: add
Enter a todo to add: KId PTM

Type Add, Show, Edit, Complete, Exit: add
Enter a todo to add: Market

Type Add, Show, Edit, Complete, Exit: show
1:KId PTM
2:Market

Type Add, Show, Edit, Complete, Exit: edit
Enter index of todo to edit like 0,1 and so on: 2
Enter new todo to replace: Doctor

Type Add, Show, Edit, Complete, Exit: complete
Enter the index to todo to removed since completed: 1

Type Add, Show, Edit, Complete, Exit: show
1:Doctor

Type Add, Show, Edit, Complete, Exit: exit
Bye thanks !!!

Process finished with exit code 0

Difference Between | and or in match-case

1. | (Pipe Operator in match-case)

  • Used inside a match-case block to match multiple fixed values in one case.
  • Works only in match-case, not in if-else.
  • Example:
choice = "start"

match choice:
case "start" | "begin":
print("Game Started")
case "pause" | "hold":
print("Game Paused")
case "exit" | "quit":
print("Exiting Game")
case _:
print("Invalid Choice")

βœ… Output if choice = "begin" β†’ "Game Started" (because "begin" is included in "start" | "begin").


2. or (Logical Operator in if-else)

  • Used in if-else conditions to combine multiple conditions.
  • Works anywhere in Python, including normal condition checks.
  • Example:
choice = "start"

if choice == "start" or choice == "begin":
print("Game Started")
elif choice == "pause" or choice == "hold":
print("Game Paused")
elif choice == "exit" or choice == "quit":
print("Exiting Game")
else:
print("Invalid Choice")

βœ… Output if choice = "begin" β†’ "Game Started" (same result, but written differently).

Version 2: Persistent To-Do List (File-Based Storage)

# Persistent To-Do List (File-Based Storage) - Version 01
# use of file method

while True:
user_prompt = input('\nType Add, Show, Edit, Complete, Exit: ').strip()

match user_prompt:
case 'Add' | 'add':
todo = input('Enter a todo to add: ') + '\n'

file = open('todos.txt', 'r')
todos = file.readlines()
file.close()

todos.append(todo)

file = open('todos.txt', 'w')
file.writelines(todos)
file.close()

case 'Show' | 'show':
file = open('todos.txt', 'r')
todos = file.readlines()
file.close()

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index+1}:{item}')
case 'Edit' | 'edit':
number = int(input('Enter index of todo to edit like 0,1 and so on: '))
new_todo = input('Enter new todo to replace: ')
todos[number-1] = new_todo
case 'Complete' | 'complete':
number = int(input('Enter the index to todo to removed since completed: '))
todos.pop(number-1)
case 'Exit' | 'exit':
break
case _:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Project_01.py

Type Add, Show, Edit, Complete, Exit: add
Enter a todo to add: Training

Type Add, Show, Edit, Complete, Exit: show
1:Doctor
2:Market
3:Kid PTM
4:School
5:Training

# Persistent To-Do List (File-Based Storage) - Version 02
# use of with method

while True:
user_prompt = input('\nType Add, Show, Edit, Complete, Exit: ').strip()

match user_prompt:
case 'Add' | 'add':
todo = input('Enter a todo to add: ') + '\n'

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.append(todo)

with open('todos.txt', 'w') as file:
file.writelines(todos)

case 'Show' | 'show':

with open('todos.txt', 'r') as file:
todos = file.readlines()

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index+1}:{item}')
case 'Edit' | 'edit':
number = int(input('Enter index of todo to edit like 0,1 and so on: '))

with open('todos.txt', 'r') as file:
todos = file.readlines()

new_todo = input('Enter new todo to replace: ')
todos[number-1] = new_todo + '\n'

with open('todos.txt', 'w') as file:
file.writelines(todos)

case 'Complete' | 'complete':

number = int(input('Enter the index to todo to removed since completed: '))

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.pop(number-1)

with open('todos.txt', 'w') as file:
file.writelines(todos)


case 'Exit' | 'exit':
break
case _:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type Add, Show, Edit, Complete, Exit: add
Enter a todo to add: Doctor

Type Add, Show, Edit, Complete, Exit: add
Enter a todo to add: Shopping

Type Add, Show, Edit, Complete, Exit: show
1:Doctor
2:Shopping

Type Add, Show, Edit, Complete, Exit: edit
Enter index of todo to edit like 0,1 and so on: 2
Enter new todo to replace: Market

Type Add, Show, Edit, Complete, Exit: show
1:Doctor
2:Market

Type Add, Show, Edit, Complete, Exit: complete
Enter the index to todo to removed since completed: 1

Type Add, Show, Edit, Complete, Exit: show
1:Market

Type Add, Show, Edit, Complete, Exit: exit
Bye thanks !!!

Process finished with exit code 0

# Persistent To-Do List (File-Based Storage) - Version 03
# use of in with if-else

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if 'add' in user_prompt:
todo = user_prompt[4:] + '\n'

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.append(todo)

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif 'show' in user_prompt:

with open('todos.txt', 'r') as file:
todos = file.readlines()

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index+1}:{item}')
elif 'edit' in user_prompt:
number = int(user_prompt[5:])

with open('todos.txt', 'r') as file:
todos = file.readlines()

new_todo = input('Enter new todo to replace: ')
todos[number-1] = new_todo + '\n'

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif 'complete' in user_prompt:

number = int(user_prompt[9:])

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.pop(number-1)

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif 'exit' in user_prompt:
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type add, show, edit, complete, exit: show
1:Market
2:testing

Type add, show, edit, complete, exit: add Doctor

Type add, show, edit, complete, exit: show
1:Market
2:testing
3:Doctor

Type add, show, edit, complete, exit: edit 2
Enter new todo to replace: Driving

Type add, show, edit, complete, exit: show
1:Market
2:Driving
3:Doctor

Type add, show, edit, complete, exit: complete 3

Type add, show, edit, complete, exit: show
1:Market
2:Driving

Type add, show, edit, complete, exit: exit
Bye thanks !!!

Process finished with exit code 0

Type add, show, edit, complete, exit: edit add new task

Type add, show, edit, complete, exit: show
1:Market
2:new
3: add new task

Type add, show, edit, complete, exit:

# Persistent To-Do List (File-Based Storage) - Version 04
# use of startswith

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.append(todo)

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif user_prompt.startswith('show'):

with open('todos.txt', 'r') as file:
todos = file.readlines()

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
number = int(user_prompt[5:])

with open('todos.txt', 'r') as file:
todos = file.readlines()

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif user_prompt.startswith('complete'):

number = int(user_prompt[9:])

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.pop(number - 1)

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type add, show, edit, complete, exit: add add new task

Type add, show, edit, complete, exit: show
1:Market
2:new
3: add new task
4:add new task

Type add, show, edit, complete, exit:

Version 3: Error Handling

# Error Handling 

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.append(todo)

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif user_prompt.startswith('show'):

with open('todos.txt', 'r') as file:
todos = file.readlines()

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

with open('todos.txt', 'r') as file:
todos = file.readlines()

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

with open('todos.txt', 'w') as file:
file.writelines(todos)
except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

with open('todos.txt', 'r') as file:
todos = file.readlines()

todos.pop(number - 1)

with open('todos.txt', 'w') as file:
file.writelines(todos)
except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type add, show, edit, complete, exit: edit test
Invalid Input

Type add, show, edit, complete, exit: edit 123
Enter new todo to replace: test
Enter valid Index

Type add, show, edit, complete, exit: complete one
Invalid Input

Type add, show, edit, complete, exit: complete 123
Enter valid Index

Type add, show, edit, complete, exit: show
1:Market
2:new
3: add new task
4:add new task
5:testing123

Type add, show, edit, complete, exit: exit
Bye thanks !!!

Understanding the Need for continue in while True

Let’s consider two cases:

πŸ”Ή Case 1: No continue – The loop naturally continues

If the loop naturally continues after handling an exception, you don’t need continue:

while True:
try:
num = int(input("Enter a number: ")) # If user enters "abc", it raises ValueError
print(f"You entered: {num}")
except ValueError:
print("Invalid input! Please enter a number.") # The loop continues without `continue`

βœ… Why it works?

  • After handling the exception, the loop moves to the next iteration automatically.

πŸ”Ή Case 2: Using continue to Explicitly Restart the Loop

You use continue when you want to immediately restart the loop without executing further code in the current iteration:

while True:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Try again.")
continue # Skips the next line and goes back to input prompt
print(f"You entered: {num}")

βœ… Why use continue?

  • Without continue, if an exception occurs, Python would still execute the next line (print(f"You entered: {num}")), which could cause errors.
  • continue forces the loop to restart immediately, skipping unnecessary execution.

πŸ”Ή When Should You Use continue?

βœ” Use continue if there is additional code after the try-except block that you want to skip when an exception occurs.
❌ Don’t use continue if the loop naturally continues as expected.

Where to Place continue in Multiple except Blocks?

βœ… Option 1: Use continue in Each except Block (if all errors should restart the loop)

If every exception should restart the loop, put continue in all except blocks:

while True:
try:
num = int(input("Enter a number: "))
result = 100 / num # Possible ZeroDivisionError
except ValueError:
print("Invalid input! Please enter a number.")
continue # Restart loop
except ZeroDivisionError:
print("Cannot divide by zero! Try again.")
continue # Restart loop
except Exception:
print("Something went wrong!")
continue # Restart loop
print(f"Result: {result}") # Runs only if no exception occurs

βœ… Why?

  • If an exception occurs, the loop restarts immediately, skipping the print(f"Result: {result}") statement.

βœ… Option 2: Use continue Only in Specific except Blocks

If only some exceptions should restart the loop while others allow the program to continue, put continue selectively:

while True:
try:
num = int(input("Enter a number: "))
result = 100 / num
except ValueError:
print("Invalid input! Please enter a number.")
continue # Restart loop
except ZeroDivisionError:
print("Cannot divide by zero! Try again.")
continue # Restart loop
except Exception:
print("Something unexpected happened!") # No continue here, so loop continues normally
print(f"Result: {result}") # This runs unless a ValueError or ZeroDivisionError occurs

βœ… Why?

  • continue is used only when we want to restart the loop.
  • If a general exception (Exception) occurs, we don’t restart the loopβ€”execution continues normally.

πŸ”Ή Key Takeaways

βœ” Use continue in each except block where you want to restart the loop.
βœ” Don’t use continue in except blocks where you want execution to proceed normally.
βœ” The last except block doesn’t need continue unless you specifically want to restart the loop.

Version 4: Custom Functions

# Custom Functions - Removed redundant codes v_01

def get_todos():
with open('todos.txt', 'r') as file_local:
todos_local = file_local.readlines()
return todos_local


while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

todos = get_todos()

todos.append(todo)

with open('todos.txt', 'w') as file:
file.writelines(todos)

elif user_prompt.startswith('show'):

todos = get_todos()

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

todos = get_todos()

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

with open('todos.txt', 'w') as file:
file.writelines(todos)
except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

todos = get_todos('todos.txt')

todos.pop(number - 1)

with open('todos.txt', 'w') as file:
file.writelines(todos)
except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type add, show, edit, complete, exit: show
1:Market
2:new
3: add new task
4:add new task
5:testing123

Type add, show, edit, complete, exit: add testing01

Type add, show, edit, complete, exit: add testing 02

Type add, show, edit, complete, exit: show
1:Market
2:new
3: add new task
4:add new task
5:testing123
6:testing01
7:testing 02

# Custom Functions - Removed redundant codes v_02

def get_todos(filepath):
with open(filepath, 'r') as file_local:
todos_local = file_local.readlines()
return todos_local


def write_todos(filepath, todos_arg):
with open(filepath, 'w') as file:
file.writelines(todos_arg)


while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

todos = get_todos('todos.txt')

todos.append(todo)

write_todos('todos.txt', todos)

elif user_prompt.startswith('show'):

todos = get_todos('todos.txt')

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

todos = get_todos('todos.txt')

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

todos = get_todos('todos.txt')

todos.pop(number - 1)

write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Ouput:

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Shopping

Type add, show, edit, complete, exit: add Vegetable

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Shopping
3:Vegetable

Type add, show, edit, complete, exit: complete 2

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable

Type add, show, edit, complete, exit: exit
Bye thanks !!!

Process finished with exit code 0

Version 5: Organizing the Code in Modules

# Organizing the Code in Modules v_01

from functions import get_todos, write_todos

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

todos = get_todos('todos.txt')

todos.append(todo)

write_todos('todos.txt', todos)

elif user_prompt.startswith('show'):

todos = get_todos('todos.txt')

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

todos = get_todos('todos.txt')

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

todos = get_todos('todos.txt')

todos.pop(number - 1)

write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable

Type add, show, edit, complete, exit: add Dentist

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable
3:Dentist

# Organizing the Code in Modules v_02

import functions

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

todos = functions.get_todos('todos.txt')

todos.append(todo)

functions.write_todos('todos.txt', todos)

elif user_prompt.startswith('show'):

todos = functions.get_todos('todos.txt')

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

todos = functions.get_todos('todos.txt')

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

functions.write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

todos = functions.get_todos('todos.txt')

todos.pop(number - 1)

functions.write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable
3:Dentist

Type add, show, edit, complete, exit: add Marketing

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable
3:Dentist
4:Marketing

# Organizing the Code in Modules v_03

from module import functions

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

todos = functions.get_todos('todos.txt')

todos.append(todo)

functions.write_todos('todos.txt', todos)

elif user_prompt.startswith('show'):

todos = functions.get_todos('todos.txt')

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

todos = functions.get_todos('todos.txt')

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

functions.write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

todos = functions.get_todos('todos.txt')

todos.pop(number - 1)

functions.write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable
3:Dentist
4:Marketing

Type add, show, edit, complete, exit: add Outing

Type add, show, edit, complete, exit: sho
Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable
3:Dentist
4:Marketing
5:Outing

# Organizing the Code in Modules v_04 (Add time stamp)

import functions
import time

now = time.strftime('%b %d, %Y %H:%M:%S')
print('It is', now)

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

todos = functions.get_todos('todos.txt')

todos.append(todo)

functions.write_todos('todos.txt', todos)

elif user_prompt.startswith('show'):

todos = functions.get_todos('todos.txt')

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

todos = functions.get_todos('todos.txt')

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

functions.write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

todos = functions.get_todos('todos.txt')

todos.pop(number - 1)

functions.write_todos('todos.txt', todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')

Output:

It is Feb 19, 2025 13:02:21

Type add, show, edit, complete, exit: show
1:Doctor Visit
2:Vegetable
3:Dentist
4:Marketing
5:Outing

# Organizing the Code in Modules v_05 (Default argument in module)

import functions
import time

now = time.strftime('%b %d, %Y %H:%M:%S')
print('It is', now)

while True:
user_prompt = input('\nType add, show, edit, complete, exit: ').strip()

if user_prompt.startswith('add'):
todo = user_prompt[4:] + '\n'

todos = functions.get_todos()

todos.append(todo)

functions.write_todos(todos)

elif user_prompt.startswith('show'):

todos = functions.get_todos()

for index, item in enumerate(todos):
item = item.strip('\n')
print(f'{index + 1}:{item}')
elif user_prompt.startswith('edit'):
try:
number = int(user_prompt[5:])

todos = functions.get_todos()

new_todo = input('Enter new todo to replace: ')
todos[number - 1] = new_todo + '\n'

functions.write_todos(todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('complete'):
try:
number = int(user_prompt[9:])

todos = functions.get_todos()

todos.pop(number - 1)

functions.write_todos(todos)

except ValueError:
print('Invalid Input')
continue
except IndexError:
print('Enter valid Index')
continue

elif user_prompt.startswith('exit'):
break
else:
print('''Invalid Input please enter valid input from:
Add
Show
Edit
Complete
Exit''')

print('Bye thanks !!!')
FILEPATH = 'todos.txt'

def get_todos(filepath=FILEPATH):
with open(filepath, 'r') as file_local:
todos_local = file_local.readlines()
return todos_local


def write_todos(todos_arg, filepath=FILEPATH):
with open(filepath, 'w') as file:
file.writelines(todos_arg)


# print('I am outside')

if __name__ == '__main__':
print('I am inside')
print(get_todos('todos.txt'))

Understanding if __name__ == "__main__":

This special condition in Python is used to control whether a script runs when executed directly or when imported as a module in another script.


πŸ”Ή What Does __name__ Mean?

In every Python script, Python automatically creates a special variable called __name__.

  • If the script is run directly, __name__ is set to "__main__".
  • If the script is imported into another script, __name__ is set to the module name instead.

βœ… Basic Example: Running Directly vs. Importing

πŸ“Œ Case 1: When Running the Script Directly

# my_script.py
print("This runs always!")

if __name__ == "__main__":
print("This runs only when executed directly!")

πŸ“Œ Output when you run my_script.py directly:

This runs always!
This runs only when executed directly!

βœ… Why?

  • Since the script is executed directly, __name__ is "__main__".

πŸ“Œ Case 2: When Importing the Script

Let’s import my_script.py into another script:

# another_script.py
import my_script
print("Hello from another_script.py!")

πŸ“Œ Output when running another_script.py:

This runs always!
Hello from another_script.py!

βœ… Why?

  • The first print statement in my_script.py executes because the file is imported.
  • But the code inside if __name__ == "__main__": does not run because __name__ is "my_script" (not "__main__").

πŸ”Ή Why Use if __name__ == "__main__":?

  1. Prevents certain code from running when imported.
  2. Useful for defining reusable modules (functions & classes remain accessible when imported).
  3. Commonly used in Python scripts that have a mix of functions and executable code.

βœ… Example: Using It in a Function

def greet():
print("Hello, World!")

if __name__ == "__main__":
greet() # Runs only if executed directly
  • If run directly β†’ It prints "Hello, World!".
  • If imported β†’ The function greet() is available, but it doesn’t execute automatically.

πŸ”Ή Summary

βœ” if __name__ == "__main__": ensures that some code only runs when the script is executed directly.
βœ” Prevents unintended execution when the script is imported into another module.
βœ” Best practice when writing reusable scripts and modules.

Click here to Download Python

Leave a Comment