0% found this document useful (0 votes)
3 views

PythonYOYO for BCA

Uploaded by

aishasharma2551
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PythonYOYO for BCA

Uploaded by

aishasharma2551
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Introduction to Python

Python is a high-level, interpreted programming


language known for its readability and simplicity.
It is widely used in various fields, such as web
development, data science, automation, and
more.
Python Variables, Expressions, and Statements
Variables
Variables in Python are used to store data that
can be referenced and manipulated in your code.
A variable is created the moment you assign a
value to it using the assignment operator (=).
python
Copy code
x = 10
name = "Alice"
Keywords
Keywords are reserved words in Python that have
special meaning. They cannot be used as variable
names. Some common keywords include if, else,
while, for, def, return, and import.
Operators & Operands
Operators are symbols that perform operations
on variables and values. The values that operators
act on are called operands.
Arithmetic Operators
• + (addition)
• - (subtraction)
• * (multiplication)
• / (division)
• % (modulus)
• ** (exponentiation)
• // (floor division)
Comparison Operators
• == (equal to)
• != (not equal to)
• > (greater than)
• < (less than)
• >= (greater than or equal to)
• <= (less than or equal to)
Logical Operators
• and (logical AND)
• or (logical OR)
• not (logical NOT)
Expressions
An expression is a combination of variables,
operators, and values that produces a result.
python
Copy code
x = 10
y=5
result = x + y # result is 15
Statements
A statement is an instruction that the Python
interpreter can execute. Examples include
assignment statements, control flow statements
(if, for, while), and function definitions.
python
Copy code
x = 10 # assignment statement
if x > 5: # if statement
print("x is greater than 5")
Order of Operations
Python follows the standard mathematical order
of operations, also known as BODMAS/BIDMAS
rules (Brackets, Orders (i.e., powers and square
roots, etc.), Division and Multiplication, Addition
and Subtraction).
python
Copy code
result = 2 + 3 * 4 # result is 14 because
multiplication is done first
String Operations
Strings are sequences of characters enclosed in
quotes. Python provides various operations for
manipulating strings.
python
Copy code
greeting = "Hello"
name = "Alice"
message = greeting + " " + name # concatenation
print(message) # Output: Hello Alice

length = len(message) # get the length of the


string
print(length) # Output: 11
Comments
Comments are used to explain code and are
ignored by the interpreter. They are created using
the # symbol.
python
Copy code
# This is a comment
x = 10 # This is an inline comment
Keyboard Input
You can take input from the user using the input()
function.
python
Copy code
name = input("Enter your name: ")
print("Hello, " + name)
Example Programs
python
Copy code
# Simple addition program
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print("The sum is:", sum)
Functions
Functions are blocks of code that perform a
specific task. They help in organizing code and
reusing it.
Type Conversion Functions
Python provides functions to convert between
different types.
python
Copy code
x = int("10") # convert string to integer
y = float("10.5") # convert string to float
z = str(10) # convert integer to string
Math Functions
Python has a built-in math module that provides
various mathematical functions.
python
Copy code
import math
result = math.sqrt(16) # square root
print(result) # Output: 4.0
Composition of Functions
You can use the output of one function as the
input to another.
python
Copy code
result = math.sqrt(abs(-16)) # abs returns 16, sqrt
returns 4.0
print(result)
Defining Your Own Function
You can define your own functions using the def
keyword.
python
Copy code
def greet(name):
return "Hello, " + name

message = greet("Alice")
print(message) # Output: Hello, Alice
Parameters and Arguments
Parameters are variables that accept values within
a function. Arguments are the values passed to
the function.
python
Copy code
def add(a, b):
return a + b
result = add(3, 5) # 3 and 5 are arguments
print(result) # Output: 8
Importing Functions
You can import specific functions from a module.
python
Copy code
from math import sqrt, pow

print(sqrt(16)) # Output: 4.0


print(pow(2, 3)) # Output: 8.0
Example Programs
python
Copy code
# Program to calculate the factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num = int(input("Enter a number: "))
print("The factorial of", num, "is", factorial(num))

Conditions and Iterations in Python


Modulus Operator
The modulus operator (%) returns the remainder
of the division between two numbers.
python
Copy code
remainder = 10 % 3 # remainder is 1
print(remainder)
Boolean Expressions
Boolean expressions evaluate to either True or
False.
python
Copy code
is_greater = 10 > 5 # True
is_equal = (10 == 5) # False
Logical Operators
Logical operators are used to combine multiple
Boolean expressions.
• and: Returns True if both expressions are
True.
• or: Returns True if at least one expression is
True.
• not: Inverts the Boolean value.
python
Copy code
a = True
b = False

