Unit 1 Python
Unit 1 Python
What is Python
Features of Python:
o Easy to use and Read - Python's syntax is clear and easy to read, making it an ideal
language for both beginners and experienced programmers. This simplicity can lead to
faster development and reduce the chances of errors.
o Dynamically Typed - The data types of variables are determined during run-time. We do
not need to specify the data type of a variable during writing codes.
o High-level - High-level language means human readable code.
o Compiled and Interpreted - Python code first gets compiled into bytecode, and then
interpreted line by line. When we download the Python in our system form org we
download the default implement of Python known as CPython. CPython is considered to
be Complied and Interpreted both.
o Garbage Collected - Memory allocation and de-allocation are automatically managed.
Programmers do not specifically need to manage the memory.
o Purely Object-Oriented - It refers to everything as an object, including numbers and
strings.
o Cross-platform Compatibility - Python can be easily installed on Windows, macOS,
and various Linux distributions, allowing developers to create software that runs across
different operating systems.
o Rich Standard Library - Python comes with several standard libraries that provide
ready-to-use modules and functions for various tasks, ranging from web
development and data manipulation to machine learning and networking.
o Open Source - Python is an open-source, cost-free programming language. It is utilized
in several sectors and disciplines as a result.
Python Code:
Java Code:
For example -
def func():
statement 1
statement 2
…………………
…………………
statement N
In the above example, the statements that are the same level to the right belong to the function.
Generally, we can use four whitespaces to define indentation.
Instead of Semicolon as used in other languages, Python ends its statements with a NewLine
character.
Python is a case-sensitive language, which means that uppercase and lowercase letters are treated
differently. For example, 'name' and 'Name' are two different variables in Python.
In Python, comments can be added using the '#' symbol. Any text written after the '#' symbol is
considered a comment and is ignored by the interpreter. This trick is useful for adding notes to
the code or temporarily disabling a code block. It also helps in understanding the code better by
some other developers.
'If', 'otherwise', 'for', 'while', 'try', 'except', and 'finally' are a few reserved keywords in Python
that cannot be used as variable names. These terms are used in the language for particular
History of Python
Python was created by Guido van Rossum. In the late 1980s, Guido van Rossum, a Dutch
programmer, began working on Python while at the Centrum Wiskunde& Informatica (CWI) in
the Netherlands. He wanted to create a successor to the ABC programming language that
would be easy to read and efficient.
In February 1991, the first public version of Python, version 0.9.0, was released. This
marked the official birth of Python as an open-source project. The language was named after
the British comedy series "Monty Python's Flying Circus".
Python development has gone through several stages. In January 1994, Python 1.0 was
released as a usable and stable programming language. This version included many of the
features that are still present in Python today.
From the 1990s to the 2000s, Python gained popularity for its simplicity, readability, and
versatility. In October 2000, Python 2.0 was released. Python 2.0 introduced list
comprehensions, garbage collection, and support for Unicode.
In December 2008, Python 3.0 was released. Python 3.0 introduced several backward-
incompatible changes to improve code readability and maintainability.
The Python Software Foundation (PSF) was established in 2001 to promote, protect, and
advance the Python programming language and its community.
Python provides many useful features to the programmer. These features make it the most
popular and widely used language. We have listed below few-essential features of Python.
o Easy to use and Learn: Python has a simple and easy-to-understand syntax, unlike
traditional languages like C, C++, Java, etc., making it easy for beginners to learn.
o Expressive Language: It allows programmers to express complex concepts in just a few
lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing rapid
development and testing. It uses Interpreter instead of Compiler.
Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.
Just type in the following code after you start the interpreter.
print("STEFFY")
# Scripts Ends
Output:
STEFFY
Line 1: [# Script Begins] In Python, comments begin with a #. This statement is ignored by the
interpreter and serves as documentation for our code.
Line 2: [print(“STEFFY”)] To print something on the console, print() function is used. This
function also adds a newline after our message is printed(unlike in C). Note that in Python 2,
“print” is not a function but a keyword and therefore can be used without parentheses. However,
in Python 3, it is a function and must be invoked with parentheses.
Python designed by Guido van Rossum at CWI has become a widely used general-purpose, high-
level programming language.
Python vs JAVA
Python Java
No need to declare anything. An All variable names (along with their types)
assignment statement binds a must be explicitly declared. Attempting to
name to an object, and the object assign an object of the wrong type to a
can be of any type. variable name triggers a type exception.
No type casting is required Type casting is required when using
when using container objects container objects.
Uses Indentation for structuring code Uses braces for structuring code
Java Code
publicclass HelloWorld
[Link]("Hello, world!");
Python Code
print("Hello, world!")
Objects:
Definition
Characteristics:
1. Attributes:
o Objects store data in the form of attributes (variables associated with the object).
o Example: A Car object might have color and speed as attributes.
2. Methods:
o Functions defined within a class and associated with an object.
o Example: A Car object might have a method start().
Example
class Car:
def __init__(self, color, speed):
[Link] = color
[Link] = speed
def start(self):
print("Car started")
# Create an object
my_car = Car("red", 120)
print(my_car.color) # Access attribute
my_car.start() # Call method
Expressions
Numerical Types
1. Integers (int):
o Whole numbers, positive or negative, without decimals.
o Example: 10, -5
2. Floating-Point Numbers (float):
o Numbers with decimal points or in exponential form.
o Example: 3.14, 1e-3
3. Complex Numbers (complex):
o Numbers with a real and imaginary part.
o Example: 3 + 4j
4. Boolean (bool):
o A subtype of integers representing True (1) or False (0).
Variables
Variables are used to store data values and act as references to objects in memory.
No need to declare variables explicitly with a type; Python infers the type based on the
assigned value.
Assignments
x = 10
PREPARED BY:[Link] MACWAN
9
name = "Alice"
Multiple Assignments
a, b, c = 1, 2, 3
x = y = z = 0
Dynamic Typing
Variables can hold values of any type and can be reassigned to different types:
x = 10 # Integer
x = "Hello" # String
Important Notes
Example
x = 5 # Integer
y = 3.14 # Float
name = "John" # String
is_valid = True # Boolean
print(x, y, name, is_valid)
IDLE :
What is IDLE?
Key Features
1. Interactive Shell:
o A REPL (Read-Eval-Print Loop) environment for executing Python commands
interactively.
o Useful for testing small code snippets.
PREPARED BY:[Link] MACWAN
10
2. Code Editor:
o Provides a text editor for writing and saving Python scripts with syntax
highlighting and auto-indentation.
o Supports .py file creation and execution.
3. Debugging Tools:
o Includes a built-in debugger with features like setting breakpoints and stepping
through code.
4. Output Window:
o Displays program outputs, errors, and debugging information in a separate
window.
5. Cross-Platform:
o Runs on Windows, macOS, and Linux.
Advantages
Limitations
Lacks advanced features like those found in more robust IDEs (e.g., PyCharm, VS Code).
Example
1. Open IDLE.
2. Write a script in the editor:
print("Hello, World!")
3. Save the file as [Link] and run it using Run -> Run Module or F5.
Branching Programs :
Definition
Branching in Python allows a program to make decisions and execute different blocks of
code based on conditions.
Achieved using conditional statements like if, elif, and else.
1. if Statement:
o Executes a block of code if a condition is True.
o Syntax:
if condition:
# Code to execute if condition is True
o Example:
age = 18
if age >= 18:
print("You are an adult.")
2. if-else Statement:
o Provides an alternative block of code if the condition is False.
o Syntax:
if condition:
# Code if condition is True
else:
# Code if condition is False
o Example:
num = 5
if num % 2 == 0:
print("Even")
else:
print("Odd")
3. if-elif-else Ladder:
o Handles multiple conditions by checking them in sequence.
o Syntax:
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if none of the above conditions are True
o Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
else:
PREPARED BY:[Link] MACWAN
12
print("Grade: C")
Nested Branching
num = 10
if num > 0:
if num % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
else:
print("Non-positive number")
Branching programs enable dynamic decision-making and are fundamental to writing logical and
interactive programs in Python.
Strings in Python
A string is a sequence of characters enclosed in single ( '), double ("), or triple quotes
(''' or """`).
Strings are immutable, meaning their content cannot be changed after creation.
String Operations
1. Concatenation:
o Combine two or more strings using the + operator.
o Example:
2. Repetition:
text = "Python"
print(text[0]) # First character
print(text[-1]) # Last character
print(text[1:4]) # Substring from index 1 to 3
4. String Methods:
o Examples:
lower(), upper(): Convert case.
strip(): Remove whitespace.
replace(): Replace parts of a string.
split(): Split into a list.
join(): Join elements of a list into a string.
String Formatting
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
2. format() Method:
Input in Python
Converting Input
Multiline Strings
message = """This is
a multiline
string."""
print(message)
Strings and input handling are essential for interacting with users and manipulating text in
Python.
Iteration :
Definition
Iteration refers to the process of repeatedly executing a block of code. In Python, iteration is
commonly performed using loops. Python provides two primary types of loops: for and while.
1. for Loop
The for loop iterates over a sequence (such as a list, tuple, string, or range).
Syntax:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
range() Function:
o Commonly used in for loops to generate a sequence of numbers.
o Syntax: range(start, stop, step)
o Example:
2. while Loop
while condition:
# Code to execute as long as condition is True
count = 1
while count <= 5:
print(count)
count += 1
List comprehensions allow you to create lists based on existing lists or sequences in a
compact and readable way.
Syntax:
Example:
for i in range(10):
for i in range(5):
if i == 2:
continue # Skip when i equals 2
print(i)
for i in range(5):
pass # Does nothing but prevents an error
Example:
for num in range(1, 10): # Loop through numbers from 1 to 9
if num == 5:
break # Stop the loop entirely when num is 5
elif num % 2 == 0:
continue # Skip even numbers
elif num == 3:
pass # Do nothing (placeholder), and move to the next
iteration
print(num)
Output
1
3
Output Explanation:
Tuples :
Definition
Creating Tuples
single_element_tuple = (5,)
Negative Indexing
Slicing
Immutability
Tuples are immutable, meaning once a tuple is created, its elements cannot be changed.
Example:
my_tuple = (1, 2, 3)
# This will raise an error:
# my_tuple[1] = 4
Tuple Operations
tuple1 = (1, 2)
tuple2 = (3, 4)
result = tuple1 + tuple2
print(result) # Output: (1, 2, 3, 4)
tuple1 = (1, 2)
result = tuple1 * 3
print(result) # Output: (1, 2, 1, 2, 1, 2)
my_tuple = (1, 2, 3)
print(2 in my_tuple) # Output: True
print(4 not in my_tuple) # Output: True
my_tuple = (1, 2, 3)
print(len(my_tuple)) # Output: 3
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
Nested Tuples
Tuples can contain other tuples, which allows for creating complex structures.
Data Integrity: Use tuples when you need to ensure data remains constant and protected
from modification.
PREPARED BY:[Link] MACWAN
19
Efficiency: Tuples are faster than lists because of their immutability.
Multiple Return Values: Functions often return tuples to provide multiple values.
# Accessing elements
x, y = coordinates
print(f"x = {x}, y = {y}")
Ranges :
Definition
A range is an immutable sequence of numbers, commonly used in for loops for iteration.
The range() function in Python generates a sequence of numbers, which can be
specified using a start, stop, and step value.
start: The number where the sequence starts (inclusive). Defaults to 0 if not provided.
stop: The number where the sequence ends (exclusive). This argument is required.
step: The difference between each number in the sequence. Defaults to 1 if not provided.
Creating a Range
r = range(5)
print(list(r)) # Output: [0, 1, 2, 3, 4]
r = range(2, 6)
print(list(r)) # Output: [2, 3, 4, 5]
r = range(0, 10, 2)
print(list(r)) # Output: [0, 2, 4, 6, 8]
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
The range() function returns a special range object, which is not a list but can be
converted into a list or iterated over directly.
r = range(5)
print(type(r)) # Output: <class 'range'>
You can convert a range object into a list or tuple for easier manipulation.
r = range(5)
print(list(r)) # Output: [0, 1, 2, 3, 4]
print(tuple(r)) # Output: (0, 1, 2, 3, 4)
Memory Efficiency
Since a range object is immutable and generates the numbers on-demand (lazy
evaluation), it is more memory efficient than creating a list of numbers, especially for
large ranges.
Range Examples
1. Basic Range:
r = range(1, 5)
print(list(r)) # Output: [1, 2, 3, 4]
r = range(0, 10, 3)
print(list(r)) # Output: [0, 3, 6, 9]
r = range(10, 0, -1)
print(list(r)) # Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Common Purpose
Iterating over indices: When you need to iterate over a range of indices, such as when
looping through a list or array.
Important Notes
range() is not inclusive of the stop value, meaning it generates values starting from
start but stops before stop.
A range() object is often used with for loops because it generates the sequence of
numbers dynamically, without storing them in memory all at once.
Definition of a List
Creating Lists
Negative Indexing
Negative indexing allows you to access list elements starting from the end. -1 refers to
the last element, -2 refers to the second last element, and so on.
Modifying Lists
Lists are mutable, meaning you can modify, add, or remove elements.
1. Changing an element:
my_list[0] = 10
print(my_list) # Output: [10, 2, 3, "apple"]
2. Adding elements:
o Use append() to add an element at the end.
my_list.append(5)
print(my_list) # Output: [10, 2, 3, "apple", 5]
my_list.insert(1, "orange")
print(my_list) # Output: [10, "orange", 2, 3, "apple", 5]
3. Removing elements:
o Use remove() to remove an element by value.
my_list.remove(3)
print(my_list) # Output: [10, "orange", 2, "apple", 5]
my_list.clear()
List Mutability
The mutability of lists allows you to change their content (add, remove, modify
elements) after creation.
Example of mutability:
my_list = [1, 2, 3]
my_list[0] = 10 # List content is changed
print(my_list) # Output: [10, 2, 3]
Cloning Lists
original_list = [1, 2, 3]
copied_list = original_list.copy()
copied_list[0] = 10
print(original_list) # Output: [1, 2, 3]
print(copied_list) # Output: [10, 2, 3]
2. Using slicing:
original_list = [1, 2, 3]
copied_list = original_list[:]
copied_list[0] = 10
print(original_list) # Output: [1, 2, 3]
print(copied_list) # Output: [10, 2, 3]
original_list = [1, 2, 3]
copied_list = list(original_list)
copied_list[0] = 10
print(original_list) # Output: [1, 2, 3]
print(copied_list) # Output: [10, 2, 3]
List Comprehension
List comprehension provides a concise way to create lists. It can replace the need for a
for loop and is often used for filtering or modifying elements.
PREPARED BY:[Link] MACWAN
24
Syntax:
Basic Example:
With Condition:
o You can add an if condition to filter elements.
Strings :
Definition
Creating Strings
A string can be created using either single quotes (') or double quotes (").
multiline_string = '''This is a
multiline string.'''
Strings are indexed, starting from 0. You can access individual characters using the
index.
my_string = "Hello"
print(my_string[0]) # Output: H
print(my_string[4]) # Output: o
print(my_string[-1]) # Output: o
Slicing a string gives a substring using the format string[start:end], where end is
exclusive.
substring = my_string[1:4]
print(substring) # Output: ell
String Operations
2. Repetition: You can repeat a string multiple times using the * operator.
repeated_string = "Hello" * 3
print(repeated_string) # Output: HelloHelloHello
my_string = "Python"
print(len(my_string)) # Output: 6
String Methods
6. split(): Splits the string into a list based on the specified delimiter.
7. join(): Joins the elements of an iterable into a single string, using a specified separator.
print("Hello".find("e")) # Output: 1
print("Hello".find("a")) # Output: -1
10. isalpha(): Returns True if the string contains only alphabetic characters.
String Formatting
name = "Alice"
age = 30
greeting = "Hello, my name is %s and I am %d years old." % (name, age)
print(greeting) # Output: Hello, my name is Alice and I am 30 years
old.
2. [Link]() method:
Escape Characters
print("Hello\nWorld") # Output:
# Hello
# World
Strings are immutable in Python, meaning their contents cannot be changed after
creation.
my_string = "Hello"
# This will raise an error:
# my_string[0] = "h"
Storing text data: Strings are commonly used to store text, such as names, addresses,
and descriptions.
Processing text: Many text manipulation tasks such as searching, replacing, and
formatting data use strings.
User input: Strings are often used to process user input, either from the keyboard or from
files.
Overview
Tuples and Lists are both sequences used to store collections of data in Python, but they have
distinct differences in their properties and usage.
Tuples
Creating a Tuple
my_tuple = (1, 2, 3, "apple", 4.5)
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: apple
Tuple Properties
Immutability: You cannot modify, add, or remove elements once the tuple is created.
Concatenation and Repetition: Tuples support concatenation (+) and repetition (*).
repeated_tuple = my_tuple * 2
print(repeated_tuple) # Output: (1, 2, 3, 'apple', 4.5, 1, 2, 3,
'apple', 4.5)
Tuple Methods
my_tuple = (1, 2, 3, 1, 4, 1)
print(my_tuple.count(1)) # Output: 3
print(my_tuple.index(3)) # Output: 2
Immutability: Tuples are often used for data that should not change, such as fixed configuration
values or function return values.
Performance: Since tuples are immutable, they are generally faster than lists for iteration and
access.
Hashable: Tuples can be used as keys in dictionaries (lists cannot).
Lists
Creating a List
my_list = [1, 2, 3, "apple", 4.5]
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: apple
List Properties
print(len(my_list)) # Output: 5
Concatenation and Repetition: Lists support concatenation (+) and repetition (*).
repeated_list = my_list * 2
print(repeated_list) # Output: [10, 2, 3, 'apple', 4.5, 10, 2, 3,
'apple', 4.5]
List Methods
my_list.append(5)
print(my_list) # Output: [10, 2, 3, 'apple', 4.5, 5]
my_list.insert(2, "orange")
print(my_list) # Output: [10, 2, 'orange', 3, 'apple', 4.5, 5]
my_list.remove("apple")
print(my_list) # Output: [10, 2, 'orange', 3, 4.5, 5]
removed_element = my_list.pop(1)
print(removed_element) # Output: 2
print(my_list) # Output: [10, 'orange', 3, 'apple', 4.5, 5]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 'apple', 4.5]
my_list.reverse()
print(my_list) # Output: [4.5, 'apple', 3, 2, 1]
Mutable Collections: Lists are ideal for data collections that may change over time, such as
inventories, to-do lists, or any sequence that may require modification.
Dynamic Data: Lists are used when the data size is unknown or needs to be altered, such as
appending elements or removing items.
Syntax () []
Hashable Yes (can be used as dictionary keys) No (cannot be used as dictionary keys)
Dictionaries :
Definition
Creating a Dictionary
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York"
}
You can also use the get() method to access a value. It returns None if the key doesn't
exist (instead of raising an error).
Modifying a Dictionary
Adding new key-value pairs: You can add new entries by assigning a value to a new
key.
my_dict["email"] = "alice@[Link]"
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'email':
'alice@[Link]'}
Updating values: You can update the value associated with an existing key.
my_dict["age"] = 31
print(my_dict)
# Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'email':
'alice@[Link]'}
Removing items: You can remove key-value pairs using del or pop().
o del: Removes a key-value pair by specifying the key.
o pop(): Removes a key-value pair and returns the value associated with the key.
email = my_dict.pop("email")
print(email) # Output: alice@[Link]
print(my_dict) # Output: {'name': 'Alice', 'age': 31}
Dictionary Methods
4. update(): Updates the dictionary with key-value pairs from another dictionary or
iterable of key-value pairs.
my_dict.clear()
print(my_dict) # Output: {}
Dictionary Properties
1. Mutable: You can add, remove, or change the contents of a dictionary after it is created.
2. Unordered: Dictionaries do not store the items in a particular order (although from
Python 3.7 onward, they maintain insertion order, but this should not be relied upon in all
cases).
3. Key Uniqueness: Each key must be unique in a dictionary. If you try to add a duplicate
key, the existing value for that key will be updated.
Dictionaries can be nested, meaning a dictionary can contain other dictionaries as values.
student_info = {
"name": "Alice",
"age": 21,
"courses": {
"math": 90,
"english": 85
}
}
print(student_info["courses"]["math"]) # Output: 90
Dictionary Comprehension
Similar to list comprehension, you can create dictionaries using a compact syntax.
1. Storing key-value pairs: Dictionaries are ideal for storing data where each piece of
information has a unique identifier (e.g., storing user details by their username).
2. Fast lookups: Since dictionaries are implemented as hash maps, they allow for fast
lookups by key, making them efficient for scenarios where quick retrieval is important.
3. Mapping relationships: Dictionaries are often used to map relationships between keys
and values, such as employee ID to employee details or product ID to product
information.