0% found this document useful (0 votes)
7 views157 pages

1753873337-Module 1 - Python Fundamentals

The document provides an overview of Python fundamentals, including its syntax, data types, control flow, functions, and exception handling. It outlines learning objectives and outcomes, as well as the structure of Python programs and key concepts such as variables, lists, tuples, and dictionaries. Additionally, it emphasizes Python's versatility, ease of learning, and extensive libraries, making it suitable for various applications.

Uploaded by

Royal Piano
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)
7 views157 pages

1753873337-Module 1 - Python Fundamentals

The document provides an overview of Python fundamentals, including its syntax, data types, control flow, functions, and exception handling. It outlines learning objectives and outcomes, as well as the structure of Python programs and key concepts such as variables, lists, tuples, and dictionaries. Additionally, it emphasizes Python's versatility, ease of learning, and extensive libraries, making it suitable for various applications.

Uploaded by

Royal Piano
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

Python Fundamentals

Module - 1

Python
Fundamentals
Python Fundamentals

DISCLAIMER
The content is curated from online/offline resources and
used for educational purpose only.
Python Fundamentals

Learning Objectives
• Introduce Python’s syntax and structure, explaining key
programming concepts.
• Explain different data types and variables, demonstrating their
usage in Python programs.
• Teach control flow mechanisms, including conditional
statements and loops, for efficient program execution.
• Guide learners in creating and utilizing functions to improve
code modularity and reuse.
• Explain exception handling techniques and their importance in
writing robust code.
• Demonstrate file handling methods, enabling learners to read
from and write to files.
• Explore essential utilities in the Python Standard Library to
enhance coding efficiency
Source
[Link]
Python Fundamentals

Learning Outcome
By the end of this chapter, learners will be able to:
 Understand the fundamentals of Python, including its syntax and
structure.
 Identify and utilize different data types and variables for effective
programming.
 Implement control flow mechanisms such as conditional statements
and loops to manage program execution.
 Create and use functions to modularize and reuse code efficiently.
 Handle errors gracefully with exception handling techniques to
ensure robust code execution.
 Read from and write to files using file handling methods.
 Explore and utilize essential utilities from the Python Standard
Library to enhance coding efficiency.
Source
[Link]
Python Fundamentals

Content
• Introduction to Python
• Data Types & Variables
• Operators
• Control Flow (if-else, loops)
• Functions
• Modules & Packages
• Exception Handling
• File Handling
• Python Standard Library
Python Fundamentals

What is programming language ?


A programming language is a formal set of instructions that can be used to produce various kinds of output, such
as software programs, websites, and mobile apps. It provides the means for a programmer to communicate with a
computer, instructing it on how to perform specific tasks.

Source
[Link]
Python Fundamentals

Let's play this

Source
[Link]
Python Fundamentals

What is Python ?
Python is a general-purpose, dynamically typed, high-level, compiled and interpreted, garbage-collected, and
purely object-oriented programming language that supports procedural, object-oriented, and functional
programming.

Source
[Link]
Python Fundamentals

Why Python ?
Easy to learn and beginner-friendly
• Python's simple syntax and readability make it accessible for beginners, supporting a wide range of
applications, from simple scripts to complex projects.
Versatile with Extensive Libraries
• Python is used in diverse fields like web development, data science, and automation, with powerful
libraries such as NumPy, Pandas, and TensorFlow.
Interpreted and Interactive
• Python runs code at runtime without needing compilation, and its interactive mode allows for real-
time testing and rapid prototyping.
Strong Community and Cross-Platform Support
• Python has a vast community, extensive support, and works seamlessly on various platforms like
Windows, macOS, and Linux.
Python Fundamentals

What are Compilers and Interpreters? Why?

Source
[Link]
Python Fundamentals

Python Features
Python Fundamentals

Python History

Source
[Link]
Python Fundamentals

Python compatible IDE


Python Fundamentals

Basic syntax and structure


• Documentation section: Includes comments that
specify the aim of the program.
• Import statements: In-built or user-defined modules
in different modules.
• Global declaration section: Gobal variables for the
programs.
• Class section: Information about the user-defined
classes present
• Subprogram section: we define user-defined
functions.
• Playground section: Main section where we call
user-defined functions and class methods.
Python Fundamentals

Lab Activity

Lab 1.1 Installing Python and setting up the environment


just follow these steps:
1. Download Python Installer File
2. Install Python
3. Verify your installation
4. Install VS Code Editor
5. Run your python first program
Python Fundamentals

Use case of Python Applications


Python Fundamentals

Python keywords and identifiers


Python Keywords
Keywords are reserved words that have specific meanings and purposes.
Python Fundamentals

Print() Function
The print() function in Python is used to output text or other data types to the console. It’s highly
versatile and supports various formatting and options for displaying data.
Syntax

print(object(s), sep=separator, end=end, file=file, flush=flush)


Python Fundamentals

Lab Activity

Lab 1.2 Write a program with print function to print single and
Multiline text
Python Fundamentals

Comment Out a Block of Code in Python


Single-line Comments
# defining a single-line comment
print('Hello World!')

Multi-line Comments
"""
This is a multi-line comment
written in
more than just one line
"""
'''
This is another multi-line comment
written in
more than just one line
'''
print("Hello, World!")
Python Fundamentals

Lines and Indentation


Lines
Each line of code in Python represents a single statement
or instruction.
Indentation
• Indentation refers to the use of spaces and tabs at the
beginning of statements, methods, and code blocks.
• Proper indentation helps clearly identify the starting and
ending points of conditional loops, functions, if-else
statements, and other control structures.

Source
[Link]
Python Fundamentals

