Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

python programming

Python is a high-level, versatile programming language known for its readability and ease of use, created by Guido van Rossum in 1991. It supports various programming paradigms and has extensive libraries for applications in web development, data analysis, and machine learning. While Python offers advantages like ease of learning and strong community support, it also has disadvantages such as slower execution speed and high memory consumption.

Uploaded by

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

python programming

Python is a high-level, versatile programming language known for its readability and ease of use, created by Guido van Rossum in 1991. It supports various programming paradigms and has extensive libraries for applications in web development, data analysis, and machine learning. While Python offers advantages like ease of learning and strong community support, it also has disadvantages such as slower execution speed and high memory consumption.

Uploaded by

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

UNIT 1

 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!

Key Features of Python

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.

Getting Started with Python

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

1. Web Development : Frameworks like Django and Flask.


2. Data Analysis : Libraries like Pandas and NumPy.
3. Machine Learning : Libraries like TensorFlow and PyTorch.
4. Automation : Writing scripts to automate repetitive tasks.

Learning Resources

 Official Documentation : Python Docs


 Online Courses : Platforms like Coursera, edX, and Codecademy offer Python courses.
 Books : "Python Crash Course" by Eric Matthes and "Automate the Boring Stuff with Python" by Al
Sweigart.

Advantages Of Python Programming:

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.

Disadvantages Of Python Programming:

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.

Rapid Introduction to Procedural Programming

 Procedural Programming is a programming paradigm based on structured, step-by-step instructions


executed in sequence.
 It focuses on procedures (also known as functions or routines) to perform tasks.

Key Concepts of Procedural Programming

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.

Advantages of Procedural Programming

 Simple and Easy to Learn : Follows a clear, step-by-step approach.


 Reusability : Functions can be reused in different parts of the program.
 Better Debugging : Code is structured, making it easier to debug.
Disadvantages of Procedural Programming

 Limited Scalability : Hard to manage in large applications.


 Less Flexibility : Less effective for complex, real-world applications compared to Object-Oriented
Programming (OOP).

Data Types In Python Programming

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

 int (Integer) : Whole numbers, e.g., 10, -5


 float (Floating-Point) : Decimal numbers, e.g., 3.14, -0.99
 complex (Complex Numbers) : Numbers with real and imaginary parts, e.g., 3 + 4j

2. Sequence Types

 str (String) : Text enclosed in quotes, e.g., "Hello, World!"


 list : Ordered, mutable collection, e.g., [1, 2, 3, "Python"]
 tuple : Ordered, immutable collection, e.g., (10, 20, "AI")

3. Set Types

 set : Unordered collection of unique elements, e.g., {1, 2, 3, 4}

4. Dictionary Type

 dict (Dictionary) : Key-value pairs, e.g., {"name": "Alice", "age": 25}

5. Boolean Type

 bool : Represents True or False, e.g., is_python_fun = True

Identifiers and Keywords in Python


Identifiers : An identifier is the name used to identify variables, functions, classes, modules, or other objects
in Python.

Rules for Naming Identifiers:

 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).

Examples of Valid Identifiers:


name = "Alice"
_age = 25
totalAmount = 100
Examples of Invalid Identifiers:
1var = 10 # ❌ Starts with a digit
my-variable = 5 # ❌ Contains hyphen
class = "Python" # ❌ Uses a keyword

Keywords : Keywords are reserved words in Python that have special meanings and cannot be used as
identifiers.

List of Python Keywords

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.

if This is used to make a conditional statement.

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.

for This is used to create a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.


Keywords Description
pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a boolean value.

False This is also a boolean value.

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

assert This function is used for debugging purposes. Usually used to check the correctness of code

class It helps us to define a class.

continue It continues to the next iteration of a loop

del It deletes a reference to an object.

except Used with exceptions, what to do when an exception occurs

Finally is used with exceptions, a block of code that will be executed no matter if there is an
finally
exception or not.

from It is used to import specific parts of any module.

global This declares a global variable.

import This is used to import a module.

in It’s used to check whether a value is present in a list, range, tuple, etc.

is This is used to check if the two variables are equal or not.

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

nonlocal It’s declared a non-local variable.

raise This raises an exception.

yield It ends a function and returns a generator.

async It is used to create asynchronous coroutine.

await It releases the flow of control back to the event loop.

Example of Using Keywords Correctly:


if True:
print("Python is awesome!")
Example of Incorrect Use of Keywords:
def = 10 # ❌ 'def' is a reserved keyword

Integral Types In Python:

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

Floating-Point Types in Python

In Python, floating-point numbers (or floats) represent numbers with decimal points or numbers in scientific
notation.

