Python Programming (BCAC403)
Python Programming (BCAC403)
Python Variables:
In Python, variables are used to store values that can be referenced and manipulated in the program.
Variables are created by assigning a value to a name using the assignment operator "=".
Example:
x = 10
name = "John"
Keywords:
Keywords are reserved words in Python that have predefined meanings and cannot be used as variable names.
Examples of keywords in Python include "if," "else," "for," "while," "def," etc.
Expressions:
Expressions are combinations of variables, values, and operators that evaluate to a single value.
They can include arithmetic, logical, or relational operations.
Examples:
x = 10
y=5
z = x + y # Addition expression
is_greater = x > y # Relational expression
Statements:
Statements are instructions or commands that perform specific actions in Python.
Examples of statements include variable assignment, conditional statements (if, elif, else), loops (while, for), etc.
Operators and Operands:
Operators are symbols or special keywords that perform operations on operands.
Operands are the values or variables on which operators act.
Examples of operators in Python:
Arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus), etc.
Relational operators: == (equal to), != (not equal to), < (less than), > (greater than), etc.
Logical operators: and, or, not, etc.
Order of Operations:
The order of operations determines the sequence in which operations are performed in an expression.
The acronym PEMDAS is commonly used to remember the order:
Parentheses first
Exponents (i.e., powers and square roots, etc.)
Multiplication and Division (from left to right)
Addition and Subtraction (from left to right)
String Operations:
Strings are sequences of characters and can be manipulated using various operations.
String operations include concatenation (combining strings), slicing (extracting substrings), length calculation, etc.
Examples:
str1 = "Hello"
str2 = "World"
concatenated = str1 + " " + str2 # Concatenation
substring = str1[1:3] # Slicing
length = len(str1) # Length calculation
Comments:
Comments are used to add explanatory notes to the code. They are not executed.
They help improve code readability and make it easier for others to understand.
In Python, comments start with the "#" symbol.
Example:
# This is a comment
Keyboard Input:
Python provides the input() function to accept user input from the keyboard.
The input() function prompts the user for input and returns the entered value as a string.
Example:
name = input("Enter your name: ")
Example Programs:
Functions:
Example Programs:
Program to calculate the area of a circle using a predefined math function:
import math
radius = float(input("Enter the radius: "))
area = math.pi * math.pow(radius, 2)
print("Area:", area)
Program to convert seconds to hours, minutes, and seconds:
total_seconds = int(input("Enter the total seconds: "))
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
print("Time: {} hours, {} minutes, {} seconds".format(hours, minutes, seconds))
Program to find the maximum of three numbers using a user-defined function:
def find_max(a, b, c):
return max(a, b, c)
Modulus Operator:
The modulus operator (%) returns the remainder of the division of one number by another.
It is denoted by the percent symbol (%).
Example:
print(7 % 3) # Output: 1 (remainder when 7 is divided by 3)
Boolean Expression:
A boolean expression is an expression that evaluates to either True or False.
It typically involves comparison operators such as equal to (==), not equal to (!=), greater than (>), less than (<), etc.
Example:
x=5
y = 10
print(x < y) # Output: True (5 is less than 10)
Logical Operators:
Logical operators are used to combine boolean expressions and perform logical operations.
The three logical operators in Python are:
and: Returns True if both operands are True.
or: Returns True if at least one of the operands is True.
not: Returns the opposite of the operand's logical value.
Example:
x=5
y = 10
z = 15
print(x < y and y < z) # Output: True (both conditions are True)
if Statement:
The if statement is used to execute a block of code only if a certain condition is True.
It can be followed by an optional else statement to specify code to execute when the condition is False.
Example:
x=5
if x < 10:
print("x is less than 10")
else:
print("x is greater than or equal to 10")
if-else Statement:
The if-else statement allows you to specify different code blocks to execute based on different conditions.
Example:
x=5
if x < 5:
print("x is less than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is greater than 5")
Nested Conditions:
Nested conditions refer to using if statements inside other if statements.
This allows for more complex decision-making based on multiple conditions.
Example:
x=5
y = 10
if x < 10:
if y > 5:
print("Nested condition satisfied")
Iteration:
while Loop:
The while loop is used to repeatedly execute a block of code as long as a certain condition is True.
The condition is checked before each iteration, and the loop continues until the condition becomes False.
Example:
count = 0
while count < 5:
print("Count:", count)
count += 1
for Loop:
The for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.
It executes a block of code for each element in the sequence.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
break Statement:
The break statement is used to exit a loop prematurely.
It terminates the loop and transfers control to the next statement following the loop.
Example:
count = 0
while True:
print("Count:", count)
count += 1
if count == 5:
break
continue Statement:
The continue statement is used to skip the rest of the code within a loop for the current iteration and move to the next iteration.
It allows you to bypass certain code blocks and proceed to the next iteration.
Example:
for num in range(10):
if num % 2 == 0:
continue
print(num)
Nested Loop:
A nested loop is a loop inside another loop.
It allows you to iterate over multiple sequences or perform repetitive tasks in a nested structure.
Example:
for i in range(3):
for j in range(2):
print(i, j)
Example Programs:
Program to find the factorial of a number using a while loop:
num = 5
factorial = 1
while num > 0:
factorial *= num
num -= 1
print("Factorial:", factorial)
Program to iterate through a list and print only the even numbers:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(num)
Program to print a pattern using nested loops:
for i in range(1, 5):
for j in range(i):
print("*", end=" ")
print()
Output:
*
**
***
****
Recursion:
Python Recursion:
Recursion is a programming technique where a function calls itself to solve a smaller version of the same problem.
It involves breaking down a complex problem into simpler, more manageable subproblems.
Recursive functions have a base case that specifies when the recursion should stop, and a recursive case that calls the function
with a smaller input.
Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Strings:
Example Programs:
Program to count the occurrences of a specific character in a string:
def count_char(string, char):
count = 0
for c in string:
if c == char:
count += 1
return count
List:
Introduction:
Lists are a versatile and widely used data structure in Python.
They can store multiple items of different data types in a single variable.
Lists are mutable, meaning their elements can be modified.
Example:
fruits = ["apple", "banana", "cherry"]
Traversal:
Traversal involves accessing each element in a list one by one.
It can be done using a for loop or while loop.
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Operations:
Lists support various operations such as concatenation, repetition, and membership testing.
Examples:
fruits1 = ["apple", "banana"]
fruits2 = ["cherry", "orange"]
concatenated = fruits1 + fruits2 # Concatenation
repeated = fruits1 * 3 # Repetition
print("apple" in fruits1) # Membership testing (Output: True)
Slice:
Slicing in lists is similar to slicing in strings.
It allows you to extract a portion of a list by specifying the start and end indices.
Example:
numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4] # Extracts [2, 3, 4]
Methods:
Lists have built-in methods that can be used to perform various operations.
Some commonly used list methods:
append(): adds an element to the end of the list.
insert(): inserts an element at a specified index.
remove(): removes the first occurrence of a specified element.
pop(): removes and returns the element at a specified index.
index(): returns the index of the first occurrence of a specified element.
count(): returns the number of occurrences of a specified element.
sort(): sorts the list in ascending order.
reverse(): reverses the order of the elements in the list.
Example:
numbers = [3, 1, 4, 2, 5]
numbers.append(6)
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
Delete Element:
Elements can be removed from a list using the del statement or the remove() method.
Example:
numbers = [1, 2, 3, 4, 5]
del numbers[2] # Removes the element at index 2
numbers.remove(4) # Removes the first occurrence of 4
Difference between Lists and Strings:
Lists and strings are both sequence types in Python but have some differences:
Strings are immutable, while lists are mutable.
Lists can contain elements of different data types, while strings are homogeneous and store characters.
List elements are accessed using indexing, while string elements are accessed in the same way but can't be modified
individually.
Lists have methods specific to lists, while strings have methods specific to strings.
Example Program:
Program to find the sum of all numbers in a list:
numbers = [10, 20, 30, 40, 50]
sum = 0
for num in numbers:
sum += num
print("Sum:", sum)
Dictionaries:
Introduction:
Dictionaries are another commonly used data structure in Python.
They store data in key-value pairs, allowing efficient retrieval of values based on their keys.
Dictionaries are enclosed in curly braces {} and consist of comma-separated key-value pairs.
Example:
student = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
}
Brief Idea of Dictionaries and Lists:
Both dictionaries and lists are used to store and organize data.
Dictionaries use keys to access values, while lists use indexes.
Dictionaries provide a way to associate values with specific identifiers, while lists are ordered collections of values.
Tuples:
Introduction:
Tuples are similar to lists and are used to store multiple items in a single variable.
Tuples are immutable, meaning their elements cannot be modified after creation.
They are enclosed in parentheses () and consist of comma-separated values.
Example:
point = (3, 5)
Brief Idea of Lists and Tuples:
Lists and tuples are both used to store and organize multiple items.
Lists are mutable, while tuples are immutable.
Lists use brackets [], while tuples use parentheses ().
Lists are typically used when the order of items matters and when modifications are expected, while tuples are used when
immutability and integrity of data are desired.
Brief Idea of tuples and dictionary:
Tuples:
Tuples are an immutable data type in Python, meaning their elements cannot be modified after creation.
They are ordered collections of elements enclosed in parentheses ().
Tuples can contain elements of different data types.
Elements in a tuple are accessed using indexing, similar to lists and strings.
Tuples are commonly used when you want to group related values together that should not be modified.
Examples:
point = (3, 5): A tuple representing a point in a 2D coordinate system.
student = ("Alice", 20, "Computer Science"): A tuple representing student information.
Dictionaries:
Dictionaries are a mutable data type in Python that store data in key-value pairs.
They are unordered collections of elements enclosed in curly braces {}.
Each element in a dictionary consists of a key and its corresponding value, separated by a colon (:).
Keys must be unique within a dictionary, and they are used to access the associated values.
Dictionaries are commonly used when you want to store and retrieve data based on specific identifiers or labels.
Examples:
student = {"name": "Alice", "age": 20, "major": "Computer Science"}: A dictionary representing student information.
fruits = {"apple": "red", "banana": "yellow", "cherry": "red"}: A dictionary mapping fruits to their colors.
Comparison:
Tuples and dictionaries serve different purposes and have different characteristics:
Tuples are used when you have a collection of related values that should remain unchanged., while Dictionaries are used when
you need to store and retrieve data based on specific keys or labels.
Tuples are indexed by position, while dictionaries are indexed by keys.
Tuples are immutable, meaning their elements cannot be modified once created, while Dictionaries are mutable and can have
elements added, modified, or removed.
Tuples are typically used for fixed and ordered data, while dictionaries are used for key-value mappings and unordered data.
Creating a Class:
In Python, a class is a blueprint for creating objects with specific attributes and behaviors.
Classes are defined using the class keyword followed by the class name.
Example:
class Car:
pass
Instance Objects:
An object is an instance of a class, created using the class as a template.
Multiple objects can be created from a single class, each with its own set of attributes and behaviors.
Example:
car1 = Car() # Creating an instance of the Car class
car2 = Car() # Creating another instance of the Car class
Accessing Attributes:
Object attributes are variables associated with a specific instance of a class.
They can be accessed using the dot notation object.attribute.
Example:
car1.color = "red" # Setting the color attribute of car1
print(car1.color) # Accessing the color attribute of car1
Built-in Class Attributes:
Classes in Python have built-in attributes that provide useful information about the class.
Here are some commonly used built-in class attributes:
‘__name__’: This attribute represents the name of the class as a string.
‘__doc__’: This attribute stores the documentation string or docstring associated with the class. It provides information about
the class and its purpose.
‘__module__’: This attribute contains the name of the module in which the class is defined. If the class is defined in the main
script, the value will be ‘__main__’.
‘__dict__’: This attribute is a dictionary that contains the class's namespace. It stores the class's attributes and their values.
‘__bases__’: This attribute contains a tuple of the base classes from which the class inherits.
Example:
print(Car.__name__) # Output: "Car" (name of the class)
print(Car.__module__) # Output: "__main__" (name of the module)
Destroying Objects:
Python automatically handles memory management and object destruction through a mechanism called garbage collection.
Objects are destroyed when they are no longer referenced by any part of the program.
However, you can use the del keyword to explicitly destroy an object or its attributes.
Example:
del car1 # Destroying the car1 object
Inheritance:
Inheritance is a mechanism that allows a class to inherit attributes and behaviors from a parent class.
The child class can override or extend the attributes and behaviors of the parent class.
It promotes code reuse and allows for the creation of specialized classes based on existing ones.
Example:
class ElectricCar(Car): # ElectricCar inherits from Car
pass
Method Overriding:
Method overriding occurs when a subclass provides its own implementation of a method inherited from the parent class.
The overridden method in the child class takes precedence over the parent class method.
Example:
class ElectricCar(Car):
def start(self):
print("Starting the electric car")
Overloading Methods:
Method overloading refers to the ability to define multiple methods with the same name but different parameters or
arguments.
Python does not support method overloading directly, but you can achieve similar functionality using default arguments or
variable-length arguments.
Example:
class Calculator:
def add(self, a, b):
return a + b
Example Program:
Program to create a class representing a Circle and calculate its area and circumference:
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def circumference(self):
return 2 * math.pi * self.radius
circle = Circle(5)
print("Area:", circle.area())
print("Circumference:", circle.circumference())