Python identifiers
An identifier is the name given to variables, functions,
classes, or other objects.
Rules for Naming Python Identifiers
• Python keywords cannot be used as identifiers.
• Whitespace is not allowed in identifiers.
• Identifiers may consist of uppercase letters (A-Z),
lowercase letters (a-z), digits (0-9), or underscores (_).
• It must begin with either an alphabetic character or an
underscore (_).
• Special characters, except for the underscore (_), are
not permitted in identifiers.
Python Fundamentals

Variables in Python
• Python variables are simply containers used to
store data values.
• A variable refers to a memory location where data
is stored, and the name of the variable is known as
an identifier.
• Python is a dynamically typed language, meaning it
can automatically infer the type of the variable
based on the assigned value.

Source
[Link]
Python Fundamentals

What is Python Literals


In Python, literals are fixed values that are directly represented in the source code.
They are used to define values for variables and constants. Python literals come in several types.
Python Fundamentals

Variables in Python
Assign Value to Multiple Variables:
• Python allows to assign values to multiple
variables in one line.
• You can also unpack a collection of values into
individual variables.
Python Fundamentals

Lab Activity

Lab 1.3 Creating Python Variables and Assigning values to Variables


Python Fundamentals

Data Types in Python


Python supports various data types to store different kinds of data.

Source
[Link]
Python Fundamentals

Numeric Data Type


• Represents data with a numeric value.
• Includes integers, floating numbers, and complex numbers.
• Integers (int class):
o Positive or negative whole numbers (no fractions or decimals).
o No limit to the length of an integer value in Python.
• Float (float class):
o Real numbers with floating-point representation.
o Specified by a decimal point.
o Can include scientific notation (e.g., e or E followed by an integer).
• Complex Numbers (complex class):
o Specified as (real part) + (imaginary part)j.
o Example: 2+3j.
Source
Python Data Types - GeeksforGeeks
Python Fundamentals

Numeric Data Types (Contd …)


Examples of Numeric Data Types:
• To identify the data types of variables in Python,
utilizing the type() function.
• It returns the data types of variables.
• The resulting output displays the specific data
type for each variable in Python.
Python Fundamentals

Boolean Data Type


• Represents one of two built-in values: True or
False.
• Represented by the bool class.
Note:
• Use capital T for True and capital F for False.
• Lowercase true and false will result in an error.
Python Fundamentals

Sequence Data Types


• Ordered collection of similar or different types of
data.
• Stores multiple values in an organized and
efficient manner.
• Types of sequence data types:
• String
• List
• Tuple

Source
Python Data Types - GeeksforGeeks
Python Fundamentals

Non-Sequence Data Types


• Non-sequential types are data structures that do not
store items in a specific order.
• Elements are not indexed and cannot access them Non- Sequence
using a position like in sequential types.
• Types of non-sequence data types:
• Dictionary
Dictionary Set
• Set
Python Fundamentals

Python List
A List is a Kind of Collection
• A collection allows us to put many values in a single
variable.
• A collection is nice because we can carry all many
values around in one convenient package.
Python Fundamentals

Python List
# Creating a list
# Removing elements from a list
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # Output: [10, 2, 4, 5, 6]
# Accessing elements of a list
print(my_list[0]) # Output: 1
print(my_list[-1]) # Output: 5 # Iterating over a list
print(my_list[2:4]) # Output: [3, 4] for item in my_list:
print(item)
# Modifying elements of a list
my_list[0] = 10 # Length of a list
print(my_list) # Output: [10, 2, 3, 4, 5] print(len(my_list)) # Output: 5

# Adding elements to a list


my_list.append(6)
print(my_list) # Output: [10, 2, 3, 4, 5, 6]
Python Fundamentals

Python Tuple
Tuple: an immutable sequence
• Very similar to a list
• Once it is created, it cannot be changed
• Format: tuple_name = (item1, item2)
• Tuples support operations as lists
• Subscript indexing for retrieving elements
• Methods such as index
• Built in functions such as len, min, max
• Slicing expressions
• The in, +, and * operators
Python Fundamentals

Python Tuple # Tuple packing and unpacking


x = 10
# Creating a tuple
y = 20
my_tuple = (1, 2, 3, 4, 5)
coordinates = (x, y) # Packing
print(coordinates) # Output: (10, 20)
# Accessing elements of a tuple
print(my_tuple[0]) # Output: 1
x, y = coordinates # Unpacking
print(my_tuple[-1]) # Output: 5
print(x:, x) # Output: x: 10
print(my_tuple[2:4]) # Output: (3, 4)
print(y:, y) # Output: y: 20

# Since tuples are immutable, modifying elements is # Iterating over a tuple


not allowed
for item in my_tuple:
# This will raise an error: TypeError: 'tuple' object
does not support item assignment print(item)

# my_tuple[0] = 10
# Length of a tuple
print(len(my_tuple)) # Output: 5
Python Fundamentals

Python String
• String is a sequence of characters.
• For example, "hello" is a string containing the
characters 'h', 'e', 'l', 'l', and 'o’.
Creating a String in Python
• String in Python can be easily created using single,
double, or even triple quotes.

Source
[Link]
Python Fundamentals

Accessing string element


• Use index values to access specific characters.
• Allowing access to elements from the end of the
string.
• To access a range of characters within a string.

Example:
greet = 'hello'
print(greet[1])
print(greet[-4])

Source
[Link]
Python Fundamentals

Iterating through a Python String


• Use a for loop to iterate through each character in
a string
Python Fundamentals

Python string operations


Slicing:
• Extracts portions of a string using start and end indices.
• Syntax: string[start:end].
• Includes start index, excludes end index.
• Supports negative indexing.
Deleting String:
• Able to delete the Python string completely
• Cannot remove or delete any character of the string
Python Fundamentals

Python string operations


Concatenation:
• Combines strings using +.
• Useful for creating new strings from existing ones.
Repetition:
• Repeats strings using *.
• Useful for creating repeated patterns.
Python Fundamentals

Python string operations