print(a and b) # Output: False


print(a or b) # Output: True
print(not a) # Output: False
Conditional Statements
if Statement
Executes a block of code if the condition is True.
python
Copy code
x = 10
if x > 5:
print("x is greater than 5")
if-else Statement
Executes one block of code if the condition is True
and another if it is False.
python
Copy code
x = 10
if x > 15:
print("x is greater than 15")
else:
print("x is not greater than 15")
if-elif-else Statement
Checks multiple conditions.
python
Copy code
x = 10
if x > 15:
print("x is greater than 15")
elif x > 5:
print("x is greater than 5 but not greater than
15")
else:
print("x is not greater than 5")
Nested Conditions
Conditions can be nested within each other.
python
Copy code
x = 10
y = 20

if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than
15")
Example Programs
python
Copy code
# Program to check if a number is positive,
negative, or zero
num = float(input("Enter a number: "))
if num > 0:
print("The number is positive")
elif num == 0:
print("The number is zero")
else:
print("The number is negative")
Iteration
while Loop
Repeats a block of code as long as the condition is
True.
python
Copy code
count = 0
while count < 5:
print(count)
count += 1
for Loop
Iterates over a sequence (e.g., list, string, range).
python
Copy code
# Iterating over a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)

# Using range
for i in range(5):
print(i)
break Statement
Exits the loop prematurely when a condition is
met.
python
Copy code
for i in range(10):
if i == 5:
break
print(i)
continue Statement
Skips the current iteration and proceeds to the
next one.
python
Copy code
for i in range(10):
if i % 2 == 0:
continue
print(i) # prints only odd numbers
Nested Loops
Loops inside other loops.
python
Copy code
for i in range(3):
for j in range(3):
print(f"i = {i}, j = {j}")
Example Programs
python
Copy code
# Program to find the sum of all numbers up to a
given number
n = int(input("Enter a number: "))
sum = 0
for i in range(1, n+1):
sum += i
print(f"The sum of all numbers from 1 to {n} is
{sum}")

# Program to print the multiplication table of a


number
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num*i}")

Recursion
What is Recursion?
Recursion is a programming technique where a
function calls itself in order to solve smaller
instances of the same problem. This continues
until it reaches a base case, which is a condition
that stops the recursion.
How Recursion Works
1. Base Case: This is the condition that stops the
recursion. Without a base case, the function
would call itself indefinitely, leading to a stack
overflow.
2. Recursive Case: This is where the function
calls itself with a smaller or simpler input,
gradually approaching the base case.
Example of a Recursive Function
• Factorial Calculation: The factorial of a
number n (denoted as n!) is the product of all
positive integers less than or equal to n.
python
Copy code
def factorial(n):
if n == 0:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive case

print(factorial(5)) # Output: 120


Recursion Error
If a recursion function does not reach a base case,
it will result in a RecursionError due to exceeding
the maximum recursion depth.
python
Copy code
def infinite_recursion():
return infinite_recursion()
# This will raise a RecursionError
# infinite_recursion()
Advantages & Disadvantages of Recursion
Advantages:
• Simplified Code: Recursive solutions are often
more concise and easier to understand for
problems that have a natural recursive
structure, such as tree traversal and divide-
and-conquer algorithms.
Disadvantages:
• Performance: Recursion can be less efficient
than iterative solutions due to the overhead
of multiple function calls.
• Memory Usage: Each recursive call adds a
new layer to the call stack, which can lead to
high memory usage and potential stack
overflow if the recursion is too deep.
Strings
What are Strings?
Strings are sequences of characters used to
represent text. They are immutable in Python,
meaning once created, their content cannot be
changed.
Accessing Values in Strings
You can access individual characters in a string
using indexing.
python
Copy code
s = "Hello"
print(s[0]) # Output: H
print(s[-1]) # Output: o
Updating Strings
Since strings are immutable, you can't modify
them directly. Instead, you create new strings.
python
Copy code
s = "Hello"
s = s + " World"
print(s) # Output: Hello World
Slicing Strings
You can extract a substring using slicing.
python
Copy code
s = "Hello World"
print(s[0:5]) # Output: Hello
print(s[6:]) # Output: World
String Methods
Strings have many built-in methods for
manipulation and querying.
• upper(): Converts all characters to uppercase.
• lower(): Converts all characters to lowercase.
• capitalize(): Capitalizes the first character of
the string.
• find(): Returns the lowest index of the
substring if found, otherwise -1.
• count(): Returns the number of non-
overlapping occurrences of a substring.
• replace(): Returns a copy of the string with all
occurrences of a substring replaced by
another substring.
• split(): Splits the string at the specified
separator and returns a list of substrings.
• join(): Joins the elements of an iterable with
the string as a separator.
python
Copy code
s = "hello world"
print(s.upper()) # Output: HELLO WORLD
print(s.capitalize()) # Output: Hello world
print(s.find("world")) # Output: 6
print(s.count("l")) # Output: 3
print(s.replace("world", "Python")) # Output:
hello Python
print(s.split()) # Output: ['hello', 'world']

words = ["hello", "world"]


print(" ".join(words)) # Output: hello world
Checking String Characteristics
• isalpha(): Returns True if all characters are
alphabetic.
• isdigit(): Returns True if all characters are
digits.
• isalnum(): Returns True if all characters are
alphanumeric.
• isnumeric(): Returns True if all characters are
numeric.
• isspace(): Returns True if all characters are
whitespace.
• islower(): Returns True if all characters are
lowercase.
• isupper(): Returns True if all characters are
uppercase.
python
Copy code
s = "Hello123"
print(s.isalpha()) # Output: False
print(s.isdigit()) # Output: False
print(s.isalnum()) # Output: True
Lists
What are Lists?
Lists are ordered collections of items, which can
be of different types. Lists are mutable, meaning
you can change their content after creation.
Traversing Lists
You can iterate over the elements in a list using a
for loop.
python
Copy code
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
List Operations and Methods
• Append and Extend: Add elements to the end
of the list.
python
Copy code
numbers = [1, 2, 3]
numbers.append(4)
numbers.extend([5, 6])
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
• Removing Elements: Remove elements by
value or by index.
python
Copy code
numbers.remove(3) # Removes the first
occurrence of 3
del numbers[0] # Removes the element at index 0
Slicing Lists
You can extract a sublist using slicing.
python
Copy code
print(numbers[1:4]) # Output: [2, 4, 5]
Difference Between Lists and Strings
• Mutability: Lists are mutable; strings are
immutable.
• Data Types: Lists can contain elements of
different data types; strings can only contain
characters.
Dictionaries
What are Dictionaries?
Dictionaries are collections of key-value pairs.
Keys are unique and immutable, while values can
be of any type.
Operations on Dictionaries
• Accessing Values: Use the key to access the
value.
python
Copy code
person = {"name": "Alice", "age": 25, "city": "New
York"}
print(person["name"]) # Output: Alice
• Updating Values: Change the value associated
with a key.
python
Copy code
person["age"] = 26
• Adding and Removing Key-Value Pairs: Add
new pairs or remove existing ones.
python
Copy code
person["email"] = "[email protected]"
del person["city"]
Traversing Dictionaries
You can iterate over keys, values, or key-value
pairs.
python
Copy code
for key, value in person.items():
print(f"{key}: {value}")
Tuples
What are Tuples?
Tuples are immutable ordered collections of
items. Once created, their content cannot be
changed.
Using Tuples
python
Copy code
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
Comparison of Lists, Dictionaries, and Tuples
• Lists vs Tuples: Lists are mutable, while tuples
are immutable. Use tuples for fixed
collections of items.
• Dictionaries vs Tuples: Dictionaries store key-
value pairs, allowing for fast lookups by key,
while tuples store ordered items and are used
for fixed data sets.
Summary
• Recursion: A technique where a function calls
itself to solve a smaller instance of the same
problem, useful but can lead to performance
issues.
• Strings: Immutable sequences of characters
with various methods for manipulation.
• Lists: Mutable collections useful for storing
and manipulating ordered data.
• Dictionaries: Collections of key-value pairs for
fast lookups.
• Tuples: Immutable ordered collections used
for fixed data sets.

Classes and Objects in Python


Creating a Class
A class is a blueprint for creating objects. It
defines a set of attributes and methods that the
created objects can use.
python
Copy code
class Dog:
# Class attribute
species = "Canis familiaris"

# Initializer / Instance attributes


def __init__(self, name, age):
self.name = name
self.age = age

# Instance method
def description(self):
return f"{self.name} is {self.age} years old"

# Another instance method


def speak(self, sound):
return f"{self.name} says {sound}"
Instance Objects
Instance objects are created from a class and have
their own set of attributes and methods defined
in the class.
python
Copy code
# Creating instance objects
my_dog = Dog("Buddy", 5)
your_dog = Dog("Lucy", 3)
# Accessing attributes
print(my_dog.name) # Output: Buddy
print(your_dog.age) # Output: 3

# Calling instance methods


print(my_dog.description()) # Output: Buddy is 5
years old
print(your_dog.speak("Woof")) # Output: Lucy
says Woof
Accessing Attributes
Attributes of an instance can be accessed using
the dot . operator.
python
Copy code
print(my_dog.name) # Output: Buddy
print(my_dog.age) # Output: 5
Built-in Class Attributes
Python provides some built-in class attributes that
can be accessed using the dot . operator.
• __dict__: Contains the namespace of the
class.
• __doc__: Contains the documentation string
of the class.
• __name__: Contains the class name.
• __module__: Contains the module name in
which the class is defined.
• __bases__: Contains a tuple of all base
classes.
python
Copy code
print(Dog.__dict__)
print(Dog.__doc__)
print(Dog.__name__)
print(Dog.__module__)
print(Dog.__bases__)
Destroying Objects
In Python, objects are destroyed automatically
when they go out of scope or when the reference
count reaches zero. The __del__ method is called
when an object is about to be destroyed.
python
Copy code
class MyClass:
def __init__(self, value):
self.value = value

def __del__(self):
print(f"An instance with value {self.value} is
being destroyed")

obj = MyClass(10)
del obj # Explicitly deletes the object
Inheritance
Inheritance allows a class to inherit attributes and
methods from another class.
python
Copy code
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
raise NotImplementedError("Subclass must
implement this method")

class Dog(Animal):
def speak(self):
return f"{self.name} says Woof"

class Cat(Animal):
def speak(self):
return f"{self.name} says Meow"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Output: Buddy says Woof
print(cat.speak()) # Output: Whiskers says Meow
Method Overriding
Method overriding allows a subclass to provide a
specific implementation of a method that is
already defined in its superclass.
python
Copy code
class Animal:
def speak(self):
return "Some sound"

class Dog(Animal):
def speak(self):
return "Woof"

dog = Dog()
print(dog.speak()) # Output: Woof
Overloading Methods
Python does not support method overloading by
default. However, you can achieve similar
functionality using default arguments.
python
Copy code
class MathOperations:
def add(self, a, b, c=0):
return a + b + c

math_op = MathOperations()
print(math_op.add(2, 3)) # Output: 5
print(math_op.add(2, 3, 4)) # Output: 9
Overloading Operators
Operator overloading allows you to define how
operators behave with your custom objects.
python
Copy code
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)

def __str__(self):
return f"Point({self.x}, {self.y})"

p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2

print(p3) # Output: Point(4, 6)


Data Hiding
Data hiding is a technique to restrict access to
certain attributes or methods. This can be
achieved using single or double underscores.
python
Copy code
class MyClass:
def __init__(self, value):
self.__hidden_value = value # Double
underscore for name mangling

def get_hidden_value(self):
return self.__hidden_value

obj = MyClass(10)
print(obj.get_hidden_value()) # Output: 10
# print(obj.__hidden_value) # This will raise an
AttributeError

Example Program
python
Copy code
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance

def deposit(self, amount):


if amount > 0:
self.__balance += amount
print(f"Deposited {amount}. New balance is
{self.__balance}")
else:
print("Invalid deposit amount")

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew {amount}. New balance is
{self.__balance}")
else:
print("Invalid withdraw amount or
insufficient funds")

def get_balance(self):
return self.__balance

# Creating an account
account = BankAccount("Alice", 100)

# Accessing attributes and methods


print(account.owner) # Output: Alice
account.deposit(50) # Output: Deposited 50.
New balance is 150
account.withdraw(30) # Output: Withdrew 30.
New balance is 120
print(account.get_balance()) # Output: 120
Summary
• Classes and Objects: A class is a blueprint for
objects, defining attributes and methods.
Objects are instances of classes.
• Instance Attributes and Methods: Attributes
and methods belong to individual objects.
• Built-in Class Attributes: Python provides
built-in attributes to access class information.
• Inheritance: Allows a class to inherit
attributes and methods from another class.
• Method Overriding: Subclasses can provide
specific implementations of methods defined
in the superclass.
• Overloading Methods and Operators:
Customize how methods and operators
behave with your objects.
• Data Hiding: Restrict access to certain
attributes or methods using underscores.

You might also like