1753873337-Module 1 - Python Fundamentals
1753873337-Module 1 - 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
Source
[Link]
Python Fundamentals
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
Source
[Link]
Python Fundamentals
Python Features
Python Fundamentals
Python History
Source
[Link]
Python Fundamentals
Lab Activity
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
Lab Activity
Lab 1.2 Write a program with print function to print single and
Multiline text
Python Fundamentals
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
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
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
Source
[Link]
Python Fundamentals
Source
Python Data Types - GeeksforGeeks
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
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
# 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
Example:
greet = 'hello'
print(greet[1])
print(greet[-4])
Source
[Link]
Python Fundamentals
Python Sets
A set is a collection of unique data, meaning that elements within a set cannot be duplicated.
Source
[Link]
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
}
# Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}
Python Fundamentals
Python Dictionary
Creating a dictionary
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
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
Lab Activity
Source
[Link]
Python Fundamentals
Lab Activity
Lab 1.8 Implementation of Addition of string and integer Using Explicit Conversion
Python Fundamentals
Arithmetic Operators
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
Identity Operators
Membership Operators
Bitwise Operators
>> 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
• Operators have the same precedence, is 4 *, /, //, % Multiplication, division, floor division, modulus
Lab Activity
Output:
• The print() function is used to output data to the
standard output (usually the screen).
Python Fundamentals
Syntax of input()
input(prompt)
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 :
% operator
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
Syntax
if condition:
# body of if statement
else:
# body of else statement
Source
[Link]
Python Fundamentals
Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
Source
[Link]
Python Fundamentals
Source
[Link]
Python Fundamentals
Lab Activity
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
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
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].
Basic Syntax
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
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
Syntax count += 1
if count == 5:
break
break
Python Fundamentals
Lab Activity
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.
Source
[Link]
Python Fundamentals
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!')
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
Source
[Link]
Python Fundamentals
# function call
square = find_square(3)
print('Square:', square)
Source
[Link]
Python Fundamentals
Source
[Link]
Python Fundamentals
global x
x = 30 # Modify the global variable def inner_function():
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
Lab Activity
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
print([Link])
# Output: 3.141592653589793
Source
[Link]
Python Fundamentals
print(pi)
# Output: 3.141592653589793
Source
[Link]
Python Fundamentals
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
Source
[Link]
Python Fundamentals
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
Custom Exceptions
Custom exceptions can be created by defining a new class that inherits from the built-in Exception class.
Python Fundamentals
Source
[Link]
Python Fundamentals
Source
[Link]
Python Fundamentals
Lab Activity
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
Source
[Link]
Python Fundamentals
Source
[Link]
Python Fundamentals
Syntax:
Source
[Link]
Python Fundamentals
File Methods
To interact with files and their contents
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
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
Lab Activity
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
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
Time Durations
Calculate and represent precise time differences and
durations with `[Link]`, perfect for adding or
subtracting time from dates.
Lab Activity
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?
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