Compare two strings:
• Use the == operator to compare equality between
two strings.

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)
Python Fundamentals

Python Sets
A set is a collection of unique data, meaning that elements within a set cannot be duplicated.

Creating a Set Adding Elements to a Set

# Using curly braces # Add a single element


fruits = {apple, banana, cherry} [Link](orange)
print(fruits) print(fruits)

# Using set() function # Add multiple elements


numbers = set([1, 2, 3, 4, 5]) [Link]([mango, grape])
print(numbers) print(fruits)

Source
[Link]
Python Fundamentals

Python Sets Conti..... # Removing elements from a set


# Creating a set my_set.remove(3)
my_set = {1, 2, 3, 4, 5} print(my_set) # Output: {1, 2, 4, 5, 6, 7, 8, 9}

# Accessing elements of a set # Discarding elements from a set (no error if


element not present)
# Since sets are unordered, they do not support
indexing or slicing my_set.discard(10)
print(my_set) # Output: {1, 2, 4, 5, 6, 7, 8, 9}
# Adding elements to a set
my_set.add(6) # Iterating over a set
print(my_set) # Output: {1, 2, 3, 4, 5, 6} for item in my_set:
print(item)
# Adding multiple elements to a set
my_set.update({7, 8, 9}) # Length of a set
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9} print(len(my_set)) # Output: 8
Python Fundamentals

Python Sets Conti.....


# Checking for membership # Intersection of sets
print(5 in my_set) # Output: True intersection_set = [Link](set2)
print(10 in my_set) # Output: False print(intersection_set) # Output: {3, 4}

# Operations on sets # Difference of sets


set1 = {1, 2, 3, 4} difference_set = [Link](set2)
set2 = {3, 4, 5, 6} print(difference_set) # Output: {1, 2}

# Union of sets # Symmetric difference of sets


union_set = [Link](set2) symmetric_difference_set =
print(union_set) # Output: {1, 2, 3, 4, 5, 6} set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 5,
6}
Python Fundamentals

Python Dictionary
A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists and tuples,
each item in a dictionary is a key-value pair (consisting of a key and a value).
# creating a dictionary
country_capitals = {
Germany: Berlin,
Canada: Ottawa,
England: London
}

# printing the dictionary


print(country_capitals)

# Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}
Python Fundamentals

Python Dictionary
Creating a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

Accessing values in a dictionary using keys


print(my_dict['name']) # Output: John
print(my_dict['age']) # Output: 30
print(my_dict['city']) # Output: New York

Modifying values in a dictionary


my_dict['age'] = 35
print(my_dict) # Output: {'name': 'John', 'age':
35, 'city': 'New York'}

Adding new key-value pairs to a dictionary


my_dict['gender'] = 'Male'
print(my_dict) # Output: {'name': 'John', 'age':
35, 'city': 'New York', 'gender': 'Male'}
Python Fundamentals

Python Dictionary
Removing key-value pairs from a dictionary
del my_dict['city']
print(my_dict) # Output: {'name': 'John', 'age': 35, 'gender': 'Male'}
Iterating over a dictionary
for key, value in my_dict.items():
print(key, ':', value)
Length of a dictionary
print(len(my_dict)) # Output: 3

Checking for existence of keys in a dictionary


print('name' in my_dict) # Output: True
print('city' in my_dict) # Output: False

Getting list of keys or values from a dictionary


keys = my_dict.keys()
values = my_dict.values()
print(keys) # Output: dict_keys(['name', 'age', 'gender'])
print(values) # Output: dict_values(['John', 35, 'Male'])
Python Fundamentals

Lab Activity

Lab 1.4 Implementation of End-to-End List Operations


Lab [Link] of End-to-End String Operations
Lab 1.6 Implementation of End-to-End Set Operations
Lab 1.7 Implementation of End-to-End Dictionary Operations
Python Fundamentals

Type conversion techniques


Type conversion in Python involves changing the type
of a value to another type.
There are two types of conversion:
1. Implicit: Python automatically converts one data type
to another.
2. Explicit: The user manually converts one data type to
another using built-in functions.

Source
[Link]
Python Fundamentals

Implicit Type conversion


• Implicit conversion, also known as coercion.
• Python automatically converts one data type to
another without any explicit instruction from the
programmer.
• This happens when mixing different data types
in operations.
Python Fundamentals

Explicit Type conversion


• Explicit conversion is when the programmer manually
converts one data type to another using built-in
functions.
• Examples
• int(): Converts a value to an integer.
• float(): Converts a value to a float.
• str(): Converts a value to a string.
Python Fundamentals

Lab Activity

Lab 1.8 Implementation of Addition of string and integer Using Explicit Conversion
Python Fundamentals

Arithmetic Operators

Operator Description Example


+ Addition - Adds values on either side of the a + b will give 30
operator
- Subtraction - Subtracts right hand operand from a - b will give -10
left hand operand
* Multiplication - Multiplies values on either side of a * b will give 200
the operator
/ Division - Divides left hand operand by right hand b / a will give 2
operand
% Modulus - Divides left hand operand by right b % a will give 0
hand operand and returns remainder
** Exponent - Performs exponential (power) a**b will give 10 to the
calculation on operators power 20
// Floor Division - The division of operands where 9//2 is equal to 4 and
the result is the quotient in which the digits after 9.0//2.0 is equal to 4.0
the decimal point are removed.
Python Fundamentals

Comparison Operators
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then (a == b) is not true.
condition becomes true.
!= Checks if the value of two operands are equal or not, if values are (a != b) is true.
not equal then condition becomes true.
<> Checks if the value of two operands are equal or not, if values are (a <> b) is true. This is similar
not equal then condition becomes true. to != operator.
> Checks if the value of left operand is greater than the value of right (a > b) is not true.
operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right (a < b) is true.
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (a >= b) is not true.
value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value (a <= b) is true.
of right operand, if yes then condition becomes true.
Python Fundamentals

