Day 2 at Python
Topics Covered
1. List Slicing
2. Tuple
3. Dictionary
4. Set
5. Exception Handling
6. Different Types of Exceptions
7. File Handling
8. Login System Using File Handling and Exception Handling
1. List Slicing
In Day 2, we learned about lists.
A list is used to store multiple values in one variable.
Example:
fruits = ["apple", "banana", "mango", "orange", "grapes"]
Now, we will learn list slicing.
List slicing means taking a specific part of a list.
List Index Revision
In Python, list index starts from 0.
Example:
fruits = ["apple", "banana", "mango", "orange"]
Index values:
apple -> index 0
banana -> index 1
mango -> index 2
orange -> index 3
Example:
fruits = ["apple", "banana", "mango", "orange"]
print(fruits[0])
print(fruits[1])
Output:
apple
banana
Basic List Slicing
Example:
numbers = [10, 20, 30, 40, 50]
print(numbers[0:3])
Output:
[10, 20, 30]
Explanation:
numbers[0:3]
means start from index 0 and stop before index 3.
It includes:
numbers[0]
numbers[1]
numbers[2]
It does not include index 3.
More List Slicing Examples
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[0:3])
print(numbers[2:5])
print(numbers[:4])
print(numbers[3:])
Output:
[10, 20, 30]
[30, 40, 50]
[10, 20, 30, 40]
[40, 50, 60]
Explanation:
numbers[0:3]
starts from index 0 and stops before index 3.
numbers[2:5]
starts from index 2 and stops before index 5.
numbers[:4]
starts from the beginning and stops before index 4.
numbers[3:]
starts from index 3 and goes until the end.
Negative Indexing
Python also supports negative indexing.
Example:
fruits = ["apple", "banana", "mango", "orange"]
print(fruits[-1])
print(fruits[-2])
Output:
orange
mango
Explanation:
-1
means last item.
-2
means second last item.
Negative Slicing
Example:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[-3:])
Output:
[40, 50, 60]
Explanation:
numbers[-3:]
means take the last three items.
Slicing With Step
Example:
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[0:6:2])
Output:
[10, 30, 50]
Explanation:
numbers[0:6:2]
means:
Start from index 0
Stop before index 6
Move by step 2
Reverse a List Using Slicing
Example:
numbers = [10, 20, 30, 40, 50]
print(numbers[::-1])
Output:
[50, 40, 30, 20, 10]
Explanation:
[::-1]
is used to reverse a list.
List Slicing Questions
Question 1
Print the first three items from a list.
Solution:
fruits = ["apple", "banana", "mango", "orange", "grapes"]
print(fruits[0:3])
Output:
['apple', 'banana', 'mango']
Question 2
Print the last two items from a list.
Solution:
fruits = ["apple", "banana", "mango", "orange", "grapes"]
print(fruits[-2:])
Output:
['orange', 'grapes']
Question 3
Reverse a list using slicing.
Solution:
numbers = [1, 2, 3, 4, 5]
print(numbers[::-1])
Output:
[5, 4, 3, 2, 1]
2. Tuple
A tuple is used to store multiple values in one variable.
It is similar to a list.
But the main difference is:
List is changeable.
Tuple is not changeable.
That means after creating a tuple, we cannot directly add, remove, or change its items.
Example:
fruits = ("apple", "banana", "mango")
print(fruits)
Output:
('apple', 'banana', 'mango')
Here, fruits is a tuple.
Accessing Tuple Items
Tuple index also starts from 0, just like list.
Example:
fruits = ("apple", "banana", "mango")
print(fruits[0])
print(fruits[1])
print(fruits[2])
Output:
apple
banana
mango
Explanation:
fruits[0]
gives "apple".
fruits[1]
gives "banana".
fruits[2]
gives "mango".
Tuple Cannot Be Changed
Example:
fruits = ("apple", "banana", "mango")
fruits[0] = "orange"
print(fruits)
This gives an error.
Because tuple does not allow item change.
Why Use Tuple?
We use tuple when we want to store values that should not change.
Example:
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
Days of the week are fixed, so tuple is a good choice.
Another example:
location = (26.4525, 87.2718)
This can store latitude and longitude.
Looping Through Tuple
Example:
fruits = ("apple", "banana", "mango")
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
Explanation:
Tuple is iterable.
So we can use a for loop to read each item one by one.
Tuple Question 1
Write a program to store five student names in a tuple and print them one by one.
Solution:
students = ("Ram", "Sita", "Hari", "Gita", "Shyam")
for student in students:
print(student)
Output:
Ram
Sita
Hari
Gita
Shyam
Tuple Question 2
Write a program to find the length of a tuple.
Solution:
numbers = (10, 20, 30, 40, 50)
print("Total items:", len(numbers))
Output:
Total items: 5
Explanation:
len() counts how many items are inside the tuple.
Tuple Question 3
Write a program to check whether "apple" exists in a tuple or not.
Solution:
fruits = ("apple", "banana", "mango")
if "apple" in fruits:
print("Apple exists")
else:
print("Apple does not exist")
Output:
Apple exists
3. Dictionary
A dictionary is used to store data in key-value pairs.
Example:
student = {
"name": "Ram",
"age": 18,
"address": "Kathmandu"
}
print(student)
Output:
{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
Here:
"name"
is a key.
"Ram"
is the value.
Real-Life Example of Dictionary
A student has different details:
Name: Ram
Age: 18
Address: Kathmandu
In Python, we can store this like:
student = {
"name": "Ram",
"age": 18,
"address": "Kathmandu"
}
Dictionary is useful when we want to store related information.
Accessing Dictionary Values
Example:
student = {
"name": "Ram",
"age": 18,
"address": "Kathmandu"
}
print(student["name"])
print(student["age"])
print(student["address"])
Output:
Ram
18
Kathmandu
Explanation:
We use the key to access the value.
student["name"]
gives "Ram".
Updating Dictionary Value
Example:
student = {
"name": "Ram",
"age": 18
}
student["age"] = 19
print(student)
Output:
{'name': 'Ram', 'age': 19}
Explanation:
The value of "age" was changed from 18 to 19.
Adding New Key-Value Pair
Example:
student = {
"name": "Ram",
"age": 18
}
student["address"] = "Kathmandu"
print(student)
Output:
{'name': 'Ram', 'age': 18, 'address': 'Kathmandu'}
Explanation:
A new key "address" was added to the dictionary.
Removing Item from Dictionary
Example:
student = {
"name": "Ram",
"age": 18,
"address": "Kathmandu"
}
student.pop("age")
print(student)
Output:
{'name': 'Ram', 'address': 'Kathmandu'}
Explanation:
pop() removes the item with the given key.
Looping Through Dictionary
Example:
student = {
"name": "Ram",
"age": 18,
"address": "Kathmandu"
}
for key in student:
print(key)
Output:
name
age
address
This prints only keys.
To print values:
student = {
"name": "Ram",
"age": 18,
"address": "Kathmandu"
}
for key in student:
print(student[key])
Output:
Ram
18
Kathmandu
To print both key and value:
student = {
"name": "Ram",
"age": 18,
"address": "Kathmandu"
}
for key, value in student.items():
print(key, ":", value)
Output:
name : Ram
age : 18
address : Kathmandu
Dictionary Question 1
Write a program to store student name, age, and address in a dictionary and print them.
Solution:
student = {
"name": "Sita",
"age": 19,
"address": "Pokhara"
}
print("Name:", student["name"])
print("Age:", student["age"])
print("Address:", student["address"])
Output:
Name: Sita
Age: 19
Address: Pokhara
Dictionary Question 2
Write a program to store product name, price, and quantity. Then calculate total price.
Solution:
product = {
"name": "Pen",
"price": 20,
"quantity": 5
}
total = product["price"] * product["quantity"]
print("Product:", product["name"])
print("Total price:", total)
Output:
Product: Pen
Total price: 100
Explanation:
Price is 20.
Quantity is 5.
So:
20 * 5 = 100
Dictionary Question 3
Write a program to update a student's marks.
Solution:
student = {
"name": "Ram",
"marks": 75
}
student["marks"] = 85
print(student)
Output:
{'name': 'Ram', 'marks': 85}
4. Set
A set is used to store multiple values in one variable.
But set has two important features:
1. Set does not allow duplicate values.
2. Set does not maintain fixed order.
Example:
numbers = {10, 20, 30, 40}
print(numbers)
Output may be:
{40, 10, 20, 30}
The order may be different.
That is normal in set.
Set Does Not Allow Duplicate Values
Example:
numbers = {10, 20, 20, 30, 30, 40}
print(numbers)
Output:
{40, 10, 20, 30}
Explanation:
Duplicate values are automatically removed.
Adding Item to Set
Example:
fruits = {"apple", "banana"}
fruits.add("mango")
print(fruits)
Output may be:
{'apple', 'banana', 'mango'}
The order may be different.
Removing Item from Set
Example:
fruits = {"apple", "banana", "mango"}
fruits.remove("banana")
print(fruits)
Output:
{'apple', 'mango'}
Looping Through Set
Example:
fruits = {"apple", "banana", "mango"}
for fruit in fruits:
print(fruit)
Output may be:
banana
apple
mango
Explanation:
Set is iterable.
But the order is not fixed.
Why Use Set?
Set is useful when we want unique values only.
Example:
students = {"Ram", "Sita", "Ram", "Hari", "Sita"}
print(students)
Output:
{'Ram', 'Sita', 'Hari'}
Duplicate names are removed.
Set Question 1
Write a program to remove duplicate numbers from a list.
Solution:
numbers = [10, 20, 20, 30, 30, 40]
unique_numbers = set(numbers)
print(unique_numbers)
Output:
{40, 10, 20, 30}
Explanation:
The list contains duplicate values.
When we convert it into a set, duplicate values are removed.
Set Question 2
Write a program to add a new student name in a set.
Solution:
students = {"Ram", "Sita", "Hari"}
students.add("Gita")
print(students)
Output may be:
{'Ram', 'Sita', 'Hari', 'Gita'}
Set Question 3
Write a program to check whether "Ram" exists in a set or not.
Solution:
students = {"Ram", "Sita", "Hari"}
if "Ram" in students:
print("Ram exists")
else:
print("Ram does not exist")
Output:
Ram exists
5. Exception Handling
Exception handling means handling errors in a program.
Sometimes our program may get an error while running.
Example:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a / b)
If the user enters:
10
0
Then the program gives an error because division by zero is not allowed.
To handle this kind of error, we use:
try
except
Basic Try Except
Example:
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print("Result:", result)
except:
print("Something went wrong")
Explanation:
The code that may cause an error is written inside try.
If an error happens, the code inside except runs.
So instead of crashing, the program shows a message.
Better Try Except
It is better to mention the exact error name.
Example:
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter numbers only")
Explanation:
ZeroDivisionError happens when we divide by zero.
ValueError happens when we enter invalid number input.
6. Different Types of Exceptions
Python has many types of exceptions.
Some common exceptions are:
1. ValueError
2. ZeroDivisionError
3. FileNotFoundError
4. IndexError
5. KeyError
6. TypeError
7. NameError
8. PermissionError
1. ValueError
ValueError happens when the value is not valid.
Example:
age = int("hello")
This gives an error because "hello" cannot be converted into an integer.
Correct handling:
try:
age = int(input("Enter your age: "))
print("Your age is", age)
except ValueError:
print("Please enter a valid number")
2. ZeroDivisionError
ZeroDivisionError happens when we divide a number by zero.
Example:
try:
a = 10
b = 0
result = a / b
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
3. FileNotFoundError
FileNotFoundError happens when we try to read a file that does not exist.
Example:
try:
with open("data.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("File not found")
4. IndexError
IndexError happens when we try to access an index that does not exist in a list.
Example:
try:
numbers = [10, 20, 30]
print(numbers[5])
except IndexError:
print("Index does not exist")
Output:
Index does not exist
Explanation:
The list has only three items.
Available indexes are:
0, 1, 2
But we tried to access index 5.
So IndexError happened.
5. KeyError
KeyError happens when we try to access a dictionary key that does not exist.
Example:
try:
student = {
"name": "Ram",
"age": 18
}
print(student["address"])
except KeyError:
print("Key does not exist")
Output:
Key does not exist
Explanation:
The dictionary has only:
name
age
But we tried to access:
address
So KeyError happened.
6. TypeError
TypeError happens when we perform an operation with the wrong data type.
Example:
try:
result = "Age: " + 20
print(result)
except TypeError:
print("Cannot add string and number directly")
Output:
Cannot add string and number directly
Correct way:
result = "Age: " + str(20)
print(result)
7. NameError
NameError happens when we use a variable that has not been created.
Example:
try:
print(username)
except NameError:
print("Variable is not defined")
Output:
Variable is not defined
8. PermissionError
PermissionError happens when Python does not have permission to read or write a file.
Example:
try:
with open("/root/data.txt", "w") as file:
file.write("Hello")
except PermissionError:
print("You do not have permission to write this file")
Handling Multiple Exceptions Together
Example:
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print("Result:", result)
except ValueError:
print("Please enter numbers only")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print("Something went wrong:", e)
Explanation:
ValueError handles invalid input.
ZeroDivisionError handles division by zero.
Exception handles any other unexpected error.
Try Except Else
else runs only when there is no error.
Example:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Please enter a valid number")
else:
print("Your age is", age)
Explanation:
If the user enters a correct number, else runs.
If the user enters text like "abc", except runs.
Try Except Finally
finally always runs.
Example:
try:
number = int(input("Enter a number: "))
print(number)
except ValueError:
print("Invalid input")
finally:
print("Program finished")
Explanation:
Whether error happens or not, finally runs.
7. File Handling
File handling means working with files using Python.
Using file handling, we can:
1. Create a file
2. Write data into a file
3. Read data from a file
4. Add new data into an existing file
Opening a File
Python uses open() to open a file.
Syntax:
file = open("filename.txt", "mode")
Common file modes:
"r" read mode
"w" write mode
"a" append mode
Write Mode
Write mode is used to write data into a file.
Example:
file = open("student.txt", "w")
file.write("Hello, this is my first file.")
file.close()
Explanation:
student.txt is the file name.
"w" means write mode.
write() writes data into the file.
close() closes the file.
Important:
If the file does not exist, Python creates it.
If the file already exists, write mode replaces old content.
Reading a File
Example:
file = open("student.txt", "r")
data = file.read()
print(data)
file.close()
Output:
Hello, this is my first file.
Explanation:
"r" means read mode.
read() reads the file content.
Append Mode
Append mode is used to add new data without deleting old data.
Example:
file = open("student.txt", "a")
file.write("\nThis is new line.")
file.close()
Explanation:
"a" means append mode.
It adds new content at the end of the file.
\n means new line.
Better Way: Using with open()
The better way to work with files is:
with open("student.txt", "w") as file:
file.write("Hello Python")
Here, we do not need to write:
file.close()
Python automatically closes the file.
Read File Using with open()
Example:
with open("student.txt", "r") as file:
data = file.read()
print(data)
File Handling With Exception Handling
File handling and exception handling are often used together.
Why?
Because file errors can happen.
For example:
1. File may not exist.
2. User may enter wrong input.
3. Program may not have permission to read/write file.
Example:
try:
with open("student.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("File does not exist")
Explanation:
If student.txt exists, Python reads the file.
If it does not exist, FileNotFoundError happens.
Then except block runs.
8. File-Based Login System
Now we will create a simple login system using file handling.
In this system:
Each user will have their own file.
The username will be used as the file name.
The password will be saved inside that file.
Example:
If username is:
ram
Then Python creates:
ram.txt
Inside ram.txt, the password is saved.
Full Login System Code
def register():
username = input("Enter your username: ")
password = input("Enter your password: ")
try:
file = open(f"{username}.txt", "r")
print("Username already exists")
file.close()
except FileNotFoundError:
with open(f"{username}.txt", "w") as f:
f.write(password)
print("User registered successfully")
except Exception as e:
print("Something went wrong while registering:", e)
def login():
username = input("Enter your username: ")
password = input("Enter your password: ")
try:
file = open(f"{username}.txt", "r")
file.close()
except FileNotFoundError:
print("User not found")
return
except Exception as e:
print("Something went wrong while opening user file:", e)
return
try:
with open(f"{username}.txt", "r") as f:
checkpass = f.readline()
if password == checkpass:
print("Welcome")
else:
print("Sorry, incorrect password")
except Exception as e:
print("Something went wrong while checking password:", e)
def ask():
x = input("Do you want to register or login? Press r for register and l for login: ")
if x == "r":
register()
elif x == "l":
login()
else:
print("Invalid choice")
ask()
9. Explanation of Login System
Register Function
def register():
This function is used to register a new user.
username = input("Enter your username: ")
password = input("Enter your password: ")
Here, the program asks the user to enter username and password.
Checking If Username Already Exists
try:
file = open(f"{username}.txt", "r")
print("Username already exists")
file.close()
Here, the program tries to open a file with the username.
Example:
If username is:
ram
Then it tries to open:
ram.txt
If the file exists, it means the username is already registered.
So the program prints:
Username already exists
Creating File for New User
except FileNotFoundError:
with open(f"{username}.txt", "w") as f:
f.write(password)
print("User registered successfully")
If the file does not exist, Python gives FileNotFoundError.
That means the username is new.
So the program creates a new file and saves the password inside it.
Example:
If username is:
sita
Then file name becomes:
sita.txt
And inside that file, the password is saved.
Login Function
def login():
This function is used to login an existing user.
username = input("Enter your username: ")
password = input("Enter your password: ")
The program asks for username and password.
Checking If User Exists
try:
file = open(f"{username}.txt", "r")
file.close()
The program tries to open the user's file.
If the file exists, the user exists.
User Not Found
except FileNotFoundError:
print("User not found")
return
If the file does not exist, the program prints:
User not found
Here, return is used to stop the function.
This is better than exit() because exit() closes the whole program immediately.
Reading Saved Password
with open(f"{username}.txt", "r") as f:
checkpass = f.readline()
This opens the user's file and reads the saved password.
The saved password is stored in:
checkpass
Checking Password
if password == checkpass:
print("Welcome")
else:
print("Sorry, incorrect password")
If entered password and saved password are same, login is successful.
Otherwise, it prints incorrect password.
10. Simpler Version Like Your Original Code
This is very close to your original code.
def register():
username = input("Enter your username: ")
password = input("Enter your password: ")
try:
file = open(f"{username}.txt", "r")
print("Username already exists")
file.close()
except:
with open(f"{username}.txt", "w") as f:
f.write(password)
print("User registered successfully")
def login():
username = input("Enter your username: ")
password = input("Enter your password: ")
try:
file = open(f"{username}.txt", "r")
file.close()
except:
print("User not found")
return
with open(f"{username}.txt", "r") as f:
checkpass = f.readline()
if password == checkpass:
print("Welcome")
else:
print("Sorry, incorrect password")
def ask():
x = input("Do you want to register or login? Press r for register and l for login: ")
if x == "r":
register()
else:
login()
ask()
This version is okay for beginners.
But for better practice, this is preferred:
except FileNotFoundError:
instead of only:
except:
Because except: catches all errors, but FileNotFoundError catches only file-not-found error.
11. Important Note About This Login System
This login system is only for learning.
It teaches:
1. Function
2. Input
3. File handling
4. Try and except
5. User already exists
6. User not found
7. Password checking
But in real websites or real applications, passwords should not be saved directly like this.
In real projects, passwords should be hashed before saving.
For now, this is good for beginner-level Python file handling practice.
12. Class Explanation Flow
You can explain the login system like this:
When registering:
Python checks if username.txt exists.
If it exists, the user already exists.
If it does not exist, Python creates the file and saves the password.
When logging in:
Python checks if username.txt exists.
If it does not exist, user not found.
If it exists, Python reads the saved password.
Then it compares the saved password with the entered password.
13. Day 3 Practice Questions
List Slicing Questions
Create a list of 10 numbers and print the first 5 numbers.
Print the last 3 numbers from a list.
Reverse a list using slicing.
Print every second item from a list.
Tuple Questions
Create a tuple of five fruits and print each fruit.
Create a tuple of numbers and find its length.
Check whether
"Python"exists in a tuple.Try to change a tuple item and observe the error.
Dictionary Questions
Create a dictionary for a student with name, age, class, and address.
Create a dictionary for a product and calculate total price.
Update the marks of a student in a dictionary.
Print all keys and values from a dictionary.
Set Questions
Create a set of numbers with duplicate values and print it.
Add a new item to a set.
Remove an item from a set.
Convert a list with duplicate values into a set.
Exception Handling Questions
Take two numbers and divide them. Handle
ZeroDivisionError.Take age from user. Handle
ValueError.Try to access an invalid list index. Handle
IndexError.Try to access an invalid dictionary key. Handle
KeyError.Try to read a file that does not exist. Handle
FileNotFoundError.
File Handling Questions
Create a file named
message.txtand write"Hello Python"into it.Read and print the content of
message.txt.Append three student names into
students.txt.Read a file and handle
FileNotFoundError.
Final Project Question
Create a login system using file handling.
Requirements:
1. Register user.
2. Login user.
3. If user already exists, show message.
4. If user does not exist, show user not found.
5. If password is correct, show welcome.
6. If password is wrong, show incorrect password.
7. Use try and except.
8. Store each user password in username.txt file.
14. Day 3 Final Summary
Today we learned:
List slicing:
Used to get part of a list.
Tuple:
Used to store multiple values that should not change.
Dictionary:
Used to store data in key-value pairs.
Set:
Used to store unique values.
Exception handling:
Used to handle errors without crashing the program.
File handling:
Used to create, read, write, and append files.
Login system:
Used file handling and exception handling together.
Final simple memory:
List -> changeable collection
Tuple -> unchangeable collection
Dictionary -> key-value collection
Set -> unique value collection
try-except -> error handling
File -> permanent data storage
Comments
Join the discussionNo comments yet. Be the first to comment.