0% found this document useful (0 votes)
20 views

PYTHONE NOTES

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

PYTHONE NOTES

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

PARAMEKKAVU COLLEGE OF ARTS AND

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

Operators are symbols used to perform operations on variables and values.


 Arithmetic Operators: +, -, *, /, // (floor division), % (modulo), ** (exponentiation)
 Comparison Operators: ==, !=, <, >, <=, >=
 Logical Operators: and, or, not
 Assignment Operators: =, +=, -=, *=, /=, %=, //=, **=
 Bitwise Operators: &, |, ^, ~, <<, >>
Operators in Python
Operators are symbols that perform specific operations on variables and values.
Python supports a variety of operators, categorized as follows:
1. Arithmetic Operators:
 Addition (+): Adds two numbers.
Python
x = 10
y=5
result = x + y # result will be 15
 Subtraction (-): Subtracts one number from another.
Python
x = 10
y=5
result = x - y # result will be 5
 Multiplication (*): Multiplies two numbers.
Python
x = 10
y=5
result = x * y # result will be 50
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
 Division (/): Divides one number by another.
Python
x = 10
y=5
result = x / y # result will be 2.0
 Floor Division (//): Divides two numbers and rounds down to the nearest integer.
Python
x = 10
y=3
result = x // y # result will be 3
 Modulo (%): Divides two numbers and returns the remainder.
Python
x = 10
y=3
result = x % y # result will be 1
 Exponentiation ():** Raises a number to a power.
Python
x=2
y=3
result = x ** y # result will be 8
2. Comparison Operators:
 Equal to (==): Checks if two values are equal.
 Not equal to (!=): Checks if two values are not equal.
 Greater than (>): Checks if one value is greater than another.
 Less than (<): Checks if one value is less than another.
 Greater than or equal to (>=): Checks if one value is greater than or equal to another.
 Less than or equal to (<=): Checks if one value is less than or equal to another.
3. Logical Operators:
 and: Returns True if both operands are True.
 or: Returns True if at least one operand is True.
 not: Inverts the truth value of an operand.
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
4. Assignment Operators:
 =: Assigns a value to a variable.
 +=: Adds a value to a variable and assigns the result to the variable.
 -=: Subtracts a value from a variable and assigns the result to the variable.
 *=: Multiplies a variable by a value and assigns the result to the variable.
 /=: Divides a variable by a value and assigns the result to the variable.
 %=: Calculates the modulo of a variable with a value and assigns the result to the
variable.
 //=: Performs floor division of a variable by a value and assigns the result to the
variable.
 **=: Exponentiates a variable by a value and assigns the result to the variable.
5. Bitwise Operators:
 & (Bitwise AND): Performs bitwise AND operation on two numbers.
 | (Bitwise OR): Performs bitwise OR operation on two numbers.
 ^ (Bitwise XOR): Performs bitwise XOR operation on two numbers.
 ~ (Bitwise NOT): Performs bitwise NOT operation on a number.
 << (Left Shift): Shifts the bits of a number to the left.
 >> (Right Shift): Shifts the bits of a number to the right.

Operator Precedence and Associativity


Operator precedence determines the order in which operations are performed. Associativity
determines the direction in which operations with the same precedence are grouped.
Statements and Expressions
 Statements: Instructions that perform actions.
 Expressions: Combinations of values, variables, and operators that evaluate to a value.
User Input
Use the input() function to get input from the user:
Python
name = input("Enter your name: ")
print("Hello, " + name)
Type Function
The type() function returns the data type of an object:
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
Python
x = 10
print(type(x)) # Output: <class 'int'>
Eval Function
Eval Function in Python
The eval() function in Python is a powerful yet potentially dangerous function that evaluates
a string as a Python expression. It takes a string as input and returns the result of evaluating
that string.
Syntax:
Python
eval(expression)
Parameters:
 expression: A string containing a valid Python expression.
Return Value:
The result of evaluating the expression. The type of the returned value depends on the
expression itself.
Example:
Python
expression = "2 + 3 * 4"
result = eval(expression)
print(result) # Output: 14
While eval() can be a useful tool, it's important to use it with caution. Here are some valid use
cases:
1. Evaluating Mathematical Expressions:
o You can use eval() to calculate complex mathematical expressions
dynamically.
o For example, you could create a calculator that takes input from the user as a
string and evaluates it using eval().
2. Dynamic Code Execution:
o In certain scenarios, you might need to execute code that is generated
dynamically.
o However, this should be done with extreme care, as it can introduce security
risks.
The eval() function is a powerful tool, but it should be used with caution. By understanding
its potential risks and following best practices, you can use it safely and effectively. In most
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
cases, it's recommended to explore safer alternatives like ast. _eval() or custom parsing
techniques.
Print Function
Print Function in Python
The print() function in Python is used to display output to the console. It's a versatile function
that can be used to print various data types, including strings, numbers, and even complex
objects.
EG:
Python
print("Hello, world!")
Printing Multiple Values:
You can print multiple values separated by commas within a single print() statement:
Python
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
he print() function is a core function in Python.
It's used to display output to the console.
You can print multiple values in a single print() statement.
String formatting can be used to customize the output.
F-strings provide a concise way to format strings.
The end parameter can be used to control the end-of-line behaviour.

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


print("You are an adult.")
if-elif-else Statement
An if-elif-else statement allows you to execute different blocks of code based on multiple
conditions.
Syntax:
Python
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition1 is False and condition2 is True
else:
# Code to be executed
if both conditions are False
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
Example:
Python
grade = 85

if grade >= 90:


print("Excellent!")
elif grade >= 80:
print("Very Good!")
else:
print("Good")
Compound Boolean Expressions
Compound Boolean expressions combine multiple conditions using logical operators (and, or,
not).
Syntax:
Python
if condition1 and condition2:
# Code to be executed if both conditions are True
if condition1 or condition2:
# Code to be executed if at least one condition is True
if not condition:
# Code to be executed if the condition is False
Example:
Python
age = 25
has_license = True

if age >= 18 and has_license:


print("You can drive.")
Nesting
Nesting refers to placing one control flow statement inside another.
Example:
Python
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
x = 10
y=5

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 + "!")

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