Assignment Operators
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to c = a + b will assigne
left side operand value of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand c += a is equivalent to c =
and assign the result to left operand c+a
-= Subtract AND assignment operator, It subtracts right operand from the c -= a is equivalent to c =
left operand and assign the result to left operand c-a
*= Multiply AND assignment operator, It multiplies right operand with the left c *= a is equivalent to c =
operand and assign the result to left operand c*a
/= Divide AND assignment operator, It divides left operand with the right c /= a is equivalent to c =
operand and assign the result to left operand c/a
%= Modulus AND assignment operator, It takes modulus using two c %= a is equivalent to c =
operands and assign the result to left operand c%a
**= Exponent AND assignment operator, Performs exponential (power) c **= a is equivalent to c =
calculation on operators and assign value to the left operand c ** a
//= Floor Division and assigns a value, Performs floor division on operators
Source c //= a is equivalent to c =
and assign value to the left operand c // a
Python Fundamentals

Logical operators

Operator Description Example

and Returns True if both statements x < 5 and x <


are true 10
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns False if not(x < 5 and x
the result is true < 10)
Python Fundamentals

Identity Operators

Operator Description Example


is Returns True if both variables are x is y
the same object

is not Returns True if both variables are x is not y


not the same object
Python Fundamentals

Membership Operators

Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object
Python Fundamentals

Bitwise Operators

Operator Name Description

& AND Sets each bit to 1 if both bits are 1


| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall off
shift

>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let the
shift rightmost bits fall off
Python Fundamentals

Operator Precedence
• Sequence in which operators are evaluated is Precedence Operator Description

determined by their varying levels of precedence. 1 () Parentheses (used for grouping)


2 ** Exponentiation
• Operators with greater precedence are evaluated
first. 3 +x, -x, ~x Unary plus, unary minus, bitwise NOT

• Operators have the same precedence, is 4 *, /, //, % Multiplication, division, floor division, modulus

determined by their associativity. 5 +, - Addition and subtraction


6 <<, >> Bitwise left shift, bitwise right shift
7 & Bitwise AND
8 ^ Bitwise XOR
9 ==, !=, >, <, >=, <= Comparison operators
10 is, is not, in, not in Identity and membership operators
11 not Logical NOT
12 and Logical AND
13 or Logical OR
14 if ... else Conditional expression
15 := Walrus operator (assignment expression)
Python Fundamentals

Lab Activity

Lab 1.9 Implementation of Comparison Operators in Python


Lab 1.10 Implementation of Logical Operators in Python
Python Fundamentals

User Input and Output


Input:
• The input() function is used to take input from the
user.
• It reads a line from the input (usually from the
keyboard) and returns it as a string.

Output:
• The print() function is used to output data to the
standard output (usually the screen).
Python Fundamentals

Input and Output


While programming, we might want to take the input from the user. In Python, we can use the input()
function.

Syntax of input()

input(prompt)

# using input() to take user input Output


num = input('Enter a number: ')

Enter a number: 10
print('You Entered:', num) You Entered: 10
Data type of num: <class 'str'>
print('Data type of num:', type(num))
Python Fundamentals

Formatted Output
Format strings in Python using various methods, including f-strings, the format() method, and
the % operator :

f-strings (available in Python 3.6+): format() method:

% operator
Python Fundamentals

Types of Control Flow Statements in Python


In Python, control flow statements allow you to direct the execution of code based on certain conditions.
Python Fundamentals

Conditional Statements in Python


Conditional statements in Python allow you to make decisions in your code based on specific
conditions. They check if a condition is True or False and execute code accordingly.

The main types of conditional statements in Python are:


1. if statement
2. if-else statement
3. if-elif-else statement
4. nested if statement
Python Fundamentals

Python if Statement
These conditional tasks can be achieved using the if statement

Syntax
if condition:
# body of if statement

Source
[Link]
Python Fundamentals

Python if...else Statement


An if statement can have an optional else clause.
The else statement executes only if the condition in the
if statement evaluates to False.

Syntax
if condition:
# body of if statement
else:
# body of else statement

Source
[Link]
Python Fundamentals

Python if…elif…else Statement


The if...else statement is used to execute a block of code
among two alternatives.

However, if we need to make a choice between more than two


alternatives, we use the if...elif...else statement.

Syntax

if condition1:
# code block 1

elif condition2:
# code block 2

else:
# code block 3

Source
[Link]
Python Fundamentals

Python Nested if Statements


It is possible to include an if statement inside another
if statement.

Source
[Link]
Python Fundamentals

Lab Activity

Lab 1.11 Implementation of conditional Statements


Python Fundamentals

Definition of Iteration
Iteration, in programming, is the process of repeating a set of instructions either for a specific number of times or
until a particular condition is satisfied.
This can be through the use of loops, which execute a block of code repeatedly as long as the condition holds
true.

Source
[Link]
Python Fundamentals

Importance of Iteration in Executing Repetitive Tasks


• Efficiency and Productivity
• Handling Large Data Sets
• Dynamic and Flexible Code
• Automation
• Algorithm Implementation
Python Fundamentals

For Loop
A for loop in Python is used for iterating over a sequence
(like a list, tuple, dictionary, set, or string) or any other
iterable object. It is the most common way to iterate
through elements in a collection.

Basic Syntax
for item in iterable:
# Code block to execute

Source
[Link]
Python Fundamentals

For Loop with range() in Python


The range() function in Python is often used in conjunction with for loops to generate a sequence of numbers.
This is useful when you want to iterate over a specific number of times or create a loop that uses numerical
indices.
Basic Syntax of range()
• start: The starting value of the sequence (inclusive). Defaults to 0 if not
range(stop) provided.
range(start, stop) • stop: The end value of the sequence (exclusive).
range(start, stop, step) • step: The difference between each number in the sequence. Defaults to 1 if
not provided
Python Fundamentals

