PYTHONE NOTES
PYTHONE NOTES
SCIENCE,THRISSUR
MODULE 1
introduction to Python
Python is a high-level, interpreted programming language known for its readability and
versatility. It's widely used in various domains, including web development, 1 data science,
machine learning, and automation. Python's simple syntax and extensive standard library
make it a popular choice for both beginners and experienced programmers.
Readability: Python's code is often described as "almost like plain English," making it
easy to learn and understand.
Interpreted: Python code is executed line by line, eliminating the need for
compilation.
Dynamically Typed: You don't have to declare variable types beforehand. Python
automatically infers the data type at runtime.
Cross-Platform Compatibility: Python code can run on various operating systems like
Windows, macOS, and Linux.
Extensive Standard Library: Python's standard library provides a rich set of modules
for tasks like file I/O, network programming, and data manipulation.
Community and Support: Python has a large and active community, offering extensive
documentation, tutorials, and forums.
IDLE (Python's Integrated Development Environment)
IDLE is a simple yet powerful IDE that comes bundled with Python. It provides features like
syntax highlighting, code completion, and debugging tools.
Python Interpreter
The Python interpreter is a program that reads and executes Python code. When you run a
Python script, the interpreter reads each line, translates it into machine code, and executes it.
Writing and Executing Python Scripts
1. Create a New File: Use a text editor like IDLE, Notepad++, or a code editor to create
a new file with a .py extension (e.g., hello.py).
2. Write Python Code: Inside the file, write your Python code, following the syntax and
rules of the language.
3. Run the Script: You can execute the script in two ways:
o Using the Command Line: Open your terminal or command prompt, navigate
to the directory where the script is saved, and type python hello.py.
o Using IDLE: Open the script in IDLE and click the "Run Module" button.
Comments in Python
Comments are used to explain code and improve its readability. They are ignored by the
interpreter.
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
Single-line comments: Start with a # symbol.
Python
# This is a single-line comment
Multi-line comments: Use triple quotes (''' or """).
Python
"""
This is a multi-line comment
that spans multiple lines.
"""
Identifiers in Python
Identifiers are names given to variables, functions, classes, and other objects in Python. They
must follow these rules:
Must start with a letter (a-z, A-Z) or an underscore (_).
Can contain letters, numbers, and underscores.
Case-sensitive (e.g., myVariable and myvariable are different).
Cannot be a keyword.
Keywords in Python
Keywords are reserved words with special meanings in Python. You cannot use them as
identifiers. Examples include if, else, for, while, def, class, etc.
Variables in Python
Variables are used to store data. You don't need to declare a variable's type; Python infers it
automatically.
Python
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
Data Types in Python
Python supports various data types:
Numbers:
o int: Integers (e.g., 10, -5, 0)
o float: Floating-point numbers (e.g., 3.14, 2.718)
o complex: Complex numbers (e.g., 2+3j)
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
String: A sequence of characters (e.g., "Hello, world!")
Boolean: True or False values
List: An ordered collection of items (e.g., [1, 2, 3])
Tuple: An immutable ordered collection of items (e.g., (1, 2, 3))
Set: An unordered collection of unique items (e.g., {1, 2, 3})
Dictionary: A collection of key-value pairs (e.g., {"name": "Alice", "age": 30})
MODULE 2:
Boolean Expressions
A Boolean expression is an expression that evaluates to either True or False. They are
fundamental to decision-making in programming.
Syntax:
Python
Boolean expression = condition1 and condition2 or condition3
Example:
Python
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
x = 10
y=5
# Boolean expressions
is_greater = x > y # True
is_equal = x == y # False
is_less_than = x < y # False
Simple if Statement
An if statement executes a block of code only if a certain condition is true.
Syntax:
Python
if condition:
# Code to be executed if the condition is True
Example:
Python
age = 18
if x > y:
if x > 20:
print("x is greater than 20")
else:
print("x is between 10 and 20")
Multi-Way Decisions
Multi-way decisions involve multiple conditions and corresponding actions.
Example:
Python
day = "Monday"
if day == "Monday":
print("Start the week!")
elif day == "Friday":
print("Weekend is near!")
elif day == "Saturday" or day == "Sunday":
print("Weekend!")
else:
print("Weekday")
Loops
Loops are used to repeatedly execute a block of code.
The while Statement
A while loop continues to execute as long as a given condition is true.
Syntax:
Python
while condition:
# Code to be executed
Example:
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
Python
count = 0
while count < 5:
print(count)
count += 1
Range Function
The range() function generates a sequence of numbers. It's commonly used with for loops.
Syntax:
Python
range(start, stop, step)
Example:
Python
for i in range(1, 11):
print(i)
The for Statement
A for loop iterates over a sequence of values.
Syntax:
Python
for variable in sequence:
# Code to be executed
Example:
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Nested Loops
Nested loops involve placing one loop inside another.
Example:
Python
for i in range(1, 4):
for j in range(1, 4):
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
print(i * j, end=" ")
print()
break and continue Statements
break: Exits the current loop.
continue: Skips the current iteration and moves to the next.
Example:
Python
for i in range(1, 11):
if i == 5:
break
print(i)
Infinite Loops
An infinite loop occurs when the condition of a while loop never becomes false.
Example:
Python
while True:
print("Infinite loop")
MODULE 3:
Functions
Functions are blocks of reusable code that perform specific tasks. They help in organizing
code, making it modular and easier to understand.
Syntax:
Python
def function_name(parameters):
"""Docstring: Description of the function"""
# Function body
return value # Optional
Built-in Functions
Python comes with a rich set of built-in functions. Here are some common ones:
Mathematical Functions:
o abs(x): Returns the absolute value of x.
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
o round(x, n): Rounds x to n decimal places.
o pow(x, y): Returns x raised to the power of y.
o min(x1, x2, ...): Returns the smallest value.
o max(x1, x2, ...): Returns the largest value.
Date and Time Functions:
o datetime.datetime.now(): Returns the current date and time.
o datetime.date.today(): Returns the current date.
o time.time(): Returns the current time in seconds since the Epoch.
Random Number Functions:
o random.randint(a, b): Returns a random integer between a and b (inclusive).
o random.random(): Returns a random float between 0.0 and 1.0.
o random.choice(sequence): Returns a random element from a sequence.
Writing User-Defined Functions
You can define your own functions to perform specific tasks.
Syntax:
Python
def my_function(parameter1, parameter2):
# Function body
return result
Example:
Python
def greet(name):
print("Hello, " + name + "!")
def double(x):
return x * 2
def square_and_double(x):
return double(square(x))
Return Statement
The return statement is used to return a value from a function.
Python
def add(x, y):
return x + y
def my_function():
print(global_var)
my_function() # Output: 10
Recursion
Recursion is a technique where a function calls itself directly or indirectly.
Python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
MODULE 4:
Strings
A string is a sequence of characters enclosed in single quotes (' ') or double quotes (" ").
Basic Operations:
Concatenation: Combining strings using the + operator.
Python
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # Output: Hello World
Indexing: Accessing individual characters using square brackets.
Python
str = "Python"
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
first_char = str[0] # Output: P
last_char = str[-1] # Output: n
Slicing: Extracting a substring using [start:end:step].
Python
str = "Python Programming"
substring = str[7:17] # Output: Programming
String Methods:
o len(str): Returns the length of the string.
o str.upper(): Converts the string to uppercase.
o str.lower(): Converts the string to lowercase.
o str.strip(): Removes leading and trailing whitespace.
o str.split(): Splits the string into a list of substrings.
o str.join(list): Joins elements of a list into a string.
Lists
A list is an ordered collection of items.
Creating a List:
Python
my_list = [1, 2, 3, "apple", "banana"]
Accessing Elements:
Python
first_element = my_list[0] # Output: 1
last_element = my_list[-1] # Output: banana
Updating Elements:
Python
my_list[2] = 4 # Update the third element
Deleting Elements:
Python
del my_list[1] # Delete the second element
Basic List Operations:
Concatenation: Combining two lists using the + operator.
Slicing: Extracting a portion of a list using [start:end:step].
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
List Methods:
o append(item): Adds an item to the end of the list.
o insert(index, item): Inserts an item at a specific index.
o remove(item): Removes the first occurrence of an item.
o pop(index): Removes and returns the item at a specific index.
o sort(): Sorts the list in ascending order.
o reverse(): Reverses the order of the list.
Tuples:
Tuples in Python
Tuples are ordered, immutable collections of items. They are similar to lists but with the key
difference that tuples cannot be modified once created.
Tuples are immutable, meaning their elements cannot be changed after creation.
They are often used to represent fixed data sets.
Tuples are efficient in terms of memory usage and performance.
They can be used as keys in dictionaries.
Creating a Tuple:
Tuples are defined using parentheses ().
Python
my_tuple = (1, 2, 3, "apple", "banana")
Accessing Elements:
You can access elements in a tuple using indexing, similar to lists:
Python
first_element = my_tuple[0] # Output: 1
last_element = my_tuple[-1] # Output: banana
Slicing Tuples:
You can extract a portion of a tuple using slicing:
Python
sub_tuple = my_tuple[1:4] # Output: (2, 3, 'apple')
Tuple Operations:
While tuples are immutable, you can perform certain operations on them:
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
Concatenation: Combining two tuples using the + operator:
Python
tuple1 = (1, 2)
tuple2 = (3, 4)
combined tuple = tuple1 + tuple2 # Output: (1, 2, 3, 4)
Repetition: Repeating a tuple using the * operator:
Python
repeated tuple = tuple1 * 3 # Output: (1, 2, 1, 2, 1, 2)
Membership Testing: Using the in and not in operators:
Python
if 2 in my tuple:
print("2 is in the tuple")
Length: Using the len() function:
Python
length = len(my tuple) # Output: 5
Dictionaries
A dictionary in Python is an unordered collection of key-value pairs. Each key is unique, and
it is used to access the corresponding value.
Dictionary keys must be unique and immutable (e.g., strings, numbers, tuples).
Dictionary values can be of any data type.
Dictionaries are highly flexible and useful for storing and organizing data.
They can be used to represent complex data structures.
Creating a Dictionary:
You can create a dictionary using curly braces {}:
Python
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
Accessing Values:
To access a value, use the key within square brackets:
Python
name = my_dict["name"] # Output: Alice
Adding or Updating Values:
You can add a new key-value pair or update an existing one:
Python
my_dict["country"] = "USA" # Add a new key-value pair
my_dict["age"] = 31 # Update an existing value
Removing Key-Value Pairs:
You can remove a key-value pair using the del keyword:
Python
del my_dict["city"]
Iterating Over a Dictionary:
You can iterate over the keys, values, or key-value pairs of a dictionary:
Python
for key in my_dict:
print(key, my_dict[key])
Sets
A set is an unordered collection of unique elements. It's used to store multiple items in a
single variable. Sets are defined using curly braces {}.
Sets are unordered, meaning the elements don't have a specific order.
Sets automatically eliminate duplicate elements.
Sets are mutable, meaning you can add or remove elements.
Set operations are efficient for performing mathematical set operations.
Sets are a powerful tool in Python for working with unique collections of elements. They are
often used for tasks like removing duplicates from a list, finding common elements between
two lists, and performing set operations.
Creating a Set:
Python
my_set = {1, 2, 3, "apple", "banana"}
Adding Elements:
You can add elements to a set using the add() method:
Python
my_set.add("cherry")
Removing Elements:
You can remove elements using the remove() or discard() methods:
Python
my_set.remove("apple") # Raises KeyError if 'apple' is not present
my_set.discard("orange") # Doesn't raise an error if 'orange' is not present
Set Operations:
Union: Combining two sets using the | operator or the union() method:
Python
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # Or union_set = set1.union(set2)
Intersection: Finding common elements using the & operator or the intersection()
method:
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
Python
intersection_set = set1 & set2 # Or intersection_set = set1.intersection(set2)
Difference: Finding elements in one set but not the other using the - operator or the
difference() method:
Python
difference_set = set1 - set2 # Or difference_set = set1.difference(set2)
Symmetric Difference: Finding elements in either set but not both using the ^
operator or the symmetric_difference() method:
Python
symmetric_difference_set = set1 ^ set2 # Or symmetric_difference_set =