Function Composition
Function composition involves combining multiple functions to create a new function.
Example:
Python
def square(x):
return x * x
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR

def double(x):
return x * 2

def square_and_double(x):
return double(square(x))

result = square_and_double(3) # Output: 18


Parameters and Arguments
 Parameters: Variables defined in the function's definition.
 Arguments: Values passed to the function when it's called.
Default Parameters
You can specify default values for parameters:
Python
def greet(name="World"):
print("Hello, " + name + "!")

greet() # Output: Hello, World!


greet("Alice") # Output: Hello, Alice!
Function Calls
To call a function, use its name followed by parentheses:
Python
function_name(arguments)

Return Statement
The return statement is used to return a value from a function.
Python
def add(x, y):
return x + y

result = add(5, 3) # result will be 8


PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
Global Variables
Global variables can be accessed from anywhere in the program.
Python
global_var = 10

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)

result = factorial(5) # Output: 120

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

Basic Tuple Operations:


 Indexing and Slicing: Similar to lists.
 Tuple Methods:
o count(item): Counts the number of occurrences of an item.
o index(item): Returns the index of the first occurrence of an item.

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

for value in my_dict.values():


print(value)

for key, value in my_dict.items():


print(key, value)
Common Dictionary Methods:
 keys(): Returns a view of the dictionary's keys.
 values(): Returns a view of the dictionary's values.
 items(): Returns a view of the dictionary's key-value pairs.
 get(key, default): Returns the value for the key, or a default value if the key is not
found.
 pop(key): Removes and returns the value for the specified key.
PARAMEKKAVU COLLEGE OF ARTS AND
SCIENCE,THRISSUR
 clear(): Removes all items from the dictionary.

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 =

Basic Set Operations:


 Union: Combining two sets using the | operator.
 Intersection: Finding common elements using the & operator.
 Difference: Finding elements in one set but not the other using the - operator.
 Symmetric Difference: Finding elements in either set but not both using the ^
operator.
 Set Methods:
o add(item): Adds an item to the set.
o remove(item): Removes an item from the set.
o discard(item): Removes an item if it exists in the set.
o clear(): Removes all items from the set.

You might also like