For Loop with range() in Python


Example 1: Using range(stop) Example 2: Using range(start, stop)

for i in range(5): for i in range(2, 7):


print(i) print(i)

This loop prints numbers from 0 to 4. Here, range(5) This loop prints numbers from 2 to 6. Here, range(2, 7)
generates the sequence [0, 1, 2, 3, 4]. generates the sequence [2, 3, 4, 5, 6].

Example 3: Using range(start, stop, step):

for i in range(1, 10, 2):


print(i)

This loop prints numbers 1, 3, 5, 7, and 9. Here, range(1,


10, 2) generates the sequence [1, 3, 5, 7, 9].
Python Fundamentals

Nested For Loops


A nested for loop is a loop inside another loop. The inner loop is executed completely for each iteration of the
outer loop. Nested loops are useful for working with multi-dimensional data structures like matrices, grids, or
performing operations that require multiple levels of iteration.

Basic Syntax

for outer_item in outer_iterable:


for inner_item in inner_iterable:
# Code block to execute
Python Fundamentals

Nested For Loops


Example: Checking for Prime Numbers in a Range
Nested loops can be used to find prime numbers within a specified range.
for num in range(2, 20):
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a prime number")

This example checks each number in the range from 2 to 19 to see if it is a prime number and prints the result.
Python Fundamentals

While Loop
A while loop in Python repeatedly executes a block of code as
long as a specified condition is true. It is particularly useful
when the number of iterations is not known beforehand and
the loop needs to continue until a certain condition changes.
Basic Syntax
while condition:
# Code block to execute

Source
[Link]
Python Fundamentals

While Loop
Example 1: Basic While Loop Example 2: Using a While Loop with User Input

count = 0 user_input = ''


while count < 5: while user_input.lower() != 'quit':
print(count) user_input = input("Enter something (type 'quit' to stop): ")
count += 1 print(f"You entered: {user_input}")

In this example, the loop will execute as long as Here, the loop continues to prompt the user for input
the count is less than 5. With each iteration, the until the user types 'quit'. The input is printed back to
count is incremented by 1, and its value is printed. the user on each iteration.
Python Fundamentals

Control Flow and Termination: Break and Continue Statements


Break Statement Example: Using break in a while Loop
The break statement is used to exit the loop count = 0
prematurely. When a break statement is encountered
inside a loop, the loop is immediately terminated, and while count < 10:
the program control resumes at the next statement
following the loop. print(count)

Syntax count += 1

if count == 5:
break
break
Python Fundamentals

Transfer statements: Break and Continue Statements in Python


Example: Using break in a for Loop Example: Searching for an Item with break
for i in range(10):
items = ['apple', 'banana', 'cherry', 'date', 'elderberry']
if i == 6:
break for item in items:
print(i) if item == 'cherry':
print("Found the cherry!")
break
print(item)
Python Fundamentals

Break and Continue Statements in Python


Continue Statement Example: Using continue in a while Loop
The continue statement is used to skip the rest of the
code inside the current iteration of the loop and move to count = 0
the next iteration. When a continue statement is while count < 10:
encountered, the loop does not terminate but
immediately jumps to the next iteration. count += 1
Syntax if count % 2 == 0:
continue
continue
print(count)
In this example, the loop will print only odd
numbers from 1 to 9. The continue statement
skips the print statement for even numbers.
Python Fundamentals

Pass Statements in Python


Pass Statement
The pass statement is used as a placeholder in situations where you don't want to execute any code.
Python Fundamentals

Lab Activity

Lab 1.12 Implementation of iterative statements – for loop


Lab 1.13 Implementation of iterative statements - while loop
Lab 1.14 Write a Python program to get the Fibonacci series between given two numbers read by
user
Python Fundamentals

Function in Python
Functions are reusable blocks of code that perform specific tasks. They help organize code, make it easier
to understand, and reduce redundancy. Functions in Python are defined using the `def` keyword, followed
by a function name and parentheses.

Benefits of Using Functions


 Enhances Code Readability
 Promotes Code Reusability

Source
[Link]
Python Fundamentals

Type of Function in Python


1. Built-in Functions
These are functions that are pre-defined and provided by Python. You can use them directly without needing
to define them yourself.
Examples:
• print(): Outputs data to the console.
• len(): Returns the length of an object like a list, string, etc.
• type(): Returns the type of an object.

2. User-defined Functions
Functions that you define yourself to perform specific tasks.
Syntax:
def function_name(parameters):
#Function body
return value # (Optional)
Python Fundamentals

Function Definition
The python def keyword is used to define a function; it is placed before a function name that is provided by the user
to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements
indented under a name given using the “def” keyword.
def function_name(parameters):
"""docstring"""
statement(s)
return value
Here’s the definition of a simple function, hello
def hello():
"""This function says hello and greets you"""
print("Hello")
print("Glad to meet you")
Source
[Link]
Python Fundamentals

Calling a Function
Python Function Call code
def greet():

print('Hello World!')

# call the function

greet()

print('Outside function')
Once you have defined a function, you can call it in
your code as many times as you need. To call a
function in Python, you simply type the name of the
function followed by parentheses (). If the function
takes any arguments, they are included within the
parentheses.
Source
[Link]
Python Fundamentals

Python Function Arguments


# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)

# function call with two values


add_numbers(5, 4)

Source
[Link]
Python Fundamentals

The return Statement


# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:', square)

Source
[Link]
Python Fundamentals

The Pass Statement


What is the pass statement?
The pass statement in Python is a placeholder that does nothing when executed. It's used in situations
where a statement is syntactically required but no action needs to be taken.
Syntax:
def future_function():
pass
Example:
for i in range(5):
if i == 3:
pass # Do nothing when i equals 3
else:
print(i)
When writing code, you may plan to implement certain sections later. You can use pass to fill in these
sections temporarily without causing syntax errors.
Python Fundamentals

