You are on page 1of 12

Python Programming

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:

Program to calculate the area of a rectangle:


length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
area = length * width
print("Area:", area)
Program to convert temperature from Celsius to Fahrenheit:
celsius = float(input("Enter the temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)
Program to check if a number is prime:
num = int(input("Enter a number: "))
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Functions:

Type Conversion Functions:


Type conversion functions are used to convert values from one data type to another.
Examples of type conversion functions:
int(): converts a value to an integer.
float(): converts a value to a floating-point number.
str(): converts a value to a string.
Math Functions:
Python provides a set of built-in math functions to perform various mathematical operations.
Examples of math functions:
abs(): returns the absolute value of a number.
pow(): raises a number to a specified power.
sqrt(): returns the square root of a number.
Composition of Functions:
Functions can be composed by calling one function inside another.
The output of one function becomes the input of another function.
Example:
result = sqrt(pow(2, 3))
Defining Your Own Function:
Python allows you to define your own functions to perform specific tasks.
Functions help in code modularity, reusability, and better organization.
Example:
def greet(name):
print("Hello, " + name + "!")

greet("Alice") # Output: Hello, Alice!


Parameters and Arguments:
Parameters are variables defined in the function's declaration, and they receive values when the function is called.
Arguments are the actual values passed to the function during the function call.
Example:
def add_numbers(x, y):
return x + y

sum = add_numbers(5, 3) # Arguments: 5 and 3


print("Sum:", sum) # Output: Sum: 8
Importing Functions:
Python provides modules and libraries that contain predefined functions.
You can import these functions into your program using the import statement.
Example:
import math
result = math.sqrt(25)
print("Square root:", result)

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)

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
max_num = find_max(num1, num2, num3)
print("Maximum number:", max_num)
Note: The above examples illustrate the concepts of functions and their usage. You can modify them or explore more advanced
examples based on your requirements.

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)

result = factorial(5) # Output: 120

Examples of Recursive Functions:


Fibonacci sequence:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

result = fibonacci(6) # Output: 8


Factorial calculation:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

result = factorial(5) # Output: 120


Recursion Error:
A recursion error, also known as a "maximum recursion depth exceeded" error, occurs when the recursive function calls itself
too many times without reaching the base case.
It indicates that the recursion depth limit has been exceeded and can lead to the program crashing.
To avoid this error, it's important to ensure that the base case is reachable and that the recursion is properly controlled.
Advantages of Recursion:
Recursive solutions can be elegant and concise, especially for problems that can be naturally divided into smaller subproblems.
Recursion allows for the application of divide-and-conquer techniques, which can simplify problem-solving.
It can lead to code that is easier to understand and maintain in some cases.
Disadvantages of Recursion:
Recursive solutions can be less efficient compared to iterative solutions due to the overhead of function calls and stack memory
usage.
If not implemented correctly, recursion can lead to infinite recursion, causing the program to crash or run indefinitely.
Recursive solutions may consume more memory, especially if the recursion depth is large.

Strings:

Accessing Values in Strings:


Individual characters in a string can be accessed using indexing.
Indexing starts from 0, where the first character is at index 0, the second at index 1, and so on.
Example:
str = "Hello"
print(str[0]) # Output: 'H'
Updating Strings:
Strings are immutable in Python, meaning their individual characters cannot be changed.
However, a new string can be created by concatenating or replacing characters.
Example:
str = "Hello"
new_str = str[:2] + "X" + str[3:] # Replaces 'l' with 'X'
print(new_str) # Output: "Hexlo"
Slicing Strings:
Slicing is a technique to extract a substring from a larger string.
It is done by specifying the start and end indices, separated by a colon ":".
The ending index is exclusive, meaning the character at that index is not included.
Example:
str = "Hello, World!"
substring = str[7:12] # Extracts "World"
print(substring)
String Methods:
Strings in Python have built-in methods that can be used to perform various operations.
Some commonly used string methods:
upper(): converts a string to uppercase.
find(): finds the first occurrence of a substring and returns its index.
lower(): converts a string to lowercase.
capitalize(): capitalizes the first character of a string.
count(): counts the occurrences of a substring in a string.
join(): concatenates a list of strings into a single string, using a specified delimiter.
len(): returns the length of a string.
isalnum(): checks if a string contains only alphanumeric characters.
isalpha(): checks if a string contains only alphabetic characters.
isdigit(): checks if a string contains only digits.
islower(): checks if all characters in a string are lowercase.
isnumeric(): checks if a string contains only numeric characters.
isspace(): checks if a string contains only whitespace characters.
isupper(): checks if all characters in a string are uppercase.
max(): returns the maximum character from a string.
min(): returns the minimum character from a string.
replace(): replaces all occurrences of a substring with another substring.
split(): splits a string into a list of substrings based on a delimiter.
Example:
str = "Hello, World!"
print(str.upper()) # Output: "HELLO, WORLD!"
print(str.find("World")) # Output: 7
print(str.isdigit()) # Output: False

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

input_str = input("Enter a string: ")


search_char = input("Enter a character: ")
occurrences = count_char(input_str, search_char)
print("Occurrences:", occurrences)
Program to reverse a string using slicing:
def reverse_string(string):
return string[::-1]

input_str = input("Enter a string: ")


reversed_str = reverse_string(input_str)
print("Reversed string:", reversed_str)
Program to capitalize the first letter of each word in a string:
def capitalize_words(string):
words = string.split()
capitalized_words = [word.capitalize() for word in words]
return " ".join(capitalized_words)

input_str = input("Enter a string: ")


capitalized_str = capitalize_words(input_str)
print("Capitalized string:", capitalized_str)
Note: The above examples demonstrate various string operations and methods. You can modify them or explore more advanced
examples based on your requirements.

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

def add(self, a, b, c):


return a + b + c
Overloading Operators:
Python allows overloading of operators by defining special methods in a class.
These special methods have predefined names and are called when certain operators are used on objects of the class.
Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
Data Hiding:
Data hiding refers to the concept of encapsulating data within a class, making it inaccessible from outside the class.
In Python, data hiding can be achieved by using name mangling, which involves adding a double underscore (__) prefix to an
attribute name.
Example:
class BankAccount:
def __init__(self):
self.__balance = 0 # Data hiding

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount

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())

___ Thanks ___

You might also like