Introduction to Python
Programming
Presentation By:- Kartikey Arora
Why to Learn Python?
• Requires fewer lines of code compared to other
programming languages.
• Provides Libraries / Frameworks like Django, Flask,
Pandas, Tensorflow, Scikit-learn and many more for
Web Development, AI/ML, Data Science and Data
Analysis
• Cross-platform, works on Windows, Mac and Linux
without major changes.
• Used by top tech companies like Google, Netflix,
Microsoft and many more Tech Giants
• Many Python coding job opportunities in Software
Development, Data Science and AI/ML.
Installing Python
• Open your browser and visit the Python download
page: python.org/downloads.
• Select the latest Python 3 version, such as Python 3.13.1 (or
whichever is the latest stable version available).
• Click on the version to download the installer (a .exe file for
Windows).
Run the Python Installer
• Once the download is complete, run the installer program.
On Windows, it will typically be a .exe file.
• Make sure to mark Add Python to PATH otherwise you will have to
do it explicitly. It will start installing Python on Windows.
• After installation is complete click on Close.
Running Python Shell on Windows
• After installing Python, we can launch the Python
Shell by searching for "IDLE" in the "Start" menu
and clicking on it.
Python Syntax
• Python syntax is like grammar for this
programming language.
• Syntax refers to the set of rules that defines
how to write and organize code so that
the Python interpreter can understand and
run it correctly.
• These rules ensure that your code is
structured, formatted, and error-free.
Hello World!
• Here’s the “Hello World” program:
# This is a comment. It will not be executed.
print("Hello, World!")
• Output: How does this work:
• print() is a built-in Python
Hello, World!
function that tells the computer
to show something on the screen.
• The message "Hello, World!" is a
string, which means it's just text.
In Python, strings are always
written inside quotes (either
single ' or double ").
• Anything after # in a line is a
comment. Python ignores
comments when running the
code, but they help people
understand what the code is
doing.
Indentation in Python
• In Python, Indentation is used to define blocks of code. It tells the Python
interpreter that a group of statements belongs to a specific block. All
statements with the same level of indentation are considered part of the same
block. It improves code readability.
• Example:
• The first two print statements are indented by 4 spaces, so they belong to the
if block.
• The third print statement is not indented, so it is outside the if block.
• If we skip Indentation, Python will throw error:
Identifiers
• Identifier is a user-defined name given to a variable,
function, class, module, etc.
• The identifier is a combination of character digits and an
underscore.
• They are case-sensitive i.e., 'num' and 'Num' and 'NUM' are
three different identifiers in python.
• It is a good programming practice to give meaningful
names to identifiers to make the code understandable.
• Rules for Naming Python Identifiers
– It cannot be a reserved python keyword.
– It should not contain white space.
– It can be a combination of A-Z, a-z, 0-9, or underscore.
– It should start with an alphabet character or an underscore ( _ ).
– It should not contain any special character other than an
underscore ( _ ).
Examples of Python Identifiers
• Valid identifiers:
• var1
• _var1
• _1_var
• var_1
• Invalid Identifiers:
• !var1
• 1var
• 1_var
• var#1
• var 1
Keywords
• Python Keywords are some predefined and
reserved words in Python that have special
meanings.
• Keywords are used to define the syntax of the
coding.
• The keyword cannot be used as an identifier,
function, or variable name.
• All the keywords in Python are written in
lowercase except True and False. There are 35
keywords in Python 3.x.
• List of keywords available in Python 3.x :
• and: This is a logical operator which returns true if both the operands are
true else returns false.
• or: This is also a logical operator which returns true if anyone operand is
true else returns false.
• not: This is again a logical operator it returns True if the operand is false else
returns false.
• if: This is used to make a conditional statement
• else: used with if block and executed if the given condition is not true.
• for: This is used to create a loop.
• while: This keyword is used to create a while loop.
• break: This is used to terminate the loop.
• def: It helps us to define functions.
• return: It will return a value and exit the function.
• True: boolean value
• False: boolean value
• import: This is used to import a module.
• from: It is used to import specific parts of any module.
• in: It's used to check whether a value is present in a list, range, tuple, etc.
• is: This is used to check if the two variables are equal or not.
Python Variables
• Variables in Python are essentially named references pointing
to objects in memory. They allow us to store and reuse values
in our program.
• Unlike some other languages, you don't need to declare a
variable's type explicitly in Python. Based on the value
assigned, Python will dynamically determine the type.
• Example:
• Python allows assigning the same value to multiple
variables in a single line, which can be useful for
initializing variables with the same value.
• We can assign different values to multiple variables
simultaneously, making the code concise and easier
to read.
Data Types
• Python Data types are the classification or categorization of
data items.
• It represents the kind of value that tells what operations
can be performed on a particular data.
• Since everything is an object in Python programming,
Python data types are classes and variables are instances
(objects) of these classes.
• The following are the standard or built-in data types in
Python:
– Numeric - int, float, complex
– Sequence Type - string, list, tuple
– Mapping Type - dict
– Boolean - bool
Getting the Type of Variable
• In Python, we can determine the type of a variable
using the type() function. This built-in function
returns the type of the object passed to it.
Swapping Two Variables
• Using multiple assignments, we can swap the
values of two variables without needing a
temporary variable.
Type Casting a Variable
• Type casting refers to the process of converting the value of
one data type into another. Python provides several built-in
functions to facilitate casting, including int(), float() and
str() among others.
Integer and Float
• int in python can be of any arbitrary size:
– a = 567
– b = 567890123
– c = 98765456342453675235167870
• Arithmetic operations can be performed over
integers without worrying about overflow or
underflow
• float are represented internally in binary as 64-bit
double-precision values, as per IEEE 754 standard
• As per this standard, the maximum value a float
can have is approx 1.8 x 10308
Input and Output in Python
• Python's input() function is used to take user input.
By default, it returns the user input in form of a
string
• Example:
• The code prompts the user to input their name,
stores it in the variable "name" and then prints a
greeting message addressing the user by their
entered name.
Take Multiple Input in Python
How to Change the Type of Input in Python
• By default input() function helps in taking user
input as string. If any user wants to take input
as int or float, we just need to typecast it.
• The below code prompts the user to input an
integer representing the number of roses,
converts the input to an integer using
typecasting and then prints the integer value.
Output Formatting
• Using format():
• Using f-string:
• Using sep and end parameter:
– print() separates multiple values by space by default but
can be customized using sep parameter
– each print() ends with a newline (\n). We can change
this ending with end parameter
• Using % Operator:
– %d : integer
– %f : float
– %s : string
Python Operators
• In Python programming, Operators in general
are used to perform operations on values and
variables.
• Example of Arithmetic Operators in Python:
• Example of Relational Operators in Python
• Example of Logical Operators in Python:
• Bitwise operators: Python Bitwise operators act
on bits and perform bit-by-bit operations. These
are used to operate on binary numbers.
• Bitwise Operators in Python are as follows:
– Bitwise NOT (~)
– Bitwise Shift (<<, >>)
– Bitwise AND (&)
– Bitwise XOR (^)
– Bitwise OR (|)
• Assignment Operator:
– Addition Assignment Operator: a += b
– Subtraction Assignment Operator: a -= b
– Multiplication Assignment Operator: a *= b
– Division Assignment Operator: a /= b
– Modulus Assignment Operator: a %= b
– Floor Division Assignment Operator: a //= b
– Exponentiation Assignment Operator: a **= b
– Bitwise AND Assignment Operator: a &= b
– Bitwise OR Assignment Operator: a |= b
– Bitwise XOR Assignment Operator: a ^= b
– Bitwise Right Shift Assignment Operator: a >>= b
– Bitwise left Shift Assignment Operator: a <<= b
Precedence and Associativity
• An expression is a combination of variables,
constants, and operators that produces a result.
• When an expression has multiple operators,
precedence decides which operator is evaluated
first.
• When two operators have the same precedence,
associativity decides the order of evaluation:
– Left-to-Right
– Right-to-Left
Precedence level Operator Associativity
1 (Highest) () (parentheses) Left to Right
2 ** (exponentiation) Right to Left
3 +x, -x, ~x (unary plus, minus, Right to Left
bitwise NOT)
4 *, /, //, % Left to Right
5 +, - Left to Right
6 <<, >> (bitwise shift) Left to Right
7 & (bitwise AND) Left to Right
8 ^ (bitwise XOR) Left to Right
9 | (bitwise OR) Left to Right
10 Comparisons (<, <=, >, >=, ==, Left to Right
!=)
11 Logical not, and, or Left to Right
12 (Lowest) =, +=, -=, *=, ... Right to Left
Strings and Strings Handling
• A string is a collection or sequence of unicode
characters.
• Python strings can be enclosed in single (' '),
double (" ") or triple quotes (""" or ''')
Accessing string elements
• String elements can be accessed using an index value.
• Strings are indexed starting from 0 and -1 from end.
• Accessing an index out of range will cause
an IndexError.
• Only integers are allowed as indices and using a float or
other types will result in a TypeError.
• Python allows negative address references to access characters
from back of the String
• e.g., -1 refers to the last character, -2 refers to the second last
character, and so on.
• If there are characters like ', " or escape characters like \n, \t
etc. within a string, they can be retained with two ways:
– Escape them by preceding them with a \
– Prepend the string with a ‘r’ indicating that it is a raw string
String Immutability
• Strings in Python are immutable. This means that
they cannot be changed after they are created.
• If we need to manipulate strings then we can use
methods like concatenation, slicing, or formatting to
create new strings based on the original.
String Slicing
• String slicing in Python is a way to get specific parts of a
string by using start, end and step values.
• Syntax of String Slicing in Python:
substring = s[start : end : step]
• Parameters:
– s: The original string.
– start (optional): Starting index (inclusive). Defaults to 0 if
omitted.
– end (optional): Stopping index (exclusive). Defaults to the
end of the string if omitted.
– step (optional): Interval between indices. A positive value
slices from left to right, while a negative value slices from
right to left. If omitted, it defaults to 1 (no skipping of
characters).
Exercise:
Print a string in reverse order using Slicing
• In python, we delete a string using del keyword
• Concatenating two strings using + operator
• Updating a string
• repeat a string multiple times using * operator
• Using in keyword for String Membership Testing
Common String Methods:
• len(): returns the total number of characters in a string.
• upper(): converts all characters to uppercase.
• lower(): converts all characters to lowercase.
• strip(): removes leading and trailing whitespace from the string
• lstrip(): removes only leading whitespaces from the string
• rstrip(): removes only trailing whitespaces from the string
• replace(old, new): replaces all occurrences of a specified
substring with another.
• title(): Converts first letter of every word to upper case rest every
character in lower case.
• capitalize(): Capitalize only the first letter of the string rest everything to
lower case.
• swapcase(): Swap upper to lower and lower to upper
• isalpha(): Check if string has only letters
• isdigit(): Check if string has only digits
• isalnum(): Check if string has letters and/or digits
• isspace(): Check if string has only spaces
• isupper() / islower(): Check case
• min(): it returns the character with the smallest ASCII value.
• max(): it returns the character with the largest ASCII value.
• find(): Returns the lowest index of the substring if it is found else -1
• count(): Returns the number of occurrences of a substring in the string.
• startswith(prefix): Returns "True" if a string starts with the given prefix
• endswith(suffix): Returns "True" if a string ends with the given suffix
• chr(ascii): returns the character corresponding to the given ascii value.
• ord(char): returns the ascii value of the given character in a string
String Formatting
• Python provides several ways to include
variables inside strings:
• Using f-strings:
• Using format():
String Comparison
• == (Equality Operator): Checks whether two strings have
the same content (character by character).
• != (Not Equal To): Checks whether two strings are different.
• <, >, <=, >= (Relational Operators): Used for lexicographical
comparison of strings (dictionary order) based on ASCII
values of characters.
• Strings in Python can be compared case-insensitively by
converting both strings to either lowercase or uppercase.
Conditional Statements
• Conditional statements in Python are used to execute certain blocks
of code based on specific conditions.
• These statements help control the flow of a program, making it
behave differently in different situations.
• Conditions are built using relational operators: <, >, <=, >=, ==, !=
• a = b is assignment and a == b is comparison
• If Conditional Statement in Python:
– If statement is the simplest form of a conditional statement. It executes a
block of code if the given condition is true.
• If else Conditional Statements in Python:
– else allows us to specify a block of code that will execute if the
condition(s) associated with an if or elif statement evaluates to False
• elif Statement:
• Nested if..else Conditional Statements in Python
• Ternary Conditional Statement in Python
Conditions with logical operators
• Conditions can be combined using and / or as shown below:
– if cond1 and cond2: returns true if both conditions are true
else, false
– if cond1 or cond2: returns true if atleast one of them is true
else, false
• Any non zero number (positive, negative, int, float) is treated as
True and 0 as false but please note: int(True) = 1
Ranges or Multiple Equalities
Examples:
• and operator evaluates ALL expressions. It
returns the last expression if all expressions
evaluates to True otherwise it returns the first
expression which evaluates to False.
• or operator evaluates ALL expressions and
returns the first expression which evaluates to
True otherwise it returns the last expression
which evaluates to False.
Match Case statement
• Introduced in Python 3.10, the match case statement offers a
powerful mechanism for pattern matching.
• Syntax:
match subject:
case pattern1:
# Code block if pattern1 matches
case pattern2:
# Code block if pattern2 matches
case _:
# Default case (wildcard) if no other pattern matches
• match subject: The value (or variable) to match against.
• case pattern: A pattern to match the subject.
• _ (Wildcard): A default catch-all pattern, similar to a "default" in
other languages' switch statements.
Match Case Statement with OR Operator Match Case Statement with Python If Condition
Python for Loop
• Python For Loops are used for iterating over a sequence like
lists, strings, and ranges.
• Python For Loop with String:
• Python for loop with list:
• Using range() with For Loop:
– range(stop): Generates numbers from 0 to stop-1.
– range(start, stop): Generates numbers from start to stop-1.
– range(start, stop, step): Generates numbers from start to stop-1,
incrementing by step (this can be +ve or –ve, in case of –ve step
value it runs from start to stop+1).
Control Statements with For Loop
• Continue with For Loop: Python continue Statement returns the
control to the beginning of the loop.
• Break with For Loop: Python break statement brings control out of the
loop.
• Else Statement with For Loops:
– Python also allows us to use the else condition for
loops.
– The else block just after for loop is executed only when
the loop is NOT terminated by a break statement.
• Nested For Loops in Python:
Python While Loop
• Python While Loop is used to execute a block of statements
repeatedly until a given condition is satisfied.
• When the condition becomes false, the line immediately after
the loop in the program is executed.
• while loop Syntax:
while expression:
statement(s)
– condition: This is a boolean expression. If it evaluates to
True, the code inside the loop will execute.
– Statement(s): These are the statements that will be
executed during each iteration of the loop.
• In the following example, the condition for while will be True as long
as the counter variable (count) is less than 3:
• for loop is primarily used when the number of iterations is known or
can be easily determined beforehand whereas, while loop is used
when the number of iterations is unknown and the loop needs to
continue as long as specific condition remains True and terminates
when condition becomes false.
• It is important to make sure the condition eventually becomes False
otherwise loop will run infinitely
Control statements with while loop
While-else loop
• The else clause after while loop is only executed when your while condition
becomes false. If you break out of the loop, or if an exception is raised, it
won’t be executed.
Python Functions
• A function in Python is a reusable block of code that
performs a specific task.
• Instead of writing the same code multiple times, you put it
inside a function and just "call" it when needed.
Benefits of Using Functions:
– Code Reuse
– Reduced code length
– Increased readability of code
Types of functions:
• Built-in Functions: Already available in Python (e.g., len(),
max(), print()).
• User-defined Functions: Functions we can create based on
our requirements using def keyword.
Creating a Function
• We can define a function in Python, using the def keyword.
• The def keyword stands for define. It is used to create a user-
defined function. It marks the beginning of a function block
and allows you to group a set of statements so they can be
reused when the function is called.
• Syntax:
Function Arguments or Parameters
• Arguments are the values passed inside the parenthesis of the
function. A function can have any number of arguments separated by
a comma.
• Syntax for functions with arguments:
def function_name(parameter: data_type) -> return_type:
# body of the function
return expression
• data_type and return_type are optional in function declaration,
meaning the same function can also be written as:
def function_name(parameter):
# body of the function
return expression
Example
create a simple function in Python to check
whether the number passed as an argument to
the function is even or odd.
Calling a function
Types of Function Arguments
• Positional Arguments:
• We used the Position argument during the function call so
that the first argument (or value) is assigned to name and
the second argument (or value) is assigned to age
• Default Arguments:
– A default argument is a parameter that assumes a
default value if a value is not provided in the
function call for that argument.
• Keyword Arguments:
– The idea is to allow the caller to specify the
argument name with values so that the caller does
not need to remember the order of parameters.
Variable length arguments
• *args: Multiple positional arguments
• **kwargs: Multiple keyword arguments
Docstring
• The first string after the function is called the Document string
or Docstring in short.
• This is used to describe the functionality of the function.
• The use of docstring in functions is optional but it is considered
a good practice.
• The below syntax can be used to print out the docstring of a
function:
print(function_name.__doc__)
Lambda Functions
• A lambda function is a small, anonymous function
(without a name).
• It is defined using keyword lambda
• Syntax:
lambda arguments: expression
• Can have any number of arguments.
• Can only contain a single expression (not multiple
statements).
• Automatically returns the result of that expression.
Examples
Python Recursive Functions
• A recursive function is just like any other
Python function except that it calls itself in its
body.
• Recursive function contains two key parts:
– Base Case: The stopping condition that prevents
infinite recursion.
– Recursive Case: The part of the function where it
calls itself with modified parameters.
Examples
• Example 1: Generate first n natural numbers
• Example2: Factorial Calculation
• Example 2: Fibonacci Sequence
• Example: sum of digits
Python Built-in Functions/Modules
• Built in functions are always available in any
part of the program for direct use. Examples:
– abs(x): returns absolute value of x
– pow(x, y): return value of x raised to y
– min(x1, x2, x3,…): return minimum value
– max(x1, x2, x3,…): return maximum value
– bin(x): return binary equivalent of x
• Built in modules are the libraries provided by
python containing multiple functions to use.
• We can import that particular module and use its
functions. Example: Mathematical functions in
math module
– math.pi: pi value
– math.sqrt(x): square root of x
– math.factorial(x): factorial of x
– math.ceil(x): smallest integer (>=x)
– math.floor(x): largest integer (<=x)
– math.log10(x): base 10 log of x
– math.fabs(x): absolute value of float
– math.trunc(x): trunc() is floor() for positive x and ceil()
for negative x
Creating and using custom modules
• A module in Python is just a .py file that contains functions,
classes, or variables.
• We can import it into another file to reuse code.
• Create a Python file (the module):
Example: mathOps.py
• Create another Python file (the main program)
Example: main.py
• Using Aliases
• Import Specific Functions
• Import everything
Python Exception Handling
• An exception is an error that occurs during program
execution (like division by zero, file not found, invalid
input).
• Instead of crashing the program, Python lets you
handle exceptions gracefully using try...except block.
• Basic Syntax
try:
# Code that may cause an error
except SomeException:
# Code to handle the error
• Example 1: Divide by Zero
• Explanation: Dividing a number by 0 raises a ZeroDivisionError.
The try block contains code that may fail and except block
catches the error, printing a safe message instead of stopping
the program.
• Example 2: Catching Multiple Exceptions
• In the previous example ValueError exception will be raised because it is
raised, when an invalid value is assigned to a variable or passed to a
function while calling it.
• Example 3: Catch Any Exception
• IndexError Exception
• TypeError Exception
• Example 4: Using else and finally
• else runs only if no exception occurs.
• finally runs always (useful for closing files, releasing resources).
• Example 5: Raising Your Own Exception
Python Lists
• In Python, a list is a built-in dynamic sized array
(automatically grows and shrinks). We can store all types
of items (including another list) in a list.
• A list may contain mixed type of items.
Creating List with Repeated Elements
Accessing list elements
• Elements in a list can be accessed using indexing. Python indexes start
at 0, so a[0] will access the first element, while negative indexing allows
us to access elements from the end of the list. Like index -1 represents the
last elements of list.
• Slicing is another way to access multiple items from a list. We can get a
range of items by specifying a starting index and an ending index.
THANK YOU