Python Function Parameters


Keyword Parameters
Positional Parameters
def greet(first_name, last_name):
def add(a, b): return f"Hello, {first_name} {last_name}!“
return a + b

result = greet(first_name="Jane", last_name="Doe")


result = add(3, 5)
print(result) # Output: Hello, Jane Doe!
print(result) # Output: 8

# Arguments can be passed in any order


result = greet(last_name="Smith", first_name="John")
print(result) # Output: Hello, John Smith!
Python Fundamentals

Python Function Parameters


Default Parameter Values

def greet(first_name, last_name="Doe"):


return f"Hello, {first_name} {last_name}!"

# Calling with one argument


result = greet("John")
print(result) # Output: Hello, John Doe!

# Calling with both arguments


result = greet("Jane", "Smith")
print(result) # Output: Hello, Jane Smith!
Python Fundamentals

Python Function Parameters


Combining Different Types of Parameters
def introduce(name, age=30, city="Unknown"):
return f"{name} is {age} years old and lives in {city}."

# Calling with only the mandatory parameter


result = introduce("Alice")
print(result) # Output: Alice is 30 years old and lives in Unknown.

# Calling with all parameters


result = introduce("Bob", 25, "New York")
print(result) # Output: Bob is 25 years old and lives in New York.

# Using keyword arguments


result = introduce(name="Charlie", city="San Francisco")
print(result) # Output: Charlie is 30 years old and lives in San Francisco.
Python Fundamentals

Python Function Parameters


Arbitrary Arguments
Python Arbitrary Arguments enable a function to accept
any number of positional arguments, meaning
arguments that do not have keywords and can vary in
length.
Two Methods:
• *args for positional arguments (Non Keyword)
• **kwargs for keyword arguments

Source
[Link]
Python Fundamentals

Scope and Lifetime of Variables in Python


Local Variables Global Variables

def my_function(): x = 20 # Global variable


x = 10 # Local variable
print(f"Inside function: x = {x}") def my_function():
print(f"Inside function: x = {x}")
my_function()
# print(x) # This would raise an error: NameError: name my_function()
'x' is not defined print(f"Outside function: x = {x}")
Python Fundamentals

Scope and Lifetime of Variables in Python Scope Resolution

Modifying Global Variables x = "global"

x = 20 # Global variable def outer_function():

def my_function(): x = "enclosing"

global x
x = 30 # Modify the global variable def inner_function():

print(f"Inside function: x = {x}") x = "local"


print(f"Inner function: x = {x}")

my_function()
print(f"Outside function: x = {x}") inner_function()
print(f"Outer function: x = {x}")

outer_function()
print(f"Global scope: x = {x}")
Python Fundamentals

Python Recursion
Definition: Recursion occurs when a function calls itself directly or indirectly as part of its execution.
Purpose:
• To solve problems that can be broken down into smaller, simpler sub-problems of the same type.
• To make the code more elegant and easier to understand for certain types of problems, such as tree
traversal, factorial calculation, and solving puzzles like the Tower of Hanoi.
Python Fundamentals

Examples Demonstrating Recursion


Factorial Calculation def factorial(n):
The factorial of a non-negative integer nnn is the # Base case: 0! = 1
product of all positive integers less than or equal to nnn. if n == 0:
It's defined as:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)

# Testing the function


print(factorial(5)) # Output: 120
print(factorial(0)) # Output: 1
Python Fundamentals

Examples Demonstrating Recursion


Fibonacci Sequence def fibonacci(n):
The Fibonacci sequence is a series of numbers where # Base cases: F(0) = 0, F(1) = 1
each number is the sum of the two preceding ones, if n == 0:
starting from 0 and 1. It's defined as:
return 0
elif n == 1:
return 1
# Recursive case: F(n) = F(n-1) + F(n-2)
else:
return fibonacci(n - 1) + fibonacci(n - 2)

# Testing the function


print(fibonacci(6)) # Output: 8
print(fibonacci(10)) # Output: 55
Python Fundamentals

Lab Activity

• Lab 1.15 Implementation of Python Function Arguments with different types


• Lab 1.16. Implementation of Factorial Calculation and Fibonacci Sequence using python
recursion function
Python Fundamentals

Python Modules
A module is a file with python code. The code can be in the form of variables, functions, or class defined. The
filename becomes the module name.

Source
[Link]
Python Fundamentals

Import Python Standard Library Modules


The Python standard library contains well over 200 modules. We can import a module according to our needs.

# import standard math module


import math

# use [Link] to get value of pi


print(The value of pi is, [Link])

# Python import with Renaming

# import module by renaming it


import math as m

print([Link])

# Output: 3.141592653589793

Source
[Link]
Python Fundamentals

Python from...import statement


# import only pi from math module
from math import pi

print(pi)

# Output: 3.141592653589793

# import all names from the standard module math


from math import *

print(The value of pi is, pi)


Python Fundamentals

Package Model Structure in Python Programming

Source
[Link]
Python Fundamentals

What is the main() function in Python?


Python offers other conventions to define the execution point. One of them is using the main() function and
the __name__ property of a python file.

Source
[Link]
Python Fundamentals

Lab Activity

• Lab 1.17 Creating new module and importing that module to execute for the simple
calculation in Python
Python Fundamentals

What is Exception in Python?


An exception means a problem or an abnormal
condition that stops a computer program from
processing information normally. In Python, an
exception is an object representing an error or an
abnormal condition that occurs at runtime and
interrupts (disrupts) the normal execution of the
program.

Source
[Link]
Python Fundamentals

Why should you use Exceptions?


• Error Handling Type of Error
• Separation of concerns
• Robustness
• Debugging
• Modularity
• Flow Control
Python Fundamentals

The try and except Block

