Basic Python Programming
Basic Python Programming
, programming
languages, tools, etc.)
Python syntax refers to the set of rules that governs the structure of a program. It's the grammar of the
language, dictating how to write code that the Python interpreter can understand and execute.
Indentation
One of the most distinctive features of Python syntax is its use of indentation to define code blocks. Unlike
many other programming languages that use curly braces {} to group statements, Python uses whitespace.
The number of spaces or tabs must be consistent within a single block. A standard is to use four spaces for
each level of indentation.
Correct:
Python
if True:
print("This code is inside the if block.")
Incorrect (IndentationError):
Python
if True:
print("This code is inside the if block.")
print("This will cause an error.")
Comments
Comments are lines of text within a program that are ignored by the Python interpreter. They are used to
explain the code and make it more readable for humans.
Python
Multi-line comments can be created by using three single or double quotes ''' or """. This is often
called a docstring when used at the beginning of a function, class, or module.
Python
"""
This is a multi-line comment.
It can span across multiple lines.
"""
Keywords
Keywords are reserved words in Python that have a specific meaning and cannot be used as variable
names. Examples include if, else, for, while, def, class, import, and True, False, None.
Statements
A statement is a single logical instruction that Python can execute. Examples include variable assignments,
function calls, and control flow structures. Each statement is typically written on a new line.
A variable is a named location in memory used to store data. In Python, you create a variable the moment
you first assign a value to it. Python is dynamically typed, meaning you do not need to declare a variable's
type before using it. The type is inferred from the value it holds.
Naming Rules
Variable names must start with a letter (a-z, A-Z) or an underscore (_).
The rest of the name can contain letters, numbers (0-9), and underscores.
Names are case-sensitive (my_variable is different from My_Variable).
Variable names should be descriptive and follow PEP 8, the official Python style guide. For example,
snake_case (lowercase with underscores) is the convention for variable and function names.
Assignment
Python
my_age = 30 # Assigns the integer 30 to the variable my_age.
name = "Alice" # Assigns the string "Alice" to the variable name.
A data type classifies the kind of values a variable can hold. Understanding data types is crucial because
they determine what operations can be performed on the data. Python has several built-in data types, but
the most fundamental are integers, floats, strings, and booleans.
1. Integers (int)
An integer is a whole number, positive or negative, without a decimal point. Integers in Python have
arbitrary precision, meaning they can be as large as your system's memory allows.
Creation:
Python
age = 25
year = -2023
large_number = 99999999999999999999
Operations: You can perform standard arithmetic operations like addition (+), subtraction (-),
multiplication (*), and division (/). The result of int division is a float. For integer division (where the
result is an integer, discarding the remainder), use //.
Python
result_add = 10 + 5 # 15
result_div = 10 / 3 # 3.3333... (float)
result_int_div = 10 // 3 # 3
A float (or floating-point number) is a number with a decimal point. Floats are used to represent real
numbers and are often used for calculations involving fractions or precise measurements.
Creation:
Python
pi = 3.14159
temperature = 25.5
Operations: Standard arithmetic operations apply. Be aware that floating-point arithmetic can
sometimes have precision issues due to how computers store these numbers.
Python
3. Strings (str)
A string is an ordered sequence of characters, used to store text. Strings are immutable, meaning once a
string is created, its contents cannot be changed.
Creation: Strings are created by enclosing text in single quotes ('...'), double quotes ("..."), or triple
quotes ('''...''' or """..."""). Using triple quotes allows for multi-line strings.
Python
Operations:
o Concatenation: Joining strings using the + operator.
Python
Python
Python
o Methods: Strings have many built-in methods for manipulation, such as upper(), lower(), strip(),
split(), and replace().
Python
4. Booleans (bool)
A boolean is a data type that can only have one of two values: True or False. Booleans are fundamental for
conditional logic and control flow.
Creation:
Python
is_sunny = True
is_raining = False
Operations: Booleans are used in comparison operators (==, !=, <, >, <=, >=) and logical operators
(and, or, not).
Python
# Comparison
is_equal = (5 == 5) # True
is_not_equal = (5 != 10) # True
# Logical
is_valid = is_sunny and not is_raining # True
Boolean values are also the result of many conditional statements and expressions. They are at the heart
of if statements and while loops, determining the flow of a program.
Input/output operations
Input/Output (I/O) operations are a fundamental part of almost every programming language, including
Python. They are the processes by which a program communicates with the outside world.
Input is the process of a program receiving data from an external source, such as a user, a file, or
another program.
Output is the process of a program sending data to an external destination, such as the screen
(console), a file, or a network.
Python provides built-in functions and methods to handle these operations efficiently.
The most common I/O operations involve the standard streams: standard input (stdin), standard output
(stdout), and standard error (stderr).
Standard Input (stdin): The source from which a program reads input. By default, this is the
keyboard.
Standard Output (stdout): The destination to which a program writes its output. By default, this is
the console or terminal.
Standard Error (stderr): The destination to which a program writes error messages. By default, this
is also the console.
The print() function is the most common way to display output on the console. It's a versatile function that
can output text, numbers, variables, and the results of expressions.
Basic Usage: The simplest form of print() takes one or more arguments and prints them to the console,
followed by a newline.
Python
print("Hello, world!")
print(123)
Multiple Arguments: You can pass multiple arguments to print(), separated by commas. The function will
convert each argument to a string and separate them with a space by default.
Python
name = "Alice"
age = 30
print("My name is", name, "and my age is", age)
# Output: My name is Alice and my age is 30
Customizing Output: The print() function has two optional keyword arguments that offer powerful
customization:
sep (separator): Specifies the string to use between arguments. The default is a single space ' '.
end: Specifies the string to append at the end of the output. The default is a newline character '\n'.
Python
# Using `sep` to change the separator
print("Python", "is", "awesome", sep="-")
# Output: Python-is-awesome
Formatting Output: For more control over string formatting, especially when combining variables with
text, you can use:
f-strings (Formatted String Literals): Introduced in Python 3.6, f-strings are the modern and most
readable way to format strings. You prefix a string with f and embed expressions inside curly braces
{}.
Python
item = "apple"
price = 1.25
print(f"The cost of an {item} is ${price:.2f}.")
# Output: The cost of an apple is $1.25.
The :.2f is a format specifier that rounds the float to two decimal places.
.format() method: An older but still widely used method. It uses curly braces as placeholders, which
are then filled by arguments passed to the .format() method.
Python
The input() function is used to read a line of text from the standard input (the keyboard). It pauses the
program's execution until the user types something and presses Enter.
Basic Usage: The function takes a single optional argument, which is a prompt displayed to the user before
they enter their input. The value returned by input() is always a string, regardless of what the user types.
Python
# Simple input
user_input = input("Please enter your name: ")
print("Hello,", user_input)
Handling Different Data Types: Since input() always returns a string, you must explicitly convert the input
to the desired data type if you need to perform numerical operations. You can use type casting functions
like int() or float().
Python
# Getting a number from the user
age_str = input("Please enter your age: ")
age_int = int(age_str)
The try...except block is a crucial way to handle potential ValueError exceptions that can occur if the user
provides input that cannot be converted to an integer.
Beyond the console, a program often needs to read from or write to files. This is essential for tasks like
data persistence, configuration management, and processing large datasets.
To perform any file operation, you must first open the file using the built-in open() function. This function
returns a file object, which is used to interact with the file.
'r' (read): Default mode. Opens a file for reading. The file must exist.
'w' (write): Opens a file for writing. Creates a new file if it doesn't exist, or overwrites the contents if
it does.
'a' (append): Opens a file for writing, but appends new data to the end of the file instead of
overwriting.
'r+': Opens a file for both reading and writing.
't' (text): Default mode. Opens the file in text mode.
'b' (binary): Opens the file in binary mode.
It is crucial to close a file after you are done with it to free up system resources and ensure all data is
written to the disk. You use the .close() method on the file object.
Python
# Open a file for writing
file_writer = open('my_notes.txt', 'w')
file_writer.write("This is my first line.\n")
file_writer.close()
The with Statement: The Best Practice
Manually closing files can be error-prone, especially if an error occurs before the .close() call. The with
statement is the recommended way to handle file I/O because it automatically ensures the file is closed,
even if an exception occurs.
Python
with open('my_notes.txt', 'w') as file_writer:
file_writer.write("This is a new line.\n")
file_writer.write("This will overwrite the old content.\n")
# The file is automatically closed here
Once a file is open for reading ('r'), you can use various methods to read its content:
.read(): Reads the entire file content into a single string. This can be inefficient for very large files.
Python
Python
Python
Iterating over the file object: This is the most memory-efficient way to read a file line-by-line,
especially for large files.
Python
Writing to Files
When a file is opened for writing ('w'), you use the .write() method to write a string to the file.
Python
with open('shopping_list.txt', 'w') as file_writer:
file_writer.write("Milk\n")
file_writer.write("Eggs\n")
file_writer.write("Bread\n")
If you use the 'a' (append) mode, the new content will be added to the end of the file.
Python
with open('shopping_list.txt', 'a') as file_writer:
file_writer.write("Cheese\n")
The combination of standard I/O (console) and file I/O operations gives a Python program the capability to
interact with users and manage data in a persistent and scalable manner.
Type casting and basic operators
Type casting, also known as type conversion, is the process of changing the data type of a variable from one
type to another. It's a fundamental operation in Python because different data types support different
operations. For example, you can't perform mathematical calculations on a string, and you can't join a
number to a string without converting it first.
Python is a dynamically typed language, meaning you don't declare a variable's type when you create it; the
interpreter infers it. However, you often need to manually convert types to perform specific tasks.
Consider a program that takes user input. The input() function always returns a string. If you want to use
the input in a numerical calculation, you must convert it to an integer or a float.
Python
user_age_str = input("Enter your age: ")
# The variable user_age_str is a string, e.g., '25'
Python provides built-in functions for converting between common data types.
Python
int('100') # 100
int(3.14) # 3
int(True) # 1
⚠️Note: int() will raise a ValueError if the string doesn't represent a valid integer (e.g.,
int('hello')).
Python
float('99.5') # 99.5
float(50) # 50.0
float(False) # 0.0
str(123) # '123'
str(4.56) # '4.56'
Python
item_count = 5
message = "We have " + str(item_count) + " items left."
print(message)
# Output: We have 5 items left.
Python
bool(0) # False
bool(10) # True
bool('') # False
bool('hello') # True
Operators are special symbols that perform operations on values and variables. The values an operator
works on are called operands. Python supports a wide range of operators, which can be categorized into
groups.
1. Arithmetic Operators
2. Assignment Operators
These are used to compare two values and return a boolean result (True or False).
4. Logical Operators
These are used to combine conditional statements and evaluate their logical relationship.
Python
Python
Python
Identity Operators (is, is not): Compare the memory location of two objects. They check if the
operands are the exact same object.
Python
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is y) # False (different objects in memory)
print(x is z) # True (z refers to the same object as x)
Membership Operators (in, not in): Test if a sequence (like a string, list, or tuple) contains a
specific value.
Python
Understanding how to use these operators and perform type casting is essential for writing effective and
functional Python programs.
2. Control Structures
Conditional Statements: The if, elif, and else
Conditional statements are a core part of programming logic. They allow a program to make decisions and
execute different blocks of code based on whether a certain condition is True or False. This is how
programs can respond dynamically to different inputs and states.
The if Statement
The if statement is the most basic conditional. It executes a block of code only if the condition is True.
Syntax:
Python
if condition:
# code to be executed if the condition is True
Explanation:
o condition: This is a boolean expression that evaluates to either True or False.
o A colon : marks the end of the if statement.
oThe code block to be executed is indented. Indentation is mandatory in Python to define the
scope of the code.
Example:
Python
age = 20
if age >= 18:
print("You are an adult.")
Since the condition age >= 18 is True, the print statement is executed.
The else statement is used to execute a block of code when the if condition is False. It provides an
alternative path for the program to follow.
Syntax:
Python
if condition:
# code if condition is True
else:
# code if condition is False
Example:
Python
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
In this case, age >= 18 is False, so the code under the else block is executed.
The elif Statement
The elif statement (short for "else if") allows you to check multiple conditions sequentially. Python checks
the conditions from top to bottom, and the first one that evaluates to True has its corresponding code block
executed. The rest are skipped.
Syntax:
Python
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True
elif condition3:
# code if condition3 is True
else:
# code if none of the above are True
An if...elif...else block can have as many elif statements as needed, and the else block is
optional.
Example:
Python
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
The program first checks if score >= 90 (False). Then it checks score >= 80 (True), so it prints
"Grade: B" and skips the remaining checks.
A response of 6000 words is not necessary to explain control structures in Python. Here is a comprehensive
and detailed explanation of conditional statements, looping structures, and loop control statements,
presented concisely.
Loops are used to execute a block of code repeatedly. They are essential for tasks like iterating over a list of
items, performing calculations a specific number of times, or reading data from a file line by line.
The for loop is used to iterate over a sequence (like a list, tuple, string, or range) or any other iterable
object. It executes the code block for each item in the sequence.
Syntax:
Python
Explanation:
o item: A temporary variable that holds the current item from the sequence during each
iteration.
o sequence: The iterable object you want to loop over.
Examples:
o Iterating over a list:
Python
Python
The range() function can also take a start and a step. range(start, stop, step).
The while loop executes a block of code as long as a specified condition is True. The condition is checked
at the beginning of each iteration.
Syntax:
Python
while condition:
# code to be executed as long as the condition is True
Explanation:
o The loop continues indefinitely until the condition becomes False.
o You must ensure that the condition will eventually become False to avoid an infinite loop.
This is typically done by modifying a variable inside the loop.
Example:
Python
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # This line is crucial to eventually make the condition False
The loop will run five times (for count 0, 1, 2, 3, 4), and then stop.
Loop control statements change the execution flow of a loop from its normal sequence. They give you
more granular control over when to exit a loop or skip an iteration.
break
The break statement is used to exit a loop prematurely. When break is encountered, the program
immediately jumps to the code that follows the loop, completely ignoring any remaining iterations.
Usage: break is often used within an if statement to stop a loop when a specific condition is met.
Example:
Python
continue
The continue statement is used to skip the current iteration of the loop and move on to the next one.
When continue is encountered, the rest of the code in the current iteration is skipped, and the loop
continues with the next item or condition check.
Usage: continue is useful for filtering or skipping unwanted items during an iteration.
Example:
Python
pass
The pass statement is a placeholder statement that does nothing. It's a null operation. It's used when the
syntax requires a statement but you don't want to execute any code.
Usage: pass is often used when defining an empty function, class, or loop to avoid a SyntaxError.
Example:
Python
Python
The pass statement keeps the program syntactically correct, allowing you to fill in the code later.
3. Data Structures in Python
Lists, Tuples, Sets, and Dictionaries
Indexing, slicing, and built-in functions
Nested data structures
In Python, a data structure is a way of organizing and storing data so it can be accessed and modified
efficiently. They are a fundamental building block of programming, allowing you to handle collections of
data in a structured manner. The four most common built-in data structures are Lists, Tuples, Sets, and
Dictionaries.
1. Lists
A list is an ordered, mutable collection of items. "Ordered" means the items have a defined position or
index, and "mutable" means you can change the list after it's created (add, remove, or modify elements).
Lists can contain items of different data types.
Creation
Lists are created using square brackets [] with items separated by commas.
Python
my_list = [1, 2, 3, "apple", True]
Indexing: Access a single item by its position (index). Indexes start at 0 for the first item. Negative
indexes count from the end (-1 is the last item).
Python
Slicing: Extract a portion of the list. The syntax is [start:stop:step]. The slice includes the item
at start but excludes the item at stop.
Python
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # Output: [2, 3, 4]
print(numbers[:3]) # Output: [0, 1, 2] (from beginning)
print(numbers[7:]) # Output: [7, 8, 9] (to end)
print(numbers[::2]) # Output: [0, 2, 4, 6, 8] (every second item)
2. Tuples
A tuple is an ordered, immutable collection of items. "Immutable" means you cannot change, add, or
remove items after the tuple is created. This makes tuples faster than lists and useful for storing data that
should not change.
Creation
Python
my_tuple = (1, "hello", 3.14)
Python
coordinates = (10, 20, 30, 40)
print(coordinates[1]) # Output: 20
print(coordinates[1:3]) # Output: (20, 30)
However, since tuples are immutable, you cannot assign a new value to an index (e.g., coordinates[0] =
5 would cause an error).
Built-in Functions
Tuples have fewer built-in methods than lists because they are immutable.
3. Sets
A set is an unordered, mutable collection of unique items. "Unordered" means items have no defined index,
so you cannot access them using a number. "Unique" means duplicate values are automatically removed.
Sets are highly efficient for membership testing.
Creation
Operations
Sets do not support indexing or slicing. They are used for mathematical set operations.
4. Dictionaries
A dictionary is an unordered, mutable collection of key-value pairs. Each item has a unique key, and the
key is used to access its associated value. Dictionaries are optimized for retrieving values based on their
keys.
Creation
Dictionaries are created using curly braces {} with key-value pairs separated by colons :.
Python
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
Keys must be unique and immutable (e.g., strings, numbers, or tuples). Values can be of any data type.
Accessing: Use the key inside square brackets [] to get the value.
Python
Python
person["age"] = 31
person["email"] = "[email protected]" # Adds a new key-value pair
Python
del person["city"]
Data structures can be nested, meaning they can contain other data structures as elements. This allows for
the creation of complex and powerful structures.
Examples
Python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0][1]) # Output: 2
Python
students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 22}
]
print(students[0]["name"]) # Output: Alice
Dictionary of Dictionaries:
Python
database = {
"user1": {"name": "Alice", "status": "active"},
"user2": {"name": "Bob", "status": "inactive"}
}
print(database["user1"]["status"]) # Output: active
Nested structures require careful indexing to access the correct data. The key is to chain the indexing
operations, moving from the outer structure inward.
Indexing in Python
Indexing is the process of accessing a single element from a sequence (like a string, list, or tuple) by its
position. Every element in an ordered sequence is assigned a unique index, which is an integer value.
Positive Indexing: Python uses zero-based indexing, meaning the first element is at index 0, the
second at 1, and so on. This is the most common way to access elements.
Python
Negative Indexing: Python also supports negative indexing, which is a convenient way to access
elements from the end of the sequence. The last element is at index -1, the second-to-last at -2, and
so on.
Python
my_string = "Python"
print(my_string[-1]) # Output: n
print(my_string[-3]) # Output: h
IndexError: If you try to access an index that is outside the bounds of the sequence, Python will
raise an IndexError.
Python
my_list = [1, 2, 3]
# This will cause an IndexError
# print(my_list[3])
Slicing in Python
Slicing is the process of extracting a subsequence (a portion) from a sequence. Instead of a single element,
slicing returns a new sequence containing a range of elements.
Slicing Syntax
start: The starting index of the slice (inclusive). If omitted, it defaults to the beginning of the
sequence (0).
stop: The ending index of the slice (exclusive). The element at this index is not included. If omitted,
it defaults to the end of the sequence.
step: The number of items to skip between each element. If omitted, it defaults to 1.
Examples of Slicing
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[2:5]) # Output: [2, 3, 4]
Python
Python
my_string = "abcdefghi"
print(my_string[1:8:2]) # From index 1 to 8, in steps of 2. Output: bdfh
print(my_string[::3]) # From start to end, in steps of 3. Output: adg
Python
my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list) # Output: [5, 4, 3, 2, 1]
Built-in Functions
Python provides a rich set of built-in functions that perform common tasks. These functions are always
available and don't require any special import. They are a crucial part of the language and are often used to
inspect and manipulate data structures.
len(): Returns the number of items in an object. It works on all sequence types (strings, lists, tuples)
as well as sets and dictionaries.
Python
my_string = "Hello"
print(len(my_string)) # Output: 5
type(): Returns the type of an object. This is useful for debugging and understanding the data you
are working with.
Python
a = 10
b = 3.14
c = "Python"
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'str'>
print(): The most common built-in function, used to display output to the console.
min() and max(): Return the smallest and largest items in an iterable.
Python
Python
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
sorted(): Returns a new, sorted list from the items in an iterable. Unlike the .sort() method,
sorted() does not modify the original list.
Python
unsorted_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(unsorted_list)
print(sorted_list) # Output: [1, 1, 3, 4, 5, 9]
print(unsorted_list) # The original list is unchanged.
list(), tuple(), set(), dict(): These are not just constructors for creating new data structures;
they can also be used to convert an object from one type to another.
Python
my_string = "Python"
my_list = list(my_string) # Converts the string to a list of characters
print(my_list) # Output: ['P', 'y', 't', 'h', 'o', 'n']
my_tuple = tuple(my_list)
print(my_tuple) # Output: ('P', 'y', 't', 'h', 'o', 'n')
Functions in Python
A function is a block of reusable code that performs a specific task. Functions allow you to break down a
large program into smaller, manageable, and organized parts, which promotes code reuse, readability, and
maintainability.
To define a function, you use the def keyword, followed by the function name, parentheses (), and a colon
:. The code block for the function must be indented. To execute the function, you call it by its name
followed by parentheses.
Python
# Function definition
def greet():
print("Hello, welcome to the program!")
# Function call
greet() # Output: Hello, welcome to the program!
Functions can be made more flexible by using arguments to pass data into them and return values to send
data back out.
Arguments (Parameters)
Arguments are values passed into a function when it is called. The function's definition specifies
parameters, which are the variables that receive these values.
Python
# The 'name' and 'age' are parameters
def greet_person(name, age):
print(f"Hello, {name}! You are {age} years old.")
Python
greet_person(age=30, name="Alice") # Same output
Default Arguments: You can provide a default value for a parameter. If the argument is not
provided in the function call, the default value is used.
Python
Return Values
A function can send data back to the calling code using the return keyword. This allows the result of a
function to be stored in a variable or used in an expression. A function that does not have a return
statement implicitly returns None.
Python
def add_numbers(x, y):
result = x + y
return result
sum_of_numbers = add_numbers(10, 5)
print(sum_of_numbers) # Output: 15
You can return multiple values by separating them with commas. Python automatically packs them into a
tuple.
Python
def get_stats(numbers):
total = sum(numbers)
count = len(numbers)
return total, count
Modules in Python
A module is simply a file containing Python code, such as function definitions, class definitions, and
variables. Modules are used to organize code and prevent namespace collisions.
Built-in Modules
Python comes with a vast Standard Library, which is a collection of built-in modules. You can use these
modules to perform a wide range of tasks without installing any extra software.
Python
import math
Python
import random
To use a module, you must first import it. There are several ways to import.
import module_name: Imports the entire module. You must use the module name followed by a dot
. to access its contents.
Python
import math
print(math.sqrt(25))
from module_name import item1, item2: Imports specific items from a module. You can then
use these items directly without the module name prefix.
Python
from module_name import *: Imports all items from a module. This is generally discouraged as it
can lead to namespace clashes and make it difficult to determine where a function came from.
import module_name as alias: Imports a module and gives it a shorter alias. This is common
with popular libraries like NumPy (import numpy as np).
Python
File handling is a crucial aspect of programming that allows your program to interact with the file system. It
enables you to read data from files and write data to files, providing a way for your program to store and
retrieve information persistently.
To work with a file, you must first open it using the built-in open() function. This function returns a file
object, which acts as a channel for communication between your program and the file.
The open() function takes two main arguments: the file path and the mode in which to open the file.
Python
file_object = open("filename.txt", "mode")
Writing to a File
To write data to a file, you open it in write mode ('w') and use the .write() method of the file object. The
.write() method takes a single string as an argument.
Overwriting Content: When you open a file in 'w' mode, if the file already exists, its entire content
is erased, and the new data is written from the beginning. If the file does not exist, a new one is
created.
Python
# Open the file in write mode
file_writer = open("my_notes.txt", "w")
To read data from a file, you open it in read mode ('r') and use methods like .read(), .readline(), or
.readlines().
The .read() method: Reads the entire content of the file into a single string. This can be inefficient
for very large files.
Python
The .readline() method: Reads one line from the file at a time. This is useful when you need to
process a file line by line.
Python
Iterating over the file object: This is the most common and memory-efficient way to read a file line
by line.
Python
The mode argument in the open() function determines what you can do with the file.
Python
File operations can fail for many reasons (e.g., file not found, permission denied). To prevent your program
from crashing, you must handle these exceptions gracefully using try...except blocks.
FileNotFoundError
This error occurs when you try to open a file for reading that does not exist.
Python
try:
with open("non_existent_file.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("Error: The file was not found.")
PermissionError
This error occurs when the program does not have the necessary permissions to read from or write to a file
or directory.
Python
try:
with open("/root/secret.txt", "w") as f: # Assuming insufficient permissions
f.write("Some data.")
except PermissionError:
print("Error: You do not have permission to write to this file.")
The with statement is the most recommended way to handle files. It automatically handles the closing of the
file, even if an exception occurs within the with block. This prevents resource leaks and ensures data is
written to the disk.
Python
try:
with open("my_notes.txt", "r") as file_reader:
content = file_reader.read()
print(content)
except FileNotFoundError:
print("The file could not be found.")
The with statement simplifies file management and makes your code more robust and reliable.
6.Object-Oriented Programming (OOPs)
Classes and Objects
Constructors (__init__ method)
Inheritance and Polymorphism
Encapsulation
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to
organize and structure code. Instead of focusing on functions and logic, OOP models real-world entities by
combining data (attributes) and behaviors (methods) into a single unit. This approach promotes code
reusability, modularity, and maintainability.
Classes
A class is a blueprint or a template for creating objects. It defines the common attributes and methods that
all objects of that type will have. Think of a class as the design for a car: it specifies that all cars will have a
color, a number of wheels, and the ability to drive and brake, but it doesn't represent any specific car.
Python
class Car:
# Attributes
color = "red"
# Method
def start_engine(self):
print("Engine started!")
Objects
An object is an instance of a class. It is a concrete entity created from the class blueprint. Each object has its
own unique set of attribute values. Using the car analogy, an object would be a specific car, such as a "blue
sedan" or a "red sports car."
Creating an object: To create an object, you call the class name followed by parentheses.
Python
Syntax:
Python
class Car:
# The constructor method
def __init__(self, color, brand):
# `self` refers to the instance being created
self.color = color
self.brand = brand
self.is_running = False
def start_engine(self):
self.is_running = True
print(f"The {self.brand} engine started.")
The self keyword is a reference to the instance of the class. It is the first parameter of every instance
method, including the constructor, and allows the method to access and modify the object's
attributes.
Inheritance
Inheritance is a mechanism that allows a new class (the child or subclass) to inherit the attributes and
methods of an existing class (the parent or superclass). This creates a hierarchy and promotes code reuse,
as the child class can use the parent's code without having to rewrite it.
Example: A SportsCar is a type of Car. It inherits all the properties of a Car but can also have its
own unique attributes (e.g., top_speed) and methods (turbo_boost).
Python
def drive(self):
print("Vehicle is driving.")
The super().__init__() call is essential for calling the parent class's constructor to properly
initialize the inherited attributes.
Polymorphism
Polymorphism (meaning "many forms") is the ability of an object to take on many forms. In the context of
inheritance, it allows methods with the same name to be used on objects of different classes, with each
method behaving in a way appropriate for its own class.
Example: If both the parent and child classes have a method with the same name, the method in the
child class will override the one in the parent class.
Python
class Animal:
def make_sound(self):
print("Generic animal sound.")
class Dog(Animal):
def make_sound(self): # Overrides the parent method
print("Woof!")
class Cat(Animal):
def make_sound(self): # Overrides the parent method
print("Meow!")
# The same method call `make_sound()` behaves differently for each object
for animal in animals:
animal.make_sound()
# Output:
# Woof!
# Meow!
# Generic animal sound.
Encapsulation
Encapsulation is the concept of bundling data (attributes) and the methods that operate on that data into a
single unit (a class). It also involves restricting direct access to some of an object's components, which is
known as data hiding.
Why Encapsulate?
o Data Integrity: It prevents outside code from accidentally changing an object's data in an
invalid way.
o Modularity: It makes the class's internal state a "black box," so other parts of the program
don't need to know how it works.
Implementation in Python: Unlike languages like Java or C++, Python does not have strict private
attributes. Instead, it uses a convention of prefixing attribute names with underscores to indicate their
intended privacy.
o Single Underscore (_): A convention for a "protected" attribute. It suggests that the attribute
should not be accessed directly from outside the class, but it is not enforced by the interpreter.
o Double Underscore (__): Triggers name mangling, a mechanism that makes an attribute
harder to access from outside the class. The interpreter renames the attribute to
_ClassName__attributeName. While not truly private, it effectively prevents accidental
modification.
Python
class BankAccount:
def __init__(self, balance):
self.__balance = balance # "Private" attribute due to name mangling
account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # Output: 150
By using methods like get_balance() (a "getter") and deposit() (a "setter"), you control how the internal
data of the object is accessed and modified, which is the essence of encapsulation.
7.Error Handling
Exceptions and try-except blocks
Raising custom errors
Error handling is a crucial aspect of writing robust and reliable programs. It involves anticipating and
managing errors that may occur during program execution, rather than letting the program crash. In Python,
errors that occur during runtime are called exceptions.
An exception is an event that disrupts the normal flow of a program's instructions. When an exception
occurs, Python creates an exception object and "raises" it. If this exception is not handled, the program will
terminate and display an error message (traceback).
The try-except block is the primary mechanism for handling exceptions. It allows you to "try" a block of
code and "catch" any exceptions that are raised.
The try Block: This is where you place the code that might raise an exception.
The except Block: This block is executed only if an exception occurs in the try block. It contains
the code to handle the error gracefully.
Basic Syntax
Python
try:
# Code that might raise an exception
numerator = int(input("Enter a numerator: "))
denominator = int(input("Enter a denominator: "))
result = numerator / denominator
print(f"The result is: {result}")
except ValueError:
# Code to handle a specific exception (e.g., if input is not a number)
print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
# Code to handle another specific exception (e.g., if the denominator is zero)
print("Error: Cannot divide by zero.")
You can have multiple except blocks to handle different types of exceptions. Python checks them in order.
You can also handle multiple exceptions with a single except block by listing them in a tuple.
Python
try:
# Code to try
my_list = [1, 2, 3]
print(my_list[5]) # This will raise an IndexError
except (ValueError, IndexError):
print("An input or index error occurred.")
Python
try:
file = open("my_file.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File was read successfully!")
print(content)
finally:
# This code will always run
if 'file' in locals() and not file.closed:
file.close()
print("File operation complete.")
While Python's built-in exceptions cover many common errors, there are times when you need to create and
raise your own specific exceptions. This is useful for making your code more descriptive and for handling
application-specific errors.
The raise statement allows you to manually trigger an exception. You can raise a built-in exception or a
custom one.
Python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be a negative number.")
elif age > 150:
raise ValueError("Age is unrealistic.")
else:
print("Age is valid.")
try:
check_age(-5)
except ValueError as e:
print(f"Caught an error: {e}")
To create a custom exception, you define a new class that inherits from Python's built-in Exception class
(or one of its subclasses). This allows your custom exception to be handled by try-except blocks just like
built-in exceptions.
Python
# Define a custom exception class
class InvalidEmailError(Exception):
"Raised when an email address is not in a valid format."
pass
def validate_email(email):
if "@" not in email or "." not in email:
raise InvalidEmailError(f"'{email}' is not a valid email address.")
try:
validate_email("[email protected]")
except InvalidEmailError as err:
print(f"Email validation failed: {err}")
By creating a custom InvalidEmailError, you provide more specific and meaningful information about
why an error occurred, which can make debugging and error handling easier for developers using your code.
8.Libraries and Tools
numpy for numerical operations
matplotlib for data visualization
pandas for handling data (optional based on course depth)
In data science and scientific computing, Python's built-in capabilities are often not enough. Libraries
provide specialized tools and functions that extend Python's functionality. NumPy, Matplotlib, and Pandas
are three of the most essential libraries for numerical operations, data visualization, and data handling.
NumPy (Numerical Python) is the foundational library for scientific computing in Python. It provides a
high-performance multidimensional array object, and tools for working with these arrays. The core of
NumPy is the ndarray object, which is significantly faster and more memory-efficient than standard Python
lists for numerical operations.
Key Features
N-dimensional arrays (ndarray): A fast and flexible container for large datasets. Operations on
these arrays are performed element-wise and are highly optimized.
Broadcasting: A powerful feature that allows NumPy to work with arrays of different shapes when
performing arithmetic operations.
Mathematical functions: A comprehensive set of mathematical functions for array operations.
Basic Usage
To use NumPy, you must first import it, typically with the alias np.
Python
import numpy as np
Key Features
Variety of plots: Supports line plots, bar charts, scatter plots, histograms, and more.
Customization: Almost every element of a plot (lines, colors, labels, legends) can be customized.
pyplot module: The most commonly used module within Matplotlib, providing a MATLAB-like
interface for simple plotting.
Basic Usage
To use Matplotlib, you typically import the pyplot module with the alias plt.
Python
import matplotlib.pyplot as plt
import numpy as np
The plt.show() function displays all open figures. You can create multiple plots by calling plotting
functions and then displaying them all at once.
Pandas is a library built on top of NumPy, designed for data manipulation and analysis. It introduces two
primary data structures: Series and DataFrame, which make working with structured data intuitive and
efficient.
Key Features
DataFrame: A 2-dimensional labeled data structure with columns of potentially different types.
Think of it as a spreadsheet or a SQL table.
Series: A 1-dimensional labeled array. It can be seen as a single column of a DataFrame.
Data alignment: Pandas automatically aligns data based on labels, which is a major advantage over
raw NumPy arrays.
Handling missing data: Provides tools to handle missing data (NaN).
Reading/writing data: Can read and write data from various formats, including CSV, Excel, and
SQL databases.
Basic Usage
Python
import pandas as pd
Pandas provides a vast number of methods for cleaning, transforming, and analyzing data, making it an
indispensable tool for anyone working with datasets.
4.Project
Introduction:-
The project's specific objectives are meticulously defined to achieve this aim:
Data Entry: Create a simple, menu-driven interface that guides the user through the
process of logging a ride. This feature will allow for the input of key metrics,
including distance, duration (in hours, minutes, and seconds), and average speed. The
interface will be designed to be intuitive, ensuring that even a novice user can input
their data without difficulty.
Computation: Implement mathematical logic to process the entered data. The
application will be capable of calculating key performance indicators such as the total
distance covered across all rides, the cumulative time spent cycling, and the overall
average speed. These computations will provide
users with a comprehensive summary of their cycling activity, offering valuable
insights into their progress.
Storage: Organize and store the ride data in a structured format that is both easy to
manipulate and retrieve. This will be achieved using Python's built-in data structures,
specifically lists and tuples. A list will be used to hold individual ride records, with
each record stored as a tuple containing the ride's details. This structured approach
ensures data integrity and simplifies future processing.
Visualization: Utilize the Matplotlib library to generate a visual representation of the
collected data. The application will create a plot that displays distance as a series of
blue bars and average speed as a red line, offering a clear, graphical overview of the
user’s performance over time. This visual component is crucial for quickly identifying
trends and patterns in their cycling habits.
Skill Development: Serve as a practical exercise for enhancing core programming
competencies. By working on this project, the developer will strengthen their
problem-solving abilities, refine their logical thinking, and gain hands-on experience
with fundamental Python features. The process of designing the application, writing
the code, and debugging will solidify their understanding of how these concepts work
together in a functional application.
These objectives collectively ensure the project not only delivers a functional tool but also
serves as a comprehensive learning experience, transforming abstract programming concepts
into a tangible and useful application.
Methodology:-
A key aspect of the project's data management is the use of native Python data
structures. Each individual ride's data—specifically distance, total time, and
average speed—is stored as a tuple. These tuples are then contained within a list,
creating a structured and easily iterable collection of all ride records. This
approach is both efficient for data handling and aligns with Python's best
practices for managing simple datasets.
The project's final and most impactful component is its data visualization. It
leverages the powerful matplotlib library to create a combined chart that offers a
clear analytical view. The visual representation consists of a bar chart that uses
blue bars to illustrate the distance of each ride and a line chart that uses a red
line to plot the average speed. This dual-axis visualization allows users to easily
identify correlations and trends, such as how increased distance might affect
average speed.
👉 We import the matplotlib.pyplot library, which is used to create graphs. Without this, we cannot show
distance and average speed visually.
rides = []
👉 An empty list is created to store all rides. Each ride will be saved as a tuple with values: (distance, time,
average speed).
def add_ride():
try:
distance = float(input("Enter distance (km): "))
hrs = int(input("Enter time (hours): "))
mins = int(input("Enter time (minutes): "))
secs = int(input("Enter time (seconds): "))
total_time = hrs * 60 + mins + (secs / 60) # convert time into minutes
if avg_speed > 0:
total_time = (distance / avg_speed) * 60
👉 The ride details are saved inside the rides list as a tuple. Example: (20, 70, 17).
👉 A confirmation message is shown.
except ValueError:
print("❌ Invalid input! Please enter numbers only.")
input("\nPress Enter to continue...")
👉 If the user types wrong input (like text instead of numbers), the program shows an error message.
def show_summary():
if not rides:
print("⚠ No rides added yet!")
👉 Function show_summary() checks if rides exist. If no rides are saved, it shows a warning.
else:
total_distance = sum(r[0] for r in rides)
total_time = sum(r[1] for r in rides)
avg_speed = (total_distance / (total_time / 60)) if total_time > 0 else 0
👉 If rides exist:
Total rides
Total distance covered
Total time in hours
Average speed
👉 First axis (ax1) is created for bar chart (blue bars) to show distance per ride.
ax2 = ax1.twinx()
ax2.plot(x, avg_speeds, color="red", marker="o", label="Avg Speed (km/h)")
ax2.set_ylabel("Avg Speed (km/h)", color="red")
👉 A second axis (ax2) is created for the line chart (red line) to show average speed per ride.
👉 The graph is given a title, legend, and grid. Then it is displayed to the user.
while True:
print("\n🚴 Cycle Ride Tracker 🚴")
print("1. Add Ride")
print("2. Show Summary")
print("3. Exit")
choice = input("Enter choice: ")
👉 This is the main menu. It keeps repeating until the user chooses Exit.
if choice == "1":
add_ride()
elif choice == "2":
show_summary()
elif choice == "3":
print("👋 Goodbye! Keep riding 🚴💨")
break
else:
print("❌ Invalid choice!")
input("\nPress Enter to continue...")
👉 Menu options:
1 → Add Ride
2 → Show Summary
3 → Exit Program
Any other input → Invalid choice
✅ In short:
screenshots of Project:-
OUTPUT:-
Bibliography:-
https://www.google.com
https://www.saylor.org
5. Stepwise Modules:-
Input/Output Module
The Input/Output (I/O) module was crucial for user interaction. The input() function was used to collect data from the user,
specifically for recording ride details such as distance, time (broken down into hours, minutes, and seconds), and average speed.
To present the results clearly and professionally, the print() function was employed, utilizing formatted output (f-strings) to
ensure readability and a clean presentation of statistics and messages.
Control flow was managed through decision-making and looping structures. An if-else statement was implemented to
handle conditions such as validating user input and checking whether any ride data exists before attempting to display a summary.
A while True loop was the foundation of the program's menu-driven structure. This loop ensures the application continues to
run and presents the main menu to the user repeatedly until a specific exit option is selected, making the program interactive and
persistent.
The project's data management relies on two fundamental data structures. A list, named rides, was used as the primary
container to store multiple ride records. To ensure each ride's data was kept together in a structured and immutable format, each
record was stored as a tuple containing (distance, total_time, avg_speed). This approach guarantees that the
individual ride details remain unchanged, and the overall list of rides is easy to manage and iterate through.
Functions Module
The program was built using a modular approach, dividing the code into distinct functions. Functions like add_ride(),
show_summary(), and visualize_data() were created to encapsulate specific tasks. This practice not only makes the
code significantly easier to maintain and debug but also improves its readability and allows for future expansion without
disrupting the core logic.
Mathematical Computation
To provide meaningful analytics, the program performs essential mathematical computations. The total time was calculated by
converting hours and minutes into seconds. The average speed was determined using the formula: Average Speed = Distance ÷
Total Time. These calculations transform raw user input into valuable performance metrics.
The Matplotlib library was integrated to provide a powerful visualization component. By using this external module, the project
was able to generate a clear and insightful graph. The visualization combines a bar chart (colored blue) to represent the distance
of each ride with a line chart (colored red) to show the corresponding average speed. This dual representation helps users easily
analyze their performance trends.
6. Conclusion:-
The development of the project Cycle Ride Tracker has been a highly valuable and
enriching learning experience. As part of the vocational course BCA 261 (CS105:
Introduction to Python), this project provided me with the opportunity to practically
implement the theoretical concepts that I had studied during the course. The main purpose
was to design and develop a Python-based application that records and analyzes cycling
rides, but through this process, I was able to explore much more than just programming.
From the very beginning, I learned how to analyze a real-world problem and then design a
structured solution using programming. The problem chosen was simple but practical: a
cyclist should be able to record his or her distance, time, and speed during each ride. By
breaking this down into smaller parts such as input, computation, storage, and visualization, I
was able to develop a modular and efficient Python program. This approach taught me the
importance of planning and logical thinking before jumping directly into coding.
A major skill developed during this project was working with data structures. I used lists to
store multiple rides and tuples to keep the details of each ride structured. This taught me
how Python can organize data efficiently and how these structures can be used in real
applications. The use of functions made my code modular and reusable, which is an
important practice in software development.
Another important part of this project was the use of the matplotlib library for data
visualization. This was my first time working with a visualization tool in Python, and I
realized how important graphical representation is in data analysis. By combining a bar
chart for distance and a line chart for average speed in one graph, I made the results easy
to understand and visually appealing. This skill of presenting data in a visual format is
extremely useful not just in academic projects but also in professional software development.
In conclusion, this project not only enhanced my technical skills in Python but also
improved my analytical thinking, logical reasoning, and problem-solving ability. I am
now more confident in my ability to use Python for real-world applications. The knowledge
gained from this project will serve as a strong foundation for future courses, advanced
programming, and even professional projects in the field of software development and data
science.