Python Note by Bishworaj Poudel
Python Note by Bishworaj Poudel
🌟 Introduction to Python
Python is World’s most popular programming language. It is a beginner-friendly programming
language widely used in web development, artificial intelligence, data analysis, automation,
networking, and many other fields.
🖥️ Installing Python
Let's get Python up and running on your machine!
On Windows:
Master Python By Bishworaj Poudel
On Mac:
1. Download Python from the official website:
[python.org/downloads](https://www.python.org/downloads/)
2. Run the installer.
3. Open Terminal and type `python3 --version` to check the installation.
On Linux:
1. Open Terminal.
2. Type `sudo apt-get update`.
3. Type `sudo apt-get install python3`.
4. Type `python3 --version` to check the installation.
On Mac:
1. Download VS Code from the official website:
[code.visualstudio.com](https://code.visualstudio.com/)
2. Run the installer.
3. Open Visual Studio Code.
4. Click on Extensions.
5. Search for "Python".
6. Click "Install".
Master Python By Bishworaj Poudel
On Linux:
1. Download VS Code from the official website:
[code.visualstudio.com](https://code.visualstudio.com/)
2. Run the installer.
3. Open Visual Studio Code.
4. Click on Extensions.
5. Search for "Python".
6. Click "Install".
print("Hello, World!")
🎉 Python Examples
Example 1: Print Your Name
print("John Doe")
print("John Doe")
print("123 Main Street")
print("New York, NY 10001")
\n New Line
\t Tab
\“ Double Quotes
\’ Single Quotes
\\ Backslash
🌟 Variables In Python
Variables are like containers that store data values. In Python, you don’t need to declare the
type of a variable, as the language is dynamically typed. This means you can just assign a value
to a variable, and Python will handle the rest.
Syntax
variable_name = value
🎉 Variable Examples
Example 1: Storing a Name
Example 3: Print Your Full Name From First and Last Name
first_name = "Bishworaj"
last_name = "Poudel"
print(f"My full name is {first_name} {last_name}")
🎉 Example Demo
Here is the Python code demonstrating the above information:
# Variables representing library data
total_books = 500 # int
average_rating = 4.5 # float
librarian_name = "John Doe" # str
is_open = True # bool
book_names = ["Python Programming", "Introduction to Data Science",
"History of Art"] # list
location_coordinates = (40.7128, -74.0060) # tuple (latitude,
longitude)
contact_details = {
"phone": "123-456-7890",
"email": "[email protected]",
"address": "123 Library St, City, State"
} # dict
unique_genres = {"Fiction", "Non-fiction", "Science Fiction"} # set
# Printing out the library information
print("Library Information:")
print(f"Total number of books: {total_books}")
print(f"Average book rating: {average_rating}")
print(f"Librarian's name: {librarian_name}")
print(f"Is library open?: {'Yes' if is_open else 'No'}")
print(f"List of book names available: {book_names}")
print(f"Location coordinates: {location_coordinates}")
print(f"Contact details: {contact_details}")
print(f"Unique genres available: {unique_genres}")
Master Python By Bishworaj Poudel
print("This is String")
print('This is also String')
Note: Whether you choose single quotes or double quotes to create strings, the end result
remains the same.
Here is_subscribed indicates whether a user is subscribed to a service (True) or not (False). It
is a boolean (bool) data type, used for storing logical values, typically used for conditions or
flags.
# Example: Subscription status of a service
is_subscribed = True
print(f"Is the user subscribed?: {'Yes' if is_subscribed else 'No'}")
print(f"Type of is_subscribed: {type(is_subscribed)}")
"in_stock": True
}
# Print product information
print("Product information:")
print(f" Name: {product_info['name']}")
print(f" Brand: {product_info['brand']}")
print(f" Price: ${product_info['price']}")
print(f" In Stock: {'Yes' if product_info['in_stock'] else 'No'}")
# Print type of product_info
print(f"Type of product_info: {type(product_info)}")
Python offers several functions to convert data from one type to another. Here are some of the
most commonly used type conversion functions:
Master Python By Bishworaj Poudel
Function Description
🚀String Vs Numbers
Consider these two examples: 2024 and "2024". At first look, they might look the same. But in
Python, they represent two different types of data:
"456" 485
"0" 0
"99.9" 600.85
🌟 Comments In Python
Comments are text in a program that are ignored by the interpreter or compiler during
execution. They are used to explain the code, making it more readable and maintainable.
🚀Advantages
● You can describe your code.
● Other people will understand your code more clearly.
● They help in understanding the code's logic and purpose.
● Comments provide context for easier maintenance and updates.
● They facilitate better collaboration by explaining complex logic and decisions.
● For beginners, comments are a valuable tool for learning and understanding
programming concepts and structures.
🎉Example 1: Comments
This code performs and prints the result of adding two numbers, num1 and
num2. The comments explain that result_add is calculated by adding num1 and
num2, and the result is printed using an f-string for formatted output.
# Addition
Master Python By Bishworaj Poudel
🌟 Operators In Python
Operators are used to perform mathematical and logical operations on the variables. Each
operation uses a symbol called the operator to denote the type of operation it performs.
2 + 3
Note: Suppose the given expression is 2 + 3. Here 2 and 3 are operands, and + is the
operator.
🚀Arithmetic Operators
These are used to perform basic arithmetic operations like addition, subtraction, multiplication,
etc.
# Performing Operations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
floor_division = num1 // num2
modulus = num1 % num2
exponentiation = num1 ** num2
# Displaying Results
print(f"Addition: {num1} + {num2} = {addition}")
print(f"Subtraction: {num1} - {num2} = {subtraction}")
print(f"Multiplication: {num1} * {num2} = {multiplication}")
print(f"Division: {num1} / {num2} = {division}")
print(f"Floor Division: {num1} // {num2} = {floor_division}")
print(f"Modulus: {num1} % {num2} = {modulus}")
print(f"Exponentiation: {num1} ** {num2} = {exponentiation}")
Master Python By Bishworaj Poudel
🚀Comparison Operators
These are used to compare two values.
!= Not Equal Checks if the value of two operands are not equal
> Greater Than Checks if the value of the left operand is greater
than the right operand
< Less Than Checks if the value of the left operand is less than
the right operand
>= Greater or Equal Checks if the value of the left operand is greater
than or equal to the right operand
# Displaying Results
print(f"Equal: {num1} == {num2} is {equal}")
print(f"Not Equal: {num1} != {num2} is {not_equal}")
print(f"Greater Than: {num1} > {num2} is {greater_than}")
Master Python By Bishworaj Poudel
🚀Logical Operators
These are used to combine conditional statements.
not NOT Reverses the result, returns False if the result is true
# Displaying Results
print(f"AND Operation: (num1 > num2) and (num1 < 20) is
{and_operation}")
print(f"OR Operation: (num1 < num2) or (num1 < 20) is {or_operation}")
print(f"NOT Operation: not(num1 > num2) is {not_operation}")
Master Python By Bishworaj Poudel
🚀Assignment Operators
These are used to assign values to variables.
+= Add and Adds right operand to the left operand and assigns the result
Assignment to the left operand
-= Subtract Subtracts right operand from the left operand and assigns the
and result to the left operand
Assignment
*= Multiply and Multiplies the left operand with the right operand and assigns
Assignment the result to the left operand
/= Divide and Divides the left operand by the right operand and assigns the
Assignment result to the left operand
num1 -= num2
subtract_and_assign = num1
num1 *= num2
multiply_and_assign = num1
num1 /= num2
divide_and_assign = num1
# Displaying Results
print(f"Initial assignment: num1 = {initial_assignment}")
print(f"Add and assign: num1 += num2 -> num1 = {add_and_assign}")
print(f"Subtract and assign: num1 -= num2 -> num1 =
{subtract_and_assign}")
print(f"Multiply and assign: num1 *= num2 -> num1 =
{multiply_and_assign}")
print(f"Divide and assign: num1 /= num2 -> num1 = {divide_and_assign}")
🚀Membership Operators
These are used to test if a value is available in a sequence or not.
not in Not In Returns True if a specified value is not found in the sequence
# Displaying Results
print(f'"banana" in fruits: {is_banana_in_fruits}')
print(f'"grape" in fruits: {is_grape_in_fruits}')
print(f'"apple" not in fruits: {is_apple_not_in_fruits}')
print(f'"grape" not in fruits: {is_grape_not_in_fruits}')
This code takes one name as input and greets that name.
# Calculation
total = number1 + number2
💡 Challenge 7
Create a program that finds cube numbers using user input.
🌟 String In Python
A string in Python is a sequence of characters. It can include letters, numbers, symbols, and
whitespace. Strings are used to represent text data.
Note: You can create a string by enclosing characters in either single quotes (') or double
quotes (").
Master Python By Bishworaj Poudel
print("This is String")
print('This is also String')
user_name = "John"
greeting = "Hello, " + user_name + "! Welcome to our service."
print(greeting)
str.split(sep) Splits the string into a list using sep as the delimiter
# Strings
user_input = "hello world"
email = "[email protected]"
sentence = "welcome to the party."
book_title = "to kill a mockingbird"
username = " alice "
Master Python By Bishworaj Poudel
# 1. str.upper()
uppercase_input = user_input.upper()
print(f"Uppercase: {uppercase_input}")
# 2. str.lower()
normalized_email = email.lower()
print(f"Lowercase email: {normalized_email}")
# 3. str.capitalize()
capitalized_sentence = sentence.capitalize()
print(f"Capitalized sentence: {capitalized_sentence}")
# 4. str.title()
formatted_book_title = book_title.title()
print(f"Title Case: {formatted_book_title}")
# 5. str.strip()
cleaned_username = username.strip()
print(f"Stripped username: '{cleaned_username}'")
# 6. str.replace(a, b)
censored_comment = comment.replace("bad", "good")
print(f"Censored comment: {censored_comment}")
# 7. str.split(sep)
split_items = items.split(",")
print(f"Split items: {split_items}")
💡 Challenge 8
Master Python By Bishworaj Poudel
Write a Python program that takes a user's full name as input and Convert the full name to title
case (capitalize the first letter of each word). Also remove trailing and leading space.
🌟 Randomisation In Python
Randomization is a powerful tool in programming, enabling the creation of random values. This
code generates a random float between 0.0 and 1.0.
import random
print(random.random())
import random
import random
💡 Challenge 9
Write a number guess game which generates numbers from 1 to 6.
🌟 PIP In Python
PIP is a tool that helps you add new features to Python by downloading and installing additional
libraries (packages) from the internet. Think of it like an app store for Python libraries.
import qrcode
img = qrcode.make('Bishworaj Poudel')
type(img) # qrcode.image.pil.PilImage
img.save("bishworaj.png")
Run this program and you will see the qr code image.
Master Python By Bishworaj Poudel
💡 Challenge 10
Create a QR code that stores URLs. https://technologychannel.org/
🌟 Condition In Python
Conditions allow you to execute certain pieces of code based on whether a condition is true or
false. In python this is often done using if, elif, and else statements. Here is the rule on how to
write conditions:
if condition:
# code to execute if condition is true
elif another_condition:
# code to execute if another_condition is true
else:
# code to execute if none of the above conditions are true
Master Python By Bishworaj Poudel
grade = 'D'
else:
grade = 'F'
💡 Points To Remember
- Use if to start a conditional statement.
- Use elif (short for "else if") to add additional conditions.
- Use else to specify what to do if none of the previous conditions are met.
💡 Challenge 11
Write a program that checks if a number is even or odd.
🌟 Assert In Python
The assert keyword checks if something is true, and if not, it stops the program and shows an
error message. Imagine you are building an online store and you want to make sure the price of
an item is never negative. You can use assert to check this:
price = -5
assert price >= 0, "Price cannot be negative"
print("After Price Negative")
If the price is negative, the program will stop and show the message "Price cannot be negative."
💡 Challenge 12
Write a program that uses assert to check if a person's age is positive.
Master Python By Bishworaj Poudel
🌟 Loop In Python
In Programming, loops are used to repeat a block of code until certain conditions are not
completed. For, e.g., if you want to print your name 100 times, then rather than typing
print(“your name”) 100 times, you can use a loop.
Syntax:
for element in sequence:
# Code to be executed
Syntax:
while condition:
# Code to be executed
countdown = 10
while countdown > 0:
print(countdown)
countdown -= 1
print("Countdown complete!")
💡 Challenge 13
Write a program that finds the total and average of the following list:
expenses = [889,788,5656,4455,455,45]
break
continue
break
print(f"Checking {book}")
print("Search ended.")
💡 Challenge 14
Write a program that calculates the total and average of the following list of numbers, stopping if
a negative value is encountered (using break), and skipping any zero values (using continue).
🌟List in Python
If you want to store multiple values in the same variable, you can use List. E.g. to store the
names of multiple items, you can use a List. The List is represented by Square Braces[].
🎉 List Features
- Ordered: The items stay in the order you list them. If you write "milk" before "bread," that
order is remembered.
- Changeable: You can update your list. If you decide you want "orange juice" instead of
"milk," you can change it.
- Mixed Items: You can mix different things in a list, like numbers and words.
Change Item of List: If you decide to "call a friend" instead of "read a book":
to_do_list[3] = "call a friend"
Add Item to List: If you remember you need to "water the plants":
to_do_list.append("water the plants")
Delete Item from List: Once you’ve bought groceries, you can remove that task:
to_do_list.remove("water the plants")
Count the Items: To see how many tasks you have left:
tasks_left = len(to_do_list)
first_task = party_tasks[0]
print("First task to do:", first_task)
total_expense = sum(monthly_expenses)
print("New Total Expense:", total_expense)
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)
my_list = [1, 2, 3, 4, 5]
last_item = my_list[-1]
print(last_item) # Output: 5
Master Python By Bishworaj Poudel
💡 Challenge 15
1. Create an empty list of type strings called days. Use the add method to add names of 7
days and print all days.
2. Add your 7 friend names to the list. Use where to find a name that starts with the
alphabet a.
🌟Tuple in Python
If you want to store multiple values in the same variable but don't want them to change, you can
use a Tuple. For example, to store a collection of fixed values, you can use a Tuple. The Tuple
is represented by parentheses ().
Here, we have created a tuple named coordinate. It contains 2 items, representing the X and Y
coordinates.
🎉 Tuple Features
- Ordered: Just like lists, the items in a tuple maintain the order you put them in.
- Unchangeable: Once you create a tuple, you cannot change it. This makes tuples
useful for storing values that should not be modified.
- Mixed Items: You can store different types of data, like numbers and strings, together in
a tuple.
Unchangeable Nature: If you try to change an item in a tuple, Python will raise an error:
colors[0] = "yellow" # Error
Tuple with Mixed Items: You can mix numbers, strings, and other types.
person = ("Alice", 30, "Engineer")
You can find out how many items are in a tuple using the len() function.
💡 Challenge 16
1. Create a tuple of your favorite fruits and display all the fruits.
2. Access and print the first and last fruit in the tuple.
3. Attempt to change the second fruit in the tuple and observe what happens (this should
raise an error since tuples are unchangeable).
4. Combine this tuple with another tuple of your favorite vegetables, and print the resulting
combined tuple.
5. Find and print the length of the combined tuple using the len() function.
🌟Set In Python
If you want to store multiple unique values in the same variable without worrying about the order
or duplicates, you can use a Set. For example, to store a collection of unique items, you can
use a Set. The Set is represented by curly braces {}.
🎉 Set Features
- Unordered: The items in a set do not have a defined order. Even if you print the set
multiple times, the order of items might change.
- Unchangeable Items: Once you add an item to a set, you cannot change it, but you can
add or remove entire items.
Master Python By Bishworaj Poudel
- Unique Items: Sets do not allow duplicate items. If you try to add an item that already
exists in the set, it will be ignored.
Check for Item in Set: Want to see if an item exists in your set?
is_in_set = "banana" in fruits # True
Add Item to Set: You can add a new item to the set.
fruits.add("orange")
Remove Item from Set: You can remove an item from the set.
fruits.remove("banana")
Set with Mixed Items: You can store different types of data together in a set.
mixed_set = {1, "apple", 3.14}
# Courses in sets
common_students = course_A_students.intersection(course_B_students)
print(common_students)
💡 Challenge 16
Create a set of your favorite hobbies. Add a few more hobbies to the set, then remove one.
Finally, perform a union with another set of hobbies and find the common ones using
intersection.
🌟Dictionary In Python
If you want to store data in key-value pairs, you can use a Dictionary. For example, to store a
collection of related data like a person's name and age, you can use a Dictionary. The
Dictionary is represented by curly braces {} with keys and values separated by a colon :.
Here, we have created a dictionary named person. It contains three key-value pairs: "name":
"Alice", "age": 25, and "city": "New York".
🎉 Dictionary Features
- Unordered: The items in a dictionary are stored without any specific order. The order of
items may vary.
- Changeable: You can change, add, or remove key-value pairs in a dictionary after it is
created.
- Key-Value Pairs: Each item in a dictionary consists of a key and a corresponding value.
Access a Value by Key: Want to see the value associated with a specific key?
car_model = car["model"] # "Corolla"
Master Python By Bishworaj Poudel
Change a Value: If you want to update a value, simply use the key.
car["year"] = 2025
Add a New Key-Value Pair: You can easily add a new key-value pair to the dictionary.
car["color"] = "blue"
Remove a Key-Value Pair: You can remove a key-value pair from the dictionary.
car.pop("model")
💡 Challenge 16
Master Python By Bishworaj Poudel
Create a dictionary of your favorite movies and their release years. Add a new movie to the
dictionary, update the release year of one of the movies, and then remove a movie.
Syntax
[expression for item in iterable if condition]
Explanation
- The list comprehension [x**2 for x in range(1, 6)] generates a list of squares
for each number in the range from 1 to 5.
- The resulting list is [1, 4, 9, 16, 25].
Syntax
{key_expression: value_expression for item in iterable if condition}
Explanation
- The dictionary comprehension {x: x**2 for x in range(1, 6)} creates a
dictionary where each number is a key, and its square is the value.
- The resulting dictionary is {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}.
💡 Challenge 19
1. Write a program that takes a list of numbers and creates a new list containing the
squares of all even numbers from the original list.
2. Write a program that takes a dictionary of student names and their grades, and creates a
new dictionary containing only the students who passed the exam (grade 50 or above).
Master Python By Bishworaj Poudel
🌟ATM Project
This program simulates a simple ATM where a user can check their balance, deposit money, or
withdraw money. The user should be able to:
while True:
print("\nPlease select an option:")
print("1. Check Balance")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Exit")
if choice == 1:
print(f"Your current balance is: ${balance:.2f}")
elif choice == 2:
deposit_amount = float(input("Enter amount to deposit: $"))
if deposit_amount > 0:
balance += deposit_amount
print(f"Successfully deposited ${deposit_amount:.2f}. Your
new balance is ${balance:.2f}.")
else:
print("Deposit amount must be positive.")
elif choice == 3:
withdrawal_amount = float(input("Enter amount to withdraw:
Master Python By Bishworaj Poudel
$"))
if withdrawal_amount > balance:
print("Insufficient funds. Please try a smaller
amount.")
elif withdrawal_amount <= 0:
print("Withdrawal amount must be positive.")
else:
balance -= withdrawal_amount
print(f"Successfully withdrew ${withdrawal_amount:.2f}.
Your new balance is ${balance:.2f}.")
elif choice == 4:
print("Thank you for using Simple Bank ATM. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
🌟Function In Python
Functions are the block of code that performs a specific task. They are created when some
statements are repeatedly occurring in the program. The function helps reusability of the code in
the program. The main objective of the function is DRY(Don’t Repeat Yourself).
Function Advantages
Function takes input (called parameters), processes it, and returns an output.
# Calling function
greet("Hari")
greet("Mark")
greet("John")
Explanation
- Here, greet is the function name, and name is the parameter.
- greet(“Hari”) is calling a function. Once you've defined a function, you can call it to
use it.
🌟Function Types
● No Parameter And No Return Type
● Parameter And No Return Type
● No Parameter And Return Type
● Parameter And Return Type
# Calling function
greet()
Master Python By Bishworaj Poudel
- In this example, greet() is a function that doesn't take any parameters. When
you call greet(), it simply prints the message "Hello, How are you!" to
the screen.
- Notice that when calling greet(), no arguments are passed because the
function does not expect any.
greeting_message = get_greeting()
# Given number
number = 16
ceiled_value = math.ceil(float_number)
print(f"The ceiling of {float_number} is: {ceiled_value}")
💡 Challenge 21
Master Python By Bishworaj Poudel
🌟OOP In Python
Object-oriented programming (OOP) is a popular technique to solve programming problems
by creating objects. It is one of the most popular programming paradigms and is used in many
programming languages, such as Python, Java, C++, etc..
🎇OOP Advantages
● It is easy to understand and use.
● It increases reusability and decreases complexity.
● The productivity of programmers increases.
● It makes the code easier to maintain, modify and debug.
● It promotes teamwork and collaboration.
● It reduces the repetition of code.
Class Syntax:
# create a class
class Classname:
pass
Master Python By Bishworaj Poudel
As mentioned earlier, you need to create a class first before you can create objects from it. Each
class has attributes and methods.
class Student:
def get_details(self):
return f"Name: {self.name}, Age: {self.age}, Grade:
{self.grade}"
def is_passing(self):
# Method: Checks if the student is passing
return self.grade >= 60
You always need to use self as the first argument in a class method. It represents the
object that calls the method.
🌟Object
An object in programming is like a real-world thing or entity that you can work with in
your code. For example, a student object might have attributes like name, age, or
grade. It might have methods like checking if a student is passing which are the actions
the object can perform.
In this example, you’ll see how to create and interact with Student objects. After defining
the Student class with attributes like name, age, and grade, and methods such as
get_details() and is_passing(), you can create your own student objects.
class Student:
def get_details(self):
return f"Name: {self.name}, Age: {self.age}, Grade:
{self.grade}"
def is_passing(self):
# Method: Checks if the student is passing
return self.grade >= 60
By creating these objects, you can easily manage and work with individual student data.
This example shows how you can access the details of each student and determine if
they are passing their course.
Master Python By Bishworaj Poudel
💡 Challenge 22
Write a Python program to create a class Laptop with the properties id, name, and ram. Then,
create three objects of this class and print all their details.
🌟 Inheritance In Python
Inheritance is one of the core concepts of object-oriented programming (OOP) in Python. It
allows a class to inherit attributes and methods from another class, promoting code reusability
and making it easier to maintain and extend.
🎇Inheritance Advantages
● Code Reusability: Inheritance allows you to reuse existing code without
rewriting it.
● Improved Maintainability: Changes made to a base class automatically reflect
in all derived classes.
● Logical Representation: Inheritance models real-world relationships, making
the code more logical and easier to understand.
● Extensibility: You can add new features to a class without modifying its existing
code.
Syntax
# Base class
class ParentClass:
def method_in_parent(self):
Master Python By Bishworaj Poudel
# Derived class
class ChildClass(ParentClass):
def method_in_child(self):
print("This is a method in the child class")
# Example usage
child = ChildClass()
child.method_in_parent() # Inherited from ParentClass
child.method_in_child() # Defined in ChildClass
# Base class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def get_details(self):
return f"Name: {self.name}, Age: {self.age}"
# Derived class
class Student(Person):
def __init__(self, name, age, grade):
# Call the constructor of the base class
super().__init__(name, age)
self.grade = grade
def is_passing(self):
Master Python By Bishworaj Poudel
Now, let's create objects using the Student class and see how inheritance works.
🌟 Method Overriding
Inheritance also allows method overriding, where a method in a derived class has the
same name as a method in the base class. The derived class's method overrides the
base class's method.
# Base class
class Animal:
def sound(self):
return "Some generic sound"
# Derived class
class Dog(Animal):
def sound(self):
return "Bark"
Master Python By Bishworaj Poudel
# Derived class
class Cat(Animal):
def sound(self):
return "Meow"
Let's see how method overriding works with objects of Dog and Cat classes.
💡 Challenge 23
Write a Python program to create a class Vehicle with properties make and model. Then,
create a derived class Car with an additional property year. Create objects of both classes and
print all their details.
class BankAccount:
def __init__(self, name, phone, balance=0.0):
self.name = name
self.phone = phone
self.balance = balance
Master Python By Bishworaj Poudel
def get_balance(self):
return f"{self.name}'s current balance: ${self.balance:.2f}"
# Demonstrate functionality
account1.deposit(200)
print(account1.get_balance())
account1.withdraw(100)
print(account1.get_balance())
account2.deposit(300)
print(account2.get_balance())
account2.withdraw(500)
print(account2.get_balance())
Master Python By Bishworaj Poudel
🌟 GUI In Python
A Graphical User Interface (GUI) is a type of user interface that allows users to interact with a
software application visually. In a GUI, elements such as buttons, text fields, images, and
windows provide intuitive ways for users to interact with the application. Instead of typing
commands, users can simply click, drag, and drop using a mouse or touch input. Here are some
examples of GUI Elements:
- Buttons
- Labels
- Text Fields
Python offers several libraries for building GUIs, allowing developers to create desktop
applications with interactive components. Here are popular libraries for building GUI In Python.
Learning Tkinter is a great way to get hands-on with GUI applications in Python. Let’s learn it.
root.mainloop()
import tkinter as tk
def greet():
label.config(text="Hello, Welcome to Tkinter!")
# Add a label
label = tk.Label(root, text="Click the button to get greeted",
font=("Arial", 14))
label.pack(pady=20)
# Add a button
button = tk.Button(root, text="Greet Me", command=greet)
button.pack(pady=10)
root.geometry("400x300")
root.mainloop()
🎉 Example 3: Calculator
This code creates a simple addition application using the tkinter library. It allows users to enter
two numbers, click a button to calculate the sum, and display the result in a message box.
import tkinter as tk
Master Python By Bishworaj Poudel
# Create window
root = tk.Tk()
root.title("Addition App")
# Input fields
entry1 = tk.Entry(root)
entry1.pack(pady=5)
entry2 = tk.Entry(root)
entry2.pack(pady=5)
# Start app
root.geometry("200x150")
root.mainloop()
This code creates a simple to-do list using tkinter. Users can add tasks by typing in an entry box
and clicking "Add Task." They can also delete tasks from the list by selecting an item and
clicking "Delete Task."
import tkinter as tk
def add_task():
task = entry.get()
if task != "":
listbox.insert(tk.END, task)
entry.delete(0, tk.END)
def delete_task():
listbox.delete(tk.ANCHOR)
# Add widgets
entry = tk.Entry(root, width=30)
entry.pack(pady=10)
💡 Challenge 25
1. Create a GUI application that finds simple interest. Simple Interest (SI) = (P * R * T) /
100
Where:
● P = Principal amount
● R = Rate of interest
● T = Time period
Python makes file handling easy with built-in functions and methods that help you work with
different types of files, such as text files (.txt), binary files (.bin), or CSV files (.csv).
try:
# Code that might raise an exception
risky_code()
except SomeSpecificException:
Master Python By Bishworaj Poudel
💡 Challenge 26
Create a Python program that asks the user to input a number. The program should then
determine if the number is odd or even and display the result. If the user enters a non-numeric
value, handle the exception and prompt the user to enter a valid number.
Python makes file handling easy with built-in functions and methods that help you work with
different types of files, such as text files (.txt), binary files (.bin), or CSV files (.csv).
# Directory name
directory = "new_folder"
# Create directory
try:
os.mkdir(directory)
print(f"Directory '{directory}' created successfully!")
except FileExistsError:
print(f"Directory '{directory}' already exists.")
In this example, the os.rmdir() function deletes the directory named new_folder.
import os
# Directory name
directory = "new_folder"
# Remove directory
try:
os.rmdir(directory)
print(f"Directory '{directory}' deleted successfully!")
except FileNotFoundError:
print(f"Directory '{directory}' does not exist.")
except OSError:
print(f"Directory '{directory}' is not empty. Unable to delete.")
💡 Challenge 27
Create a Python program that reads a file containing a list of numbers (one number per line)
and writes the sum of those numbers to another file called sum.txt.
🌟 Datetime In Python
Python's datetime module helps you work with dates and times, making it simple to create,
manipulate, and format dates. Whether you want to get the current date, calculate time
differences, or convert strings into date objects, datetime has got you covered.
Master Python By Bishworaj Poudel
import datetime
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
Sometimes you might want to pause your program for a certain period. You can use time.sleep()
to do this. It pauses the execution for the specified number of seconds.
import time
# Print a message
print("This message will be followed by a 3-second pause...")
💡 Challenge 28
Create a Python program that asks the user for their birthdate (in YYYY-MM-DD format) and
calculates their age.