python programming
python programming
Python is a versatile, high-level, interpreted programming language known for its readability and ease of
use.
It was created by Guido van Rossum and first released in 1991.
Python is widely used in various fields, including web development, data analysis, artificial intelligence,
and more.
Python is a powerful and flexible language that can help you solve a wide range of problems.
Whether you’re a beginner or an experienced developer, there’s always something new to learn!
1. Readability : Python’s syntax is designed to be clear and concise, making it easy to read and write.
2. Versatility : It supports multiple programming paradigms, including procedural, object-oriented, and
functional programming.
3. Extensive Libraries : Python has a vast ecosystem of libraries and frameworks, such as NumPy,
Pandas, Django, and TensorFlow.
4. Interpreted Language : Python code is executed line by line, which makes debugging easier.
5. Cross-Platform : Python can run on various operating systems, including Windows, macOS, and
Linux.
1. Installation : You can download Python from the official website python.org. It’s recommended to
install the latest stable version.
2. Interactive Shell : You can run Python in an interactive shell by typing python or python3 in your
terminal or command prompt.
3. Integrated Development Environment (IDE) : Tools like PyCharm, VS Code, or Jupyter Notebooks
can make writing and running Python code more convenient.
Practical Applications
Learning Resources
1. Easy to Learn and Use : Python has a simple and readable syntax, making it beginner-friendly and
easy to understand.
2. Extensive Libraries and Frameworks : Python has a vast collection of libraries (e.g., NumPy,
Pandas, TensorFlow) that simplify development in various domains like data science, machine
learning, and web development.
3. Cross-Platform Compatibility : Python is platform-independent, meaning code written in Python can
run on multiple operating systems (Windows, macOS, Linux) without modification.
4. Strong Community Support : Python has a large and active community, providing extensive
documentation, tutorials, and open-source support.
5. Versatility and Flexibility : Python can be used for web development, automation, artificial
intelligence, data science, game development, and more.
6. Rapid Development and Prototyping : Python's concise syntax allows developers to quickly
prototype and build applications, reducing development time.
7. Integration Capabilities : Python can easily integrate with other languages like C, C++, Java,
and .NET, making it useful for mixed-language projects.
8. Dynamically Typed : Variables in Python do not require explicit declaration, reducing the complexity
of coding.
9. Robust Data Science and AI Support : Python is the preferred language for AI, machine learning,
and data science due to libraries like TensorFlow, PyTorch, and Scikit-learn.
10. Automation and Scripting : Python is widely used for scripting and automation, helping automate
repetitive tasks efficiently.
1. Slow Execution Speed : Python is an interpreted language, which makes it slower compared to
compiled languages like C or C++.
2. High Memory Consumption : Python's dynamic memory allocation and garbage collection can lead
to higher memory usage, making it inefficient for memory-intensive tasks.
3. Global Interpreter Lock (GIL) : The GIL restricts Python to executing only one thread at a time,
limiting its performance in multi-threaded applications.
4. Weak in Mobile Development : Python is not commonly used for mobile app development due to its
higher memory consumption and slow execution speed.
5. Limited Support for Low-Level Programming : Unlike C or C++, Python is not well-suited for low-
level system programming, such as writing operating systems or device drivers.
6. Dependency on Third-Party Modules : While Python has a vast library ecosystem, many
functionalities rely on third-party modules, which can introduce compatibility issues.
7. Not Ideal for Real-Time Applications : Python's slow execution and garbage collection make it less
suitable for real-time applications that require precise timing.
8. Version Compatibility Issues : Some libraries and applications may face compatibility problems when
transitioning between Python 2.x and 3.x versions.
9. Security Concerns : Python is considered less secure compared to languages like Java, as it allows
dynamic typing and execution of arbitrary code, making it vulnerable to security threats.
10. Difficult to Optimize for Performance : Since Python is dynamically typed, optimizing code for
performance can be challenging compared to statically typed languages.
1. Sequential Execution : Code runs from top to bottom, following a logical flow.
2. Functions/Procedures : Code is divided into reusable functions that perform specific tasks.
3. Variables and Data Types : Data is stored and manipulated using variables.
4. Control Structures : Includes loops (for, while) and conditionals (if-else) to control execution flow.
5. Modularity : Code is organized into functions to improve readability and reusability.
In Python, data types define the kind of data a variable can hold. Here are the main built-in data types in
Python:
1. Numeric Types
2. Sequence Types
3. Set Types
4. Dictionary Type
5. Boolean Type
Can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
Cannot start with a digit (e.g., 1var ❌).
Cannot use Python keywords as identifiers (e.g., def = 10 ❌).
Case-sensitive (var and Var are different).
Cannot contain special characters like @, #, $, %, &, etc.
No spaces allowed (use _ instead, e.g., my_variable).
Keywords : Keywords are reserved words in Python that have special meanings and cannot be used as
identifiers.
Keywords Description
and This is a logical operator which returns true if both the operands are true else returns false.
or This is also a logical operator which returns true if anyone operand is true else returns false.
not This is again a logical operator it returns True if the operand is false else returns false.
Elif is a condition statement used with an if statement. The elif statement is executed if the
elif
previous conditions were not true.
Else is used with if and elif conditional statements. The else block is executed if the given
else
condition is not true.
assert This function is used for debugging purposes. Usually used to check the correctness of code
Finally is used with exceptions, a block of code that will be executed no matter if there is an
finally
exception or not.
in It’s used to check whether a value is present in a list, range, tuple, etc.
This is a special constant used to denote a null value or avoid. It’s important to remember, 0, any
none
empty container(e.g empty list) do not compute to None
In Python, the term "integral types" can be interpreted in two different contexts:
1. Integral Data Types : These are data types used to represent whole numbers without decimal points. In
Python, the primary integral data type is int, which represents integer numbers. Integers can be positive,
negative, or zero and have no limit on their size, except for the amount of available memory.
2. Integral Calculations : If you are referring to performing integral calculations (such as definite or
indefinite integrals) in Python, you can use libraries like SciPy for numerical integration and SymPy for
symbolic integration
In Python, floating-point numbers (or floats) represent numbers with decimal points or numbers in scientific
notation.
Used to represent real numbers (both positive and negative) with decimals.
Stored in 64-bit double precision (like C’s double).
Supports scientific notation.
Examples:
x = 10.5 # Float number
y = -3.14 # Negative float
z = 1.5e3 # Scientific notation (1.5 × 10³ = 1500.0)
print(x, y, z)
# Output: 10.5 -3.14 1500.0
Examples:
pos_inf = float('inf')
neg_inf = float('-inf')
not_a_number = float('nan')
a = 5.5
b = 2.2
Floating-point arithmetic can have precision errors due to how numbers are stored in memory.
Strings in Python
A string in Python is a sequence of characters enclosed in single ('), double ("), or triple (''' or """) quotes.
s1 = 'Hello'
s2 = "Python"
s3 = '''Multiline
String'''
print(s1, s2, s3)
1. Comparing Strings
Operator Meaning
== Equal to
!= Not equal to
Syntax: string[start:end:step]
Parameter Meaning
3. String Operators
Concatenation (+)
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # "Hello World"
Repetition (*)
4. String Methods
Method Description
Python provides four main built-in collection data types to store and manipulate groups of data:
1. Tuples (tuple)
Characteristics:
Ordered
Immutable (cannot be changed after creation)
Allows duplicate values
Creating a Tuple
Accessing Elements
Tuple Methods
Characteristics:
✅ Ordered
✅ Mutable (can be changed)
✅ Allows duplicate values
Creating a List
Accessing Elements
print(my_list[1]) # 20
print(my_list[-1]) # 3.14
Modifying a List
List Methods
Characteristics:
❌ Unordered
✅ Mutable
❌ No duplicate values
Creating a Set
my_set = {1, 2, 3, 3, 4, 5}
print(my_set) # {1, 2, 3, 4, 5} (duplicates removed)
Set Operations
A = {1, 2, 3}
B = {3, 4, 5}
Characteristics:
✅ Key-value pairs
✅ Mutable
❌ No duplicate keys
Creating a Dictionary
print(person["name"]) # Alice
person["age"] = 26 # Update value
person["gender"] = "Female" # Add new key-value pair
del person["city"] # Remove key
Dictionary Methods
unique_numbers = {1, 2, 3}
for num in unique_numbers:
print(num)
Copying a List
list1 = [1, 2, 3]
list2 = list1.copy() # Creates a new copy
list1.append(4)
print(list1) # [1, 2, 3, 4]
print(list2) # [1, 2, 3] (unchanged)
Copying a Dictionary
Copying a Set
set1 = {1, 2, 3}
set2 = set1.copy()
set1.add(4)
print(set1) # {1, 2, 3, 4}
print(set2) # {1, 2, 3} (unchanged)
Summary Table
Dictionary (dict) ✅ Yes (Python 3.7+) ✅ Yes ❌ No (Keys must be unique) {"name": "Alice", "age": 25}
UNIT – 2
Control structures
Control structures in Python are essential for directing the flow of execution in a program.
They allow you to make decisions, repeat actions, and manage the overall logic of your code.
Here’s a breakdown of the main control structures in Python:
1. Conditional Statements
Conditional statements let you execute different blocks of code based on certain conditions.
If Statement
age = 18
If-Else Statement
age = 16
else:
If-Elif-Else Statement
age = 20
else:
2. Loops
For Loop
print(fruit)
You can also use the range() function to iterate a specific number of times:
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
While Loop
count = 0
print(count)
3. Control Statements
Break Statement
for i in range(10):
if i == 5:
break
print(i) # Output: 0, 1, 2, 3, 4
Continue Statement
Skips the current iteration and moves to the next iteration of the loop:
for i in range(5):
if i == 2:
continue
print(i) # Output: 0, 1, 3, 4
Pass Statement
for i in range(5):
if i == 2:
pass # Placeholder
print(i) # Output: 0, 1, 2, 3, 4
Custom Functions
In Python, custom functions are user-defined functions that allow you to structure your code, promote
reusability, and improve readability.
These functions are created using the def keyword.
A function is defined using the def keyword, followed by the function name and parentheses. It may include
parameters (optional) and a return statement.
def greet(name):
"""This function greets the user with a custom message."""
return f"Hello, {name}!"
2. Calling a Function
You call a function by using its name followed by parentheses, passing arguments if needed.
result = add(5, 3)
print(result) # Output: 8
4. Default Parameters
5. Keyword Arguments
You can specify arguments using keywords, making the order irrelevant.
describe_pet(name="Buddy", animal="dog")
# Output: I have a dog named Buddy.
def sum_all(*numbers):
"""Returns the sum of all numbers provided."""
return sum(numbers)
def display_info(**info):
"""Displays key-value pairs of user information."""
for key, value in info.items():
print(f"{key}: {value}")
def get_square_and_cube(num):
return num**2, num**3
square = lambda x: x ** 2
print(square(5)) # Output: 25
add = lambda a, b: a + b
print(add(3, 4)) # Output: 7
def double_numbers(numbers):
return [num * 2 for num in numbers]
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Python provides several built-in modules that help with different functionalities.
Here's a brief overview of some commonly used modules:
The random module is used for generating random numbers, selecting random elements, and shuffling
sequences.
Examples:
import random
The math module provides mathematical functions such as square root, logarithms, trigonometry, and more.
Examples:
import math
Examples:
import time
The os module allows interaction with the operating system, such as file and directory operations.
Examples:
import os
The shutil module helps with file and directory operations like copying and moving files.
Examples:
import shutil
Examples:
import sys
Examples:
import glob
8. re (Regular Expressions)
Examples:
import re
The statistics module provides functions for mean, median, mode, etc.
Examples:
import statistics
data = [1, 2, 3, 4, 5, 5, 6]
A module in Python is simply a file containing Python code (functions, classes, or variables) that can be
reused in multiple programs. Custom modules allow you to organize your code into separate files for better
readability and reusability.
Create a new Python file (e.g., mymodule.py) and define functions or variables inside it.
# mymodule.py
def greet(name):
"""Returns a greeting message."""
return f"Hello, {name}!"
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
PI = 3.14159 # A constant
After creating the module, you can import and use it in another script.
# main.py
import mymodule # Import the custom module
Instead of importing the whole module, you can import specific functions or variables.
import mymodule as mm
# mymodule.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Alice")) # This will only run if executed directly
Now, if mymodule.py is run directly, it will print "Hello, Alice!", but if imported, this block won’t execute.
6. Creating a Package (Multiple Modules)
mypackage/
│── __init__.py
│── mymodule.py
│── anothermodule.py
If your module is not in the same directory, you can install it using sys.path.
import sys
sys.path.append("path/to/your/module")
import mymodule
A keyword refers to a predefined word that python Python Identifiers are the different values that a
1 reserves for working programs that have a specific programmer can use to define various variables,
meaning, You can’t use a keyword anywhere else. integers, functions, and classes.
An identifier can identify a single entity (a
2 A keyword can specify the type of entity.
variable, a class, or a function).
A few examples of Python keywords are: True, False, A few examples of identifiers are testing, sq4
7
else, import, finally, is, and global sides, area_square, etc.
Python Keywords
The Python keywords act as the building blocks of a python program. These words have a specific meaning
and can’t be used for other purposes. The keywords will always be available to a programmer for coding. You
need not import them. To get a list of the Python reserved words, follow the below process-
Syntax:
>>> help(“keywords”)
Output:
Here is a list of the Python keywords. Enter any keyword to get any more help
Python Identifiers
A python identifier is a name given to various entities like variables, functions, and classes. It helps a
programmer to distinguish one entity from another entity. Below are a few rules to be kept in mind while
naming an identifier-
1) An identifier can be a composition of alphabets (a-z) and numbers (0-9). The alphabets can be in uppercase
or lowercase. An underscore can also be used in an identifier. However, we must note that Python is a case-
sensitive language. Hence, “testing” will not be the same as “Testing”.
2) You cannot start an identifier with a number. Thus, 2square will be an invalid Python identifier. However,
square2 will be a valid identifier.
3) You cannot use reserved keywords as Identifiers. Thus, “break” will be an invalid identifier.
An invalid identifier
Source: Self
4) You can use ‘_’ as a special character in the naming of a variable. However, there is a restriction on the use
of other special characters like ‘&’, and ‘@’, and ‘!’.
Source: Self
In Python, integral types refer to data types that represent whole numbers. The primary integral type in Python
is int. Let's break down some key points about Python's integral types:
1. int
In Python 3, the int type can represent arbitrarily large integers. This is different from many other
languages where integers are of fixed size (e.g., 32-bit or 64-bit).
The int type is used to store both positive and negative whole numbers, including zero.
There is no need to declare a specific type (like short, long, or int) in Python, as the int type
dynamically expands to accommodate very large numbers.
x = 42 # Positive integer
z=0 # Zero
3. Arithmetic Operations
a = 10
b=3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a % b) # 1 (remainder)
4. Type Conversion
You can convert other types (like strings or floats) to integers using the int() constructor.
s = "100"
f = 12.34
5. Boolean Context
In Python, int values can be used in boolean contexts where 0 is considered False and any non-zero integer is
considered True.
if 42:
Float () Syntax
Every inbuilt function in the python programming language has a predefined objective and a syntax. The term
syntax refers to how a particular function needs to be used or called. In the below line, we can learn more
about the syntax of the float() function in the python programming language.
Where X is an input parameter passed to the function when it is called in the program.
Float () Parameters
One of the salient features of the python programming language is that it has rich predefined libraries with
numerous methods defined in it. We can use them by just calling the function. While a function is being called,
the necessary syntax must be followed and suitable parameters must be passed to the function. Here the term
parameters refer to the input arguments given to the method by the user. In the next lines, let us understand
more about the parameter of the float() function.
Here, the variable X is called the parameter to that function. X can be a normal integer value or any string that
has decimal points. An interesting fact about the float() is that the parameter is optional.
Python programming language has many inbuilt libraries and functions. One among them is the float()
function. With the help of the float() function, we can convert an input string or an integer value to a floating
point value. We already knew that it is not mandatory to send a parameter to the float(), in such a case the
function returns 0.0 as output. On another side, the float() function returns the corresponding floating-point
value when an integer or string with decimals is given as an input argument. If any input value is out of range
of floating value in python, then it returns OverflowError.
Difference Between List and Dictionary in Python
Both of these are tools used in the Python language, but there is a crucial difference between List and
Dictionary in Python. A list refers to a collection of various index value pairs like that in the case of an array in
C++. A dictionary refers to a hashed structure of various pairs of keys and values. In this article, we will
discuss the same in a tabular form. But let us first know a bit more about each of these individually.
A list is just like an array, but its declaration occurs in other languages. The lists don’t always need to be
homogenous. Thus, it becomes the most powerful tool in the case of the Python language. A single list may
consist of various DataTypes, such as Strings, Integers, and also Objects. The Lists are always mutable. Thus,
we can alter it even after we create it.
What is a Dictionary in Python?
A dictionary, on the other hand, refers to an unordered collection of the data values that we use for storing the
data values, such as a map. Unlike the other DataTypes, which are capable of holding only a single value in the
form of an element, a Dictionary is capable of holding the key:value pair. In a Dictionary, a colon separates all
the key-value pairs from each other, while a comma separates all the keys from each other.
Here are the differences present between List and Dictionary in Python:
Mode of We can access the elements in a key We can access the elements present in a dictionary using
Accessing using indices. the key-values.
Order of The entered order of elements is We don’t have any guarantee of maintaining the order of
Elements always maintained. the available elements.