Unit - 1
Unit - 1
Chapter -1
Topic – Python Basics
Python is a high level interpreted interactive and object-oriented scripting
language.
Python is designed to be highly readable because it uses English keywords
frequently whereas other languages use punctuations.
why do we use it:
Python is interpreted – python is processed at run time by the
interpreter, you don’t have to need to compile your programs before
executing it.
Python is interactive – You can directly write your python program at
python prompt.
Python is Object – Oriented – It uses programming technique that
encapsulates code within objects.
Python is Beginner’s Language - It has a simple syntax and it is easy to
learn.
Features of python:
Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax.
Easy-to-read − Python code is more clearly defined and uses English like
language.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable
and cross-platform compatible on UNIX, Windows, and MacOS.
Interactive Mode − Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and
has the same interface on all platforms. The code written in any other OS
can run on any other OS.
Extendable − You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
Databases − Python provides interfaces to all major commercial
databases.
GUI Programming − Python supports GUI applications that can be
created and ported to many system calls, libraries and windows systems.
Scalable − Python provides a better structure and support for large
programs than shell scripting.
Removing Numbers:
In Python, you don't explicitly remove numbers; instead, you can delete
the variable holding the number using the del statement.
When you delete a variable, it removes the reference to the number,
and if there are no other references to that number, it becomes eligible
for garbage collection.
After deleting a variable, you won't be able to access its value, and
attempting to do so will result in a NameError because the variable no
longer exists.
Example of demonstration:
x = 5 # Create and assign a number
del x # Delete the variable x (number is removed if no other references
exist)
Topic – Operators
In Python, you can perform various operations on numbers using operators.
These operators allow you to perform arithmetic calculations, comparisons,
and other manipulations on numeric values.
Arithmetic Operators:
Arithmetic operators are used for performing mathematical operations on
numbers.
o Addition +: Adds two numbers together.
Example code:
result = 5 + 3 # Result is 8
o Subtraction -: Subtracts the right operand from the left operand.
result = 8 - 3 # Result is 5
o Multiplication *: Multiplies two numbers.
result = 4 * 6 # Result is 24
o Division /: Divides the left operand by the right operand. The result is a
float.
result = 15 / 2 # Result is 7.5
o Integer Division //: Performs floor division, discarding the remainder to
return an integer result.
result = 15 // 2 # Result is 7
o Modulo %: Returns the remainder of the division of the left operand by
the right operand.
remainder = 15 % 2 # Result is 1
o Exponentiation **: Raises the left operand to the power of the right
operand.
result = 2 ** 3 # Result is 8
Comparison Operators:
Comparison operators are used to compare two numbers and return a Boolean
result (True or False).
Equal ==: Checks if two values are equal.
result = (5 == 5) # Result is True
Not Equal !=: Checks if two values are not equal.
result = (5 != 3) # Result is True
Greater Than >: Checks if the left operand is greater than the right
operand.
result = (8 > 5) # Result is True
Less Than <: Checks if the left operand is less than the right operand.
result = (3 < 5) # Result is True
Greater Than or Equal To >=: Checks if the left operand is greater than or
equal to the right operand.
result = (5 >= 5) # Result is True
Less Than or Equal To <=: Checks if the left operand is less than or equal
to the right operand.
result = (3 <= 5) # Result is True
Logical Operators:
Logical operators are used to combine or manipulate Boolean values.
and: Returns True if both operands are True.
result = (True and False) # Result is False
or: Returns True if at least one operand is True.
result = (True or False) # Result is True
not: Returns the opposite of the operand's value.
result = not True # Result is False
Bitwise Operators:
Bitwise operators in Python are used to perform
operations on the individual bits of integers.
These operators work directly with the binary
representation of the numbers.
The bitwise operators include:
def bark(self):
return f"{self.name} barks loudly!"
Method Creation:
Methods are functions defined within a class that perform operations
on the class's attributes or provide functionality related to the class.
The def keyword is used to create methods within a class.
The first parameter of a method is always self, which represents the
instance of the class on which the method is called.
You can define methods to access and modify attributes or perform
other tasks specific to the class.
In the example above, the Dog class has a constructor method init
and a method bark.
Method Calling:
To call a method on an object, you use the dot notation, specifying the
object followed by the method name and parentheses.
The self parameter is implicitly passed when you call a method on an
object. You don't need to provide it explicitly.
Example of creating an object and calling its methods:
# Creating a Dog object
my_dog = Dog("Buddy", "Golden Retriever")
# Calling methods on the Dog object
print(my_dog.bark()) # Output: "Buddy barks loudly!"
Tuples:
Tuples are similar to lists, but they are enclosed in parentheses ( ).
They are immutable, meaning their elements cannot be changed after
creation.
Tuples can also contain elements of different data types.
Example:
# Creating a tuple of colors
colors = ('red', 'green', 'blue')
# Accessing elements
first_color = colors[0]
second_color = colors[1]
# Iterating through the tuple
for color in colors:
print(color)
Mapping Types:
Mapping types in Python are collections of key-value pairs. In other words, they
allow you to associate values (the "values") with unique keys (the "keys").
The keys are used to retrieve the corresponding values. Python provides a
built-in mapping type called a dictionary.
Dictionary (dict):
A dictionary is an unordered collection of key-value pairs enclosed in
curly braces {} or created using the dict() constructor.
Keys within a dictionary are unique, immutable (e.g., strings, numbers,
or tuples), and used to access the associated values.
Dictionaries are often used when you need to store and retrieve data
based on specific identifiers or labels.
Example:
# Creating a dictionary
student = {
"name": "Alice",
"age": 25,
"grade": "A"
}
# Accessing values using keys
print(student["name"]) # Output: "Alice"
Set Types:
Set types in Python are collections of unique, unordered elements. Sets are
similar to lists or tuples, but they do not allow duplicate values.
Set (set):
A set is an unordered collection of unique elements enclosed in curly
braces {} or created using the set() constructor.
Sets are commonly used for tasks that involve testing membership or
removing duplicates from a collection.
Example:
# Creating a set
fruits = {"apple", "banana", "cherry"}
# Adding an element to the set
fruits.add("orange")
# Checking membership
print("apple" in fruits) # Output: True