1. float (Floating-Point Numbers)

 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

2. Special Float Values

Python provides special floating-point values:

 Infinity (inf): Represents an infinitely large number.


 Negative Infinity (-inf): Represents an infinitely small number.
 Not-a-Number (nan): Represents undefined values (e.g., 0/0).

Examples:
pos_inf = float('inf')
neg_inf = float('-inf')
not_a_number = float('nan')

print(pos_inf, neg_inf, not_a_number)


# Output: inf -inf nan

print(pos_inf > 1000000) # Output: True


print(not_a_number == not_a_number) # Output: False (NaN is not equal to itself)
3. Float Operations

Python allows basic arithmetic operations with floats:

a = 5.5
b = 2.2

print(a + b) # Addition → 7.7


print(a - b) # Subtraction → 3.3
print(a * b) # Multiplication → 12.1
print(a / b) # Division → 2.5
print(a // b) # Floor Division → 2.0
print(a ** b) # Exponentiation → 37.5

4. Type Checking and Conversion

 Use type() to check the type.


 Convert between int and float using float() and int().

print(type(3.14)) # Output: <class 'float'>


print(float(10)) # Output: 10.0
print(int(3.99)) # Output: 3 (Removes decimal part)

5. Rounding and Precision Issues

Floating-point arithmetic can have precision errors due to how numbers are stored in memory.

print(0.1 + 0.2) # Output: 0.30000000000000004

To fix precision issues, use the round() function:

print(round(0.1 + 0.2, 2)) # Output: 0.3

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

You can compare strings using comparison operators:

Operator Meaning

== Equal to

!= Not equal to

> Greater than (lexicographically)


Operator Meaning

< Less than

>= Greater than or equal to

<= Less than or equal to

print("apple" == "banana") # False


print("apple" < "banana") # True (lexicographically 'a' < 'b')
print("Python" != "Java") # True

2. Slicing and Striding Strings

Slicing (Extracting Substrings)

Syntax: string[start:end:step]

Parameter Meaning

start Start index (inclusive)

end End index (exclusive)

step Skips characters (default 1)

text = "Hello, Python!"


print(text[0:5]) # 'Hello' (Characters from index 0 to 4)
print(text[:5]) # 'Hello' (Same as above)
print(text[7:]) # 'Python!' (From index 7 to end)
print(text[-7:-1]) # 'Python' (Negative indexing)
print(text[::-1]) # '!nohtyP ,olleH' (Reversed string)

3. String Operators

Python provides several operators for working with strings.

Concatenation (+)

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # "Hello World"

Repetition (*)

print("Python! " * 3) # "Python! Python! Python! "

Membership (in and not in)

print("Py" in "Python") # True


print("Java" not in "Python") # True

String Length (len())


text = "Hello"
print(len(text)) # 5

4. String Methods

Python provides many built-in string methods.

Method Description

upper() Converts to uppercase

lower() Converts to lowercase

strip() Removes leading and trailing spaces

replace(old, new) Replaces a substring

find(substring) Returns index of first occurrence (-1 if not found)

split(delimiter) Splits into a list

join(iterable) Joins elements of an iterable with a string separator

text = " Python is awesome! "


print(text.upper()) # " PYTHON IS AWESOME! "
print(text.lower()) # " python is awesome! "
print(text.strip()) # "Python is awesome!"
print(text.replace("awesome", "great")) # " Python is great! "
print(text.find("is")) # 9
print(text.split()) # ['Python', 'is', 'awesome!']
print("-".join(["Hello", "Python"])) # "Hello-Python"

5. String Formatting with str.format()

Python’s str.format() method allows dynamic string formatting.

Collection Data Types In Python

Python provides four main built-in collection data types to store and manipulate groups of data:

 Tuple (tuple) → Immutable ordered collection


 List (list) → Mutable ordered collection
 Set (set) → Unordered collection of unique elements
 Dictionary (dict) → Collection of key-value pairs

1. Tuples (tuple)

A tuple is an immutable, ordered collection that allows duplicate values.

Characteristics:

 Ordered
 Immutable (cannot be changed after creation)
 Allows duplicate values

Creating a Tuple

my_tuple = (1, 2, 3, "Python", 3.14)


print(my_tuple) # (1, 2, 3, 'Python', 3.14)

Accessing Elements

print(my_tuple[0]) # 1 (First element)


print(my_tuple[-1]) # 3.14 (Last element)

Tuple Methods

print(my_tuple.count(3)) # Count occurrences of 3


print(my_tuple.index("Python")) # Find index of "Python"
2. Lists (list)

A list is a mutable, ordered collection that allows duplicate values.

Characteristics:

✅ Ordered
✅ Mutable (can be changed)
✅ Allows duplicate values

Creating a List

my_list = [10, 20, 30, "Python", 3.14]


print(my_list) # [10, 20, 30, 'Python', 3.14]

Accessing Elements

print(my_list[1]) # 20
print(my_list[-1]) # 3.14

Modifying a List

my_list[2] = 99 # Changing value at index 2


print(my_list) # [10, 20, 99, 'Python', 3.14]

List Methods

my_list.append(50) # Add element at the end


my_list.insert(1, 15) # Insert at index 1
my_list.remove(99) # Remove element
print(my_list.pop()) # Remove and return last element
print(len(my_list)) # Length of list
3. Sets (set)

A set is an unordered collection of unique elements.

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

my_set.add(6) # Add an element


my_set.remove(3) # Remove an element
print(2 in my_set) # True (Check if element exists)

Set Operations (Union, Intersection, Difference)

A = {1, 2, 3}
B = {3, 4, 5}

print(A | B) # Union → {1, 2, 3, 4, 5}


print(A & B) # Intersection → {3}
print(A - B) # Difference → {1, 2}
4. Dictionaries (dict)

A dictionary is a collection of key-value pairs.

Characteristics:

✅ Key-value pairs
✅ Mutable
❌ No duplicate keys

Creating a Dictionary

person = {"name": "Alice", "age": 25, "city": "New York"}


print(person) # {'name': 'Alice', 'age': 25, 'city': 'New York'}

Accessing and Modifying Values

print(person["name"]) # Alice
person["age"] = 26 # Update value
person["gender"] = "Female" # Add new key-value pair
del person["city"] # Remove key

Dictionary Methods

print(person.keys()) # Get all keys


print(person.values()) # Get all values
print(person.items()) # Get all key-value pairs
5. Iterating Over Collections

Iterating Over a List


fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Iterating Over a Tuple

numbers = (10, 20, 30)


for num in numbers:
print(num)

Iterating Over a Set

unique_numbers = {1, 2, 3}
for num in unique_numbers:
print(num)

Iterating Over a Dictionary

person = {"name": "Alice", "age": 25, "city": "New York"}


for key, value in person.items():
print(key, ":", value)
6. Copying Collections

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

dict1 = {"a": 1, "b": 2}


dict2 = dict1.copy()
dict1["c"] = 3
print(dict1) # {'a': 1, 'b': 2, 'c': 3}
print(dict2) # {'a': 1, 'b': 2} (unchanged)

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

Collection Type Ordered Mutable Duplicates Allowed Example

Tuple (tuple) ✅ Yes ❌ No ✅ Yes (10, 20, 30)


Collection Type Ordered Mutable Duplicates Allowed Example

List (list) ✅ Yes ✅ Yes ✅ Yes [1, 2, 3, 4]

Set (set) ❌ No ✅ Yes ❌ No {1, 2, 3}

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 age >= 18:

print("You are an adult.")

 If-Else Statement

age = 16

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.")

 If-Elif-Else Statement

age = 20

if age < 13:

print("You are a child.")

elif age < 18:

print("You are a teenager.")

else:

print("You are an adult.")

2. Loops

Loops allow you to execute a block of code repeatedly.

 For Loop

Used to iterate over a sequence (like a list, tuple, or string):

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

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

Executes as long as a specified condition is true:

count = 0

while count < 5:

print(count)

count += 1 # Increment count to avoid infinite loop

3. Control Statements

Control statements alter the flow of loops or conditionals.

 Break Statement

Exits the nearest enclosing loop:

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

A null operation; it does nothing when executed. It can be useful as a placeholder:

for i in range(5):

if i == 2:

pass # Placeholder

print(i) # Output: 0, 1, 2, 3, 4

4. Nested Control Structures


You can nest control structures (e.g., loops inside loops, or if statements inside loops):

for i in range(3): # Outer loop: i takes values 0, 1, 2

for j in range(2): # Inner loop: j takes values 0, 1

print(f"i: {i}, j: {j}")

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.

1. Defining a Custom Function

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.

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

3. Function with Multiple Parameters

You can define a function with multiple parameters.

def add(a, b):


"""Returns the sum of two numbers."""
return a + b

result = add(5, 3)
print(result) # Output: 8

4. Default Parameters

You can set default values for parameters.

def power(base, exponent=2):


"""Calculates the power of a number."""
return base ** exponent

print(power(3)) # Output: 9 (3^2)


print(power(3, 3)) # Output: 27 (3^3)

5. Keyword Arguments
You can specify arguments using keywords, making the order irrelevant.

def describe_pet(animal, name):


print(f"I have a {animal} named {name}.")

describe_pet(name="Buddy", animal="dog")
# Output: I have a dog named Buddy.

6. Variable-Length Arguments (*args and **kwargs)

 *args allows a function to accept multiple positional arguments.


 **kwargs allows multiple keyword arguments.

def sum_all(*numbers):
"""Returns the sum of all numbers provided."""
return sum(numbers)

print(sum_all(1, 2, 3, 4)) # Output: 10

def display_info(**info):
"""Displays key-value pairs of user information."""
for key, value in info.items():
print(f"{key}: {value}")

display_info(name="Alice", age=25, city="New York")

7. Returning Multiple Values

A function can return multiple values as a tuple.

def get_square_and_cube(num):
return num**2, num**3

square, cube = get_square_and_cube(3)


print(square, cube) # Output: 9, 27

8. Lambda (Anonymous) Functions

Lambda functions are single-line, anonymous functions.

square = lambda x: x ** 2
print(square(5)) # Output: 25

add = lambda a, b: a + b
print(add(3, 4)) # Output: 7

9. Function with a List

Functions can process lists and return results.

def double_numbers(numbers):
return [num * 2 for num in numbers]

print(double_numbers([1, 2, 3, 4])) # Output: [2, 4, 6, 8]


10. Recursive Function

A function that calls itself (useful for factorials, Fibonacci, etc.).

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

print(factorial(5)) # Output: 120

Python Library Modules

 Python provides several built-in modules that help with different functionalities.
 Here's a brief overview of some commonly used modules:

1. random (Generating Random Data)

The random module is used for generating random numbers, selecting random elements, and shuffling
sequences.

Examples:

import random

print(random.randint(1, 10)) # Random integer between 1 and 10


print(random.random()) # Random float between 0 and 1
print(random.uniform(1, 10)) # Random float between 1 and 10
print(random.choice(["apple", "banana", "cherry"])) # Random choice
nums = [1, 2, 3, 4, 5]
random.shuffle(nums) # Shuffle list
print(nums)

2. math (Mathematical Functions)

The math module provides mathematical functions such as square root, logarithms, trigonometry, and more.

Examples:

import math

print(math.sqrt(25)) # Square root (Output: 5.0)


print(math.factorial(5)) # Factorial (Output: 120)
print(math.pi) # Value of π
print(math.e) # Value of Euler's number
print(math.sin(math.radians(30))) # Sine of 30 degrees

3. time (Time-Related Functions)

The time module provides functions to handle time-related tasks.

Examples:
import time

print(time.time()) # Current timestamp


time.sleep(2) # Pause execution for 2 seconds
print("Hello after 2 seconds!")

print(time.ctime()) # Current date and time

4. os (Operating System Interactions)

The os module allows interaction with the operating system, such as file and directory operations.

Examples:

import os

print(os.getcwd()) # Get current working directory


os.mkdir("new_folder") # Create a directory
os.rename("new_folder", "renamed_folder") # Rename folder
os.rmdir("renamed_folder") # Remove directory
print(os.listdir(".")) # List files in the current directory

5. shutil (File Operations)

The shutil module helps with file and directory operations like copying and moving files.

Examples:

import shutil

shutil.copy("source.txt", "destination.txt") # Copy file


shutil.move("source.txt", "new_location.txt") # Move file
shutil.rmtree("folder_to_delete") # Delete a directory and its contents

6. sys (System Functions and Arguments)

The sys module provides access to system-related information.

Examples:

import sys

print(sys.version) # Python version


print(sys.platform) # OS platform
sys.exit() # Exit program (used in scripts)

7. glob (Pattern Matching for File Names)

The glob module is used to find files based on patterns.

Examples:
import glob

print(glob.glob("*.py")) # List all Python files in the current directory


print(glob.glob("data/*.csv")) # List all CSV files in the 'data' folder

8. re (Regular Expressions)

The re module is used for pattern matching and string manipulation.

Examples:

import re

text = "My email is example@email.com"


match = re.search(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", text)
if match:
print(match.group()) # Output: example@email.com

9. statistics (Statistical Calculations)

The statistics module provides functions for mean, median, mode, etc.

Examples:

import statistics

data = [1, 2, 3, 4, 5, 5, 6]

print(statistics.mean(data)) # Average (mean)


print(statistics.median(data)) # Middle value (median)
print(statistics.mode(data)) # Most common value (mode)
print(statistics.stdev(data)) # Standard deviation

Creating a Custom Module in Python

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.

1. Creating a Custom Module

To create a module, follow these steps:

Step 1: Create a Python File

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

2. Importing the Custom Module

After creating the module, you can import and use it in another script.

Step 2: Create Another Python File (main.py)

In another file, import the module and use its functions.

# main.py
import mymodule # Import the custom module

print(mymodule.greet("Alice")) # Output: Hello, Alice!


print(mymodule.add(5, 3)) # Output: 8
print(mymodule.PI) # Output: 3.14159

3. Using from ... import

Instead of importing the whole module, you can import specific functions or variables.

from mymodule import greet, add

print(greet("Bob")) # Output: Hello, Bob!


print(add(10, 5)) # Output: 15

4. Using as to Rename a Module

You can assign a different name to the module using as.

import mymodule as mm

print(mm.greet("Charlie")) # Output: Hello, Charlie!

5. Checking if a Script is Run Directly (__name__ == "__main__")

To prevent code execution when the module is imported, use:

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

A package is a collection of modules inside a folder. To create a package:

1. Create a folder (e.g., mypackage/).


2. Inside the folder, create an empty __init__.py file (this makes it a package).
3. Add modules inside the folder (e.g., mymodule.py).

mypackage/
│── __init__.py
│── mymodule.py
│── anothermodule.py

4. Import from the package:

from mypackage import mymodule

print(mymodule.greet("David")) # Output: Hello, David!

7. Installing and Using Custom Modules

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

Difference between a Python Keyword and a Python Identifier

S.No Keyword Identifier

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

The first character can be a lowercase letter or


All the keywords except ‘True’, ‘False’, and ‘None’
3 an uppercase letter. However, an identifier can’t
start in lowercase letters.
start with a digit.

A variable can be in uppercase or lowercase


4 Keywords are generally in lower case.
letters.

An identifier can comprise alphabets, numbers,


5 Python Keywords comprise alphabetical characters.
and underscore.

No special character is used except underscore


6 There is no use of special characters.
(‘_’).

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

None break except in raise

False await else import pass

and continue for lambda try

True class finally is return

as def from nonlocal while

async elif if not with

assert del global or yield

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”.

Valid identifiers: testing, variable_1

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 ‘!’.

Valid Identifier: test_name

Invalid Identifier: abc@

The above identifier will be an invalid identifier

Source: Self

5) There is no restriction on the length of a Python identifier.

What are the integral types in python?

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

y = -999 # Negative integer

z=0 # Zero

large = 10**100 # Very large integer

2. Binary, Octal, and Hexadecimal Integers


 Python provides support for integers in different bases (binary, octal, hexadecimal). You can define
them using specific prefixes:
o Binary: Prefix with 0b or 0B
o Octal: Prefix with 0o or 0O
o Hexadecimal: Prefix with 0x or 0X

binary = 0b1010 # Binary (10 in decimal)

octal = 0o12 # Octal (10 in decimal)

hexadecimal = 0xA # Hexadecimal (10 in decimal)

3. Arithmetic Operations

Python int supports various arithmetic operations:

 Addition (+), Subtraction (-), Multiplication (*), Division (/)


 Floor division (//), Modulo (%), Exponentiation (**)

a = 10

b=3

print(a + b) # 13

print(a - b) # 7

print(a * b) # 30

print(a / b) # 3.333...

print(a // b) # 3 (floor division)

print(a % b) # 1 (remainder)

print(a ** b) # 1000 (a raised to the power of b)

4. Type Conversion

You can convert other types (like strings or floats) to integers using the int() constructor.

s = "100"

f = 12.34

print(int(s)) # 100 (string to int)

print(int(f)) # 12 (float to int, truncates the decimal part)

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:

print("This is True") # This will print


if 0:

print("This is False") # This won't print

How to Use the Python Float Function?


Python's float() function will convert any value into a decimal or fractional number. Basically, it converts
integers or real numbers into floating-point numbers.

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.

Syntax: The syntax of the inbuilt float() function: float(X)

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.

Calling float function: float(X)

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.

Float () Return Value

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.

What is a List in Python?

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.

Difference Between List and Dictionary in Python

Here are the differences present between List and Dictionary in Python:

Parameters List Dictionary

A list refers to a collection of various


A dictionary refers to a hashed structure of various pairs of
Basics index value pairs like that in the case
keys and values.
of an array in C++.

We can create a dictionary by placing all the available


We can create a list by placing all the
elements into a { } in the form of a key:vale. Here, we
Creation available elements into a [ ] and
have to separate each pair of available key-values using the
separating them using “,” commas.
“,” commas.

The indices in the case of a list are


The keys present in a dictionary can easily be of any given
Data Type basically integers that start from the
data type.
value 0.

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.

You might also like