Source
[Link]
Python Fundamentals

Common Exceptions
• Name Error • Type Error
• Index Error • Attribute Error
• Key Error • Arithmetic Error
• Value Error • Floating point error
• IO Error • Zero Division Error
• Import Error • File Exists Error
• Syntax Error • Permission Error
Python Fundamentals

Common Exceptions – Type Error


Python Fundamentals

Catching specific Exceptions


Catch specific exceptions using the try-except block to handle different types of errors.
Python Fundamentals

Catching specific Exceptions


Python Fundamentals

Custom Exceptions
Custom exceptions can be created by defining a new class that inherits from the built-in Exception class.
Python Fundamentals

The Else Clause

Source
[Link]
Python Fundamentals

The Else Clause - Example


The else block follows the except block and is executed only if the code in the try block completes successfully
without raising any exceptions.
Python Fundamentals

The Finally Clause

Source
[Link]
Python Fundamentals

The Finally Clause


The finally block should always execute after the try block, regardless of whether an exception was
raised or handled.
Python Fundamentals

Lab Activity

• Lab 1.18 Implementation of the handle specific exceptions in Python


• Lab 1.19 Implementation of Python Built-in Exceptions for various error conditions
Python Fundamentals

File Handling
• Store data for further use.
• Process of reading, writing, and manipulating files using
Python code.
• Allows you to interact with data stored on your
computer.

Source
[Link]
Python Fundamentals

Type of File and File path


• Text File: Text file usually we use to store character data. For
example, [Link]
• Binary File: The binary files are used to store binary data such
as images, video files, audio files, etc.
• A file path defines the location of a file or folder in the computer
system. There are two ways to specify a file path.
• Absolute path
• Relative path

Source
[Link]
Python Fundamentals

Flow of file handling


• Opening a file
• Reading / Writing
• Closing a file

Source
[Link]
Python Fundamentals

Opening and closing a File


• Opening a file is the fundamental step in every file type handling
a task.
• Files in Python can be opened with a built-in open() function.
Ideally, it takes two string arguments:
o Filename
o Mode

Syntax:

file = open(file name, access mode)


• Close the file to terminate access to the currently open file.
Syntax:
[Link]()

Source
[Link]
Python Fundamentals

Basic Concepts of File Handling in Python


• 'r' (Read): Opens a file for reading (default mode). The file pointer is placed at the beginning of the file.
• 'w' (Write): Opens a file for writing. If the file already exists, its content is overwritten. If the file doesn't exist,
a new one is created.
• 'a' (Append): Opens a file for appending. The file pointer is at the end of the file, and new content is added to
the end.
• 'b' (Binary): Opens a file in binary mode. Use 'rb', 'wb', or 'ab' for reading, writing, or appending in binary
mode.
• 'x' (Exclusive Creation): Creates a new file and opens it for writing. If the file already exists, the operation
fails.
• 't' (Text): Opens a file in text mode (default). Use 'rt', 'wt', or 'at' for reading, writing, or appending in text
mode.
Python Fundamentals

File Methods
To interact with files and their contents
Python Fundamentals

File operation – open and read data


To open and read the content
Python Fundamentals

File operation – open and write data


To write data into a file
Python Fundamentals

Binary File operation – open , write and read data


• To write and read data in a binary file
Python Fundamentals

with statement in Python


• with open('[Link]', 'r') as f:
• content = [Link]()
• When the block ends, the file is automatically closed, even if an
error occurs.
Python Fundamentals

CSV files – write and read data in CSV file


Python Fundamentals

Directory and Files Management


Directory and file management in Python involves
performing various operations like creating, renaming,
deleting directories and files, navigating through
directories, and handling files effectively. Python's
OS and shutil modules provide a robust set of tools to
manage these tasks.
Python Fundamentals

OS Module
Functions for interacting with the operating system
Functions:
• Managing the Current Working Directory
• Creating a Directory
• Listing out Files and Directories
• Deleting Directory or Files
Python Fundamentals

List Directories and Files in Python


• All files and sub-directories inside a directory can
be retrieved using the listdir() method.
• This method takes in a path and returns a list of
subdirectories and files in that path.
• If no path is specified, it returns the list of
subdirectories and files from the current working
directory.
Python Fundamentals

File Exceptions
• An error or unexpected condition that occurs while working with files in programming.
• It occurs when the program tries to perform operations like reading, writing, opening, or closing a file.
Common types of File exceptions:
• FileNotFoundError
• PermissionError
• EOFError (End of File Error)
• FileExistsError
Python Fundamentals

File Exceptions - example


Python Fundamentals

Lab Activity

• Lab 1.20 Implementation of the Basic Concepts of File Handling in


Python
• Lab 1.21 Implementation of Directory and Files Management in Python
Python Fundamentals

Python Standard Library


• The Python Standard Library is a comprehensive collection of built-in modules designed to facilitate a wide
range of programming tasks.
• It provides robust support for essential operations, including file I/O, system interfaces, networking, threading,
and much more, enabling developers to build powerful applications efficiently.
Essential Python Standard Library Modules
Python Fundamentals

Essential Python Standard Library Modules


Provides a way to interact with the operating system, including file and directory
os OS Interaction
management, process handling, and environment variables.
Gives access to variables and functions used or maintained by the Python
sys System Utilities interpreter. Useful for reading arguments, manipulating the path, and exiting
programs.
Offers an object-oriented approach to handle filesystem paths and operations,
pathlib File System Paths
replacing many [Link] functions.
Includes high-level file operations like copying, moving, and deleting files or
shutil File Operations
directories. Also supports archiving and disk usage statistics.
Provides access to basic mathematical functions like square roots, trigonometry,
math Mathematics
logarithms, and constants such as π and e.
Enables generation of pseudo-random numbers, shuffling, sampling, and selections
random Randomization
for simulations and games.
Implements fixed and floating-point arithmetic with exact precision, useful for financial
decimal Arithmetic (Precision)
and accounting applications.
Supports manipulation of dates, times, and timedeltas. Ideal for formatting,
datetime Date & Time
calculating, or scheduling tasks.
Works with time representations, sleep delays, timestamps, and conversions
time Time Access
between time formats.
Enables pattern matching and search/replace operations on text using Perl-like
re Regular Expressions
regular expressions.
Python Fundamentals

os Module: Operating System Interfaces

1
File & Directory
Management
Create, delete, list, and
navigate files/directories
cross-platform. 2
Process Control &
Env Variables
Manage running
3 processes and
System Info & Shell environment variables.
Commands
Retrieve OS details and
run external commands.
Python Fundamentals

sys Module: System Utilities

Interpreter Interaction
Provides direct access to variables and
functions managed by the Python interpreter.

Essential Functions
• [Link]: Access command-line arguments.
• [Link](): Terminate program execution.
• [Link]: Manage module search paths.

Runtime Information
Retrieve crucial details like the Python version
and platform specifics.
Python Fundamentals

math Module: Mathematical Functions


The math module provides access to common mathematical functions and constants, designed for working
with floating-point numbers. It's essential for various scientific and engineering computations.
Basic Operations Constants & Functions
Perform fundamental numerical calculations with
Utilize well-known mathematical constants and
precision.
trigonometric/logarithmic functions.
• sqrt(): Calculate the square root of a number.
• pi: The mathematical constant π ( 3.14159).
• ceil(): Round a number up to the nearest
integer. • e: The mathematical constant e (approximately
2.71828), the base of the natural logarithm.
• floor(): Round a number down to the nearest
integer. • sin(): Calculate the sine of an angle (in radians).
• pow(): Raise a number to a specified power. • cos(): Calculate the cosine of an angle (in radians).
• factorial(): Compute the factorial of a non- • tan(): Calculate the tangent of an angle (in radians).
negative integer. • log(): Compute the natural logarithm of a number.
Python Fundamentals

datetime Module: Date and Time

Current Date & Time


Access the current date and time effortlessly using
`[Link]()` for full timestamps or
`[Link]()` for just the date.

Time Durations
Calculate and represent precise time differences and
durations with `[Link]`, perfect for adding or
subtracting time from dates.

Formatting & Parsing


Effortlessly convert `datetime` objects into custom string
formats with `strftime()`, and parse date/time strings back into
`datetime` objects using `strptime()`.
Python Fundamentals

json Module: JSON Encoding & Decoding

Serialize Python Objects Deserialize JSON Strings


Use `[Link]()` to convert Use `[Link]()` to parse
Python objects into JSON JSON strings back into Python
formatted strings. objects.

Handle JSON Files


Use `[Link]()` and
`[Link]()` for convenient
JSON reading and writing to
files.
Python Fundamentals

re Module: Regular Expressions


The re module allows pattern matching using regular expressions, supporting tasks like text searching,
tokenization, and string manipulation.
Powerful Pattern Matching Efficient Text Manipulation
• [Link](): Matches a pattern at the beginning • [Link](): Replaces occurrences of a pattern
of a string. with a specified string.
• [Link](): Scans through a string to find the • [Link](): Compiles a regular expression
first occurrence of a pattern. pattern into a regex object for efficiency,
• [Link](): Returns all non-overlapping especially with repeated use.
matches of a pattern as a list.
• [Link](): Returns an iterator yielding Match
objects for all non-overlapping matches.
Python Fundamentals

Lab Activity

• Lab 1.22 Implementation of Python Standard Library Modules with


different operations
Python Fundamentals

Summary
In this presentation, you explored the essentials of Python
programming, gaining a strong foundation in key concepts:
• The basics of Python and why it's a popular language.
• Understanding data types and how variables store
information.
• Using operators for calculations and comparisons.
• Controlling the flow of programs with if-else statements
and loops.
• Writing reusable code with functions.
• Managing large projects with modules and packages.
• Handling errors efficiently with exception handling.
• Working with files through file handling techniques.
• Leveraging the Python Standard Library for powerful built-
in tools.
Source
[Link]
Python Fundamentals

References
• Automate the Boring Stuff with Python by Al Sweigart
• Great for beginners and practical applications. Python Crash Course by Eric Matthes
• A hands-on introduction to programming in Python.
• Learn Python the Hard Way by Zed A. Shaw
• A well-structured guide to learning Python through exercises. Fluent Python by Luciano Ramalho
• The primary resource for Python's syntax and libraries. Real Python: [Link]
• Offers tutorials and articles on Python programming. W3Schools Python Tutorial: [Link]/python
• A beginner-friendly tutorial with interactive examples. GeeksforGeeks Python Programming Language:
[Link]
Python Fundamentals

Let’s Start
Python Fundamentals

Quiz
1. Which of the following is NOT a feature of Python?

a) Easy-to-read syntax
b) Strongly typed variables
c) Extensive standard library
d) Open-source and community-driven

Answer: B
Strongly typed variables
Python Fundamentals

Quiz
2. Which loop is best suited for iterating over elements
of a list?

a) while loop
b) for loop
c) do-while loop
d) switch statement

Answer: B
for loop
Python Fundamentals

Quiz
3. Which keyword is used to handle exceptions in
Python?

a) catch
b) handle
c) try
d) error

Answer: C
try
Python Fundamentals

Quiz
4. What is the purpose of the __init__.py file in a
package?

a) It initializes Python settings


b) It indicates the folder is a Python package
c) It stores metadata information
d) It defines global variables

Answer: B
It indicates the folder is a Python package
Python Fundamentals

Quiz
5. Which module provides functions to manipulate file
paths in Python?

a) os
b) sys
c) pathlib
d) shutil

Answer: C
pathlib
Thank You

You might also like