Python Programming Pritam Chakraborty
Python Programming Pritam Chakraborty
BCAAE301
Copyright @Pritam_Chakraborty
• What is Python?
Copyright @Pritam_Chakraborty
Programing Language Trends:
For the Year : 2023-24
Copyright @Pritam_Chakraborty
Why Do People are getting Crazy over Python ?
Copyright @Pritam_Chakraborty
• an open-source, high-level, interpreted, general-purpose, dynamic
programming language
Copyright @Pritam_Chakraborty
• flexibility as a programming language means it can also be used as an
add-on to make highly customizable programs.
• Cross-platform language
• Software quality.
Copyright @Pritam_Chakraborty
• embedded easily into any application to provide a programmable
interface.
• Developer productivity.
Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Limitations of Python
Copyright @Pritam_Chakraborty
Python Features From Other Programing
Languages
• Function Concept from C Language
• Object Oriented Feature from C++ Language
• Scripting feature from PEARL and Shell Script
• Modular programming features from Modula-3
• Syntax from C Language and ABC Language
Copyright @Pritam_Chakraborty
Compiler Versus Interpreter
Copyright @Pritam_Chakraborty
• Compiler meticulously scans and converts the source code before
launching the program. In this perspective, the high-level program is called
the source code, and the translated program is called the object code or the
executable. Compiling a program allows users to run it repeatedly without
retranslating it each time. A hardware executor can then run the compiled
object code.
Copyright @Pritam_Chakraborty
Structure of a Compiler
Copyright @Pritam_Chakraborty
High-Level Block diagram of an Interpreter
Copyright @Pritam_Chakraborty
Python Interpreter
Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
IDE’s and Code Editors
• What Is an IDE?
Copyright @Pritam_Chakraborty
• What is a Code Editors?
Copyright @Pritam_Chakraborty
Top IDEs For Python
• IDLE: IDLE (Integrated Development and Learning Environment) is a
default editor that accompanies Python
Copyright @Pritam_Chakraborty
• Sub Lime Text 3
• Spyder
Copyright @Pritam_Chakraborty
• PyDev
• Thonny
• Wing
• Vim
• Pyscripter
• Rodeo
Copyright @Pritam_Chakraborty
Installing Python
• Installing Python on Windows/Mac
• Step 1: Go to https://www.python.org/ Dowloads
Copyright @Pritam_Chakraborty
• Integrate Python in VSCode
Copyright @Pritam_Chakraborty
• Step3: Create a virtual environment
Copyright @Pritam_Chakraborty
• The command then presents a list of interpreters that can be used for
your project. Select the interpreter you installed at the beginning of
the tutorial.
Copyright @Pritam_Chakraborty
• After Selecting the Interpreter a notification will show the progress of
the environment creation and the environment folder (/.venv) will
appear in your workspace.
Copyright @Pritam_Chakraborty
• Ensure your new environment is selected by using the Python: Select
Interpreter command from the Command Palette.
Copyright @Pritam_Chakraborty
Create a Python source code file
Copyright @Pritam_Chakraborty
Copyright @Pritam_Chakraborty
Run Python code
Copyright @Pritam_Chakraborty
Configure and run the debugger
Copyright @Pritam_Chakraborty
Let’s Start Coding in Python
Copyright @Pritam_Chakraborty
Elements of Python Language
• The set of valid characters that a programming language can recognize is called the character set
of the language. Two types of character sets are
• Source Characters. ( Alphabets uppercase and lowercase, underscore, Special characters blank –
(+,-,*,/,^,~,%,!,&,|,(),{},[] ?’, ;, \), blank(“”))
• The Token is the smallest lexical unit in a program. The Types of tokens are listed below.
1. Identifiers
2. Keywords
3. Literals
4. Punctuations
Copyright @Pritam_Chakraborty
Identifiers
Copyright @Pritam_Chakraborty
Keywords
• Python has many inbuilt functions like input(). So Python does not
allow a program to use these function names liberally.
Keywords in Python:
Copyright @Pritam_Chakraborty
Literals
• Literal is one way of specifying data values. These will be the values
that never modify while the program is executing.
• Literals in Python are numbers, text, or other fixed data, unlike
variables whose values change during the action.
• Some of the literals are listed below:
1. String literals
2. Numerical literals
3. Boolean literals
Copyright @Pritam_Chakraborty
• String Literals • Numerical Literals
>>> # string literals Example of handling constant as a variable
>>> # in single quote
>>> single_quote = ‘stringliterals’
>>> # in double quotes >>>
>>> double_quotes = "stringliterals" >>> PI = 3.14
>>> # multi-line string
>>> TEMPERATURE = 9.0
>>> multiline = ‘’’ string
... literals’’’
>>> print(single_quote)
stringliterals
>>> print(double_quotes)
stringliterals
>>> print(multiline)
string
literals
>>>
Copyright @Pritam_Chakraborty
Python Code Block Structure
Copyright @Pritam_Chakraborty
Illustration of Blocks in Python
x = 10 # Block 1 starts
if x% 2 == 0: # Block 1 continues
print("The number is even" ) # Block 2
else: # Block 1
print("The number is odd") # Block 2
print("Program Ends’) # Block 1 continues
Copyright @Pritam_Chakraborty
Comments in Python
Block Comments illustration Inline comments illustration Multiple quotes illustration
Copyright @Pritam_Chakraborty
Variables and Assignment Statement
• In Python everything is an object, therefore a variable also is an
object. Thus, the rules for forming a variable are the same as the
identifiers.
Copyright @Pritam_Chakraborty
Assignment Statement
• One of the most critical statements in Python is the assignment
statement. The syntax of the introductory assignment statement is
given as follows:
Copyright @Pritam_Chakraborty
Name Spaces
• Python interpreter uses a unique structure called namespace using
which it maintains a list of names and their associated values.
• Python updates the list when a new variable is created and it is
deleted in the namespace when the variable is deleted.
Copyright @Pritam_Chakraborty
Example 1: Scope and Namespace in Python
# global_var is in the global namespace
global_var = 10
def outer_function():
# outer_var is in the local namespace
outer_var = 20
•global_var - is in the global
def inner_function(): namespace with value 10
# inner_var is in the nested local namespace
inner_var = 30 •outer_val - is in the local
print(inner_var)
namespace
of outer_function() with value 20
print(outer_var)
•inner_val - is in the nested local
inner_function() namespace
# print the value of the global variable of inner_function() with value 30
print(global_var)
# call the outer function and print local and nested local variables
Copyright @Pritam_Chakraborty
outer_function()
Example 2: Use of global Keyword in Python
Copyright @Pritam_Chakraborty
Python Objects
Copyright @Pritam_Chakraborty
Data Types in Python
• A data type indicates what values a variable can hold, and an operator indicates the kind of
operations performed on the values.
• Python supports numbers and floating numbers. Classification of data types as follows,
Copyright @Pritam_Chakraborty
Python Type Conversion
Copyright @Pritam_Chakraborty
Python Implicit Type Conversion
• In certain situations, Python automatically converts one data type to another. This is
known as implicit type conversion.
Example:
integer_number = 123
float_number = 1.23
Copyright @Pritam_Chakraborty
Explicit Type Conversion
Example:
Copyright @Pritam_Chakraborty
num_string = '12'
num_integer = 23
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Copyright @Pritam_Chakraborty
Key Points For Type Conversion
• Type Conversion is the conversion of an object from one data type to
another data type.
• Implicit Type Conversion is automatically performed by the Python
interpreter.
• Python avoids the loss of data in Implicit Type Conversion.
• Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
• In Type Casting, loss of data may occur as we enforce the object to a
specific data type.
Copyright @Pritam_Chakraborty
Operators and Expression
• Operators
Operators are contructs that are used to manipulate the value of operands.
Some basic operators includes +,-,*,and /.
Copyright @Pritam_Chakraborty
e) Unary Operators
f) Bitwise Operators
g) Membership Operators
h) Identity Operators
• Expression
Copyright @Pritam_Chakraborty
Arithmetic Operators
Copyright @Pritam_Chakraborty
Comparison Operators
Copyright @Pritam_Chakraborty
Assignment and in-place or shortcut
operators
Copyright @Pritam_Chakraborty
Unary Operators
• Acts on Single Operands.
• >> a = 5
• >> b = -a
• >> print(b)
• Output: -5
Copyright @Pritam_Chakraborty
Bitwise Operators
Copyright @Pritam_Chakraborty
Truth Table For Bitwise Operator
Copyright @Pritam_Chakraborty
Verification of Bitwise Operator Output
• The bin() function is a built-in Python function that converts an
integer number into a binary string prefixed with '0b'.
Copyright @Pritam_Chakraborty
Shift Operator
• Python Support two bitwise shift operators. They are shift left (<<)
and shift right (>>). Example of Left Shift,
Copyright @Pritam_Chakraborty
• Example of Right Shift
Copyright @Pritam_Chakraborty
Logical Operators
Copyright @Pritam_Chakraborty
Membership Operator
Copyright @Pritam_Chakraborty
Identity Operator
Copyright @Pritam_Chakraborty
Operators Precedence and Associativity
Copyright @Pritam_Chakraborty
Strings
• Strings in Python are arrays of bytes representing unicode characters.
• Python does not have a character data type, a single character is
simply a string with a length of 1.
Strings in python are surrounded by either single
quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
print("Hello")
print('Hello')
Copyright @Pritam_Chakraborty
• Quotes Inside Quotes
You can use quotes inside a string, as long as they don't
match the quotes surrounding the string:
• Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
print(a)
Or three single quotes:
• Example
• a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.''‘
print(a)
Copyright @Pritam_Chakraborty
• Strings as an Array
• >> a = “hello!Students”
• >> print(a[6])
• Output: S
Copyright @Pritam_Chakraborty
• Looping through strings
Since Strings in python are treated as an ARRAY, Using FOR loop we can parse
through string.
Output:
S
T
U
D
E
N
T
Copyright @Pritam_Chakraborty
• String Length
>> a = “hello”
>> print(len(a))
Output: 5
Copyright @Pritam_Chakraborty
• Check Presence of word, character, phrase etc. in a String
To check the presence of word, character, phrase etc. in a String , we can use in
keyword.
Output: true
Use it in IF-ELSE:-
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Output: True
Use it in IF-ELSE:-
txt = "The best things in life are free!"
if “expensive" not in txt:
print("Yes, ‘expensive ' is not present.")
Copyright @Pritam_Chakraborty
String Slicing
• We can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to
return a part of the string.
Example: Get the characters from position 2 to position 5 (not
included):
• >> b = "Hello, Student!"
>> print(b[2:5])
• Output: llo
Copyright @Pritam_Chakraborty
• Slice From the Start
By leaving out the start index, the range will start at the first character:
• Example:
#Get the characters from the start to position 5 (not included):
Output: Hello
Copyright @Pritam_Chakraborty
• Slice To the End
By leaving out the end index, the range will go to the end:
• Example
# Get the characters from position 2, and all the way to the end:
• b = "Hello, Student!"
print(b[2:])
Copyright @Pritam_Chakraborty
• Negative Indexing
Use negative indexes to start the slice from the end of the
string:Example
• Output: yth
Copyright @Pritam_Chakraborty
Modify Strings
• Upper Case
• Lower Case
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Copyright @Pritam_Chakraborty
• Remove Whitespace
Whitespace is the space before and/or after the actual text, and
very often you want to remove this space.
Example
The strip() method removes any whitespace from the beginning
or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Copyright @Pritam_Chakraborty
• Replace String:
Copyright @Pritam_Chakraborty
Split String
• The split() method returns a list where the text between the specified
separator becomes the list items.
Copyright @Pritam_Chakraborty
String Concatenation
a = "Hello"
b = "World"
c=a+b
print(c)
• Output: HelloWorld
Copyright @Pritam_Chakraborty
Format String
• we cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
Copyright @Pritam_Chakraborty
We can combine strings and numbers by using f-strings or the format() method!
F-String was introduced in Python 3.6, and is now the preferred way of formatting
strings.
To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.
>> age = 24
>> txt = f"My name is John, I am {age}"
print(txt)
Copyright @Pritam_Chakraborty
Lab Practice Question:
1. Create a string made of the first, middle and last character.
Soln:
>>str1 = 'James‘
print("Original String is", str1)
# Get first character
>>res = str1[0]
# Get string size
>>l = len(str1)
# Get middle index number
>>mi = int(l / 2)
# Get middle character and add it to result
res = res + str1[mi]
# Get last character and add it to result
res = res + str1[l - 1]
print("New String:", res)
Copyright @Pritam_Chakraborty
• Exercise 2: Append new string in the middle of a given string
• s1 = "Ault" s2 = "Kelly“
• O/P: AuKellylt
Solution:
•First, get the middle index number of s1 by dividing s1’s length by 2
•Use string slicing to get the character from s1 starting from 0 to the
middle index number and store it in x
•concatenate x and s2. x = x + s2
•concatenate x and remaining character from s1
•print x
Copyright @Pritam_Chakraborty
• >>> s1 = "Ault"
• >>> s2 = "Kelly"
• >>> mi = int(len(s1) / 2)
• >>> x = s1[:mi:]
• >>> x = x + s2
• >>> x = x + s1[mi:]
• >>> print(x)
Copyright @Pritam_Chakraborty
• Exercise 3: Create a string made of the middle three characters
• str1 = "JohnDipPeta“
• O/P: Dip
• Solution:
Copyright @Pritam_Chakraborty
• str1 = "JohnDipPeta“
• # first get middle index number
• mi = int(len(str1) / 2)
• # use string slicing to get result characters
• res = str1[mi - 1:mi + 2]
• print("Middle three chars are:", res)
Copyright @Pritam_Chakraborty
• Exercise 4: Create a new string made of the first, middle, and last characters of
each input string
• s1 = "America"
• s2 = "Japan“
• first_char = s1[0] + s2[0]
• # get middle character from both string
• middle_char = s1[int(len(s1) / 2):int(len(s1) / 2) + 1] + s2[int(len(s2) / 2):int(len(s2)
/ 2) + 1]
• # get last character from both string
• last_char = s1[len(s1) - 1] + s2[len(s2) - 1]
• # add all
• res = first_char + middle_char + last_char
• print("Mix String is ", res)
Copyright @Pritam_Chakraborty
• Exercise 5: Arrange string characters such that lowercase letters should come first
• Str1= “PyNaTive”
• O/P = yaivePNT
• str1 = "PYnAtivE“
• print('Original String:', str1)
• lower = []
• upper = []
• for char in str1:
if char.islower():
# add lowercase characters to lower list
lower.append(char)
else:
# add uppercase characters to lower list
upper.append(char)
# Join both
list sorted_str = ''.join(lower + upper)
print('Result:', sorted_str)
Copyright @Pritam_Chakraborty
• Example 6. Count all the letters, digits, and special symbols from a given string
• Solution:
sample_str = "P@yn2at&#i5ve"
char_count = 0
digit_count = 0
symbol_count = 0
for char in sample_str:
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1
Copyright @Pritam_Chakraborty
• Example 7: Create a mixed String using the following rules
Given two strings, s1 and s2. Write a program to create a new string s3 made
of the first char of s1, then the last char of s2, Next, the second char of s1
and second last char of s2, and so on. Any leftover chars go at the end of the
result.
• s1 = “Abc”
• s2 = “Xyz”
Copyright @Pritam_Chakraborty
• s1 = "Abc"
• s2 = "Xyz"
• # iterate string
• # s1 ascending and s2 descending
• for i in range(length):
• if i < s1_length:
• result = result + s1[i]
• if i < s2_length:
• result = result + s2[i]
• print(result)
Copyright @Pritam_Chakraborty
• Example 8: Write a program to count occurrences of all characters within a string
• Solution:
• str1 = "Apple"
Copyright @Pritam_Chakraborty
• Example 9: Split a string on hyphens
Solution:
str1 = "Emma-is-a-data-scientist"
print("Original String is:", str1)
# split string
sub_strings = str1.split("-")
• Solution method 1:
import string
Copyright @Pritam_Chakraborty
• Solution method 2:
import re
Copyright @Pritam_Chakraborty
• Example 11: Write a Python program to change a given string to a new string
where the first and last chars have been exchanged
• Before Swap : PythoN
After Swap : NythoP
Solution:
1st way:
str = "Python"
print("Before Swap :",str)
res = str[-1:] + str[1:-1] + str[:1]
print("After Swap :",res)
Copyright @Pritam_Chakraborty
2nd Way:
str = "Python"
print("Before Swap :",str)
s = str[0]
e = str[-1]
res = e + str[1:-1] + s
print("After Swap :",res)
Copyright @Pritam_Chakraborty
Escape Characters
Copyright @Pritam_Chakraborty
• Example
• The escape character allows you to use double quotes when you
normally would not be allowed:
• >> txt = "We are the so-called \"Vikings\" from the north."
Copyright @Pritam_Chakraborty
String Methods
• Python has a set of built-in methods that you can use on strings. Note: All string methods return
new values. They do not change the original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was
found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
Copyright @Pritam_Chakraborty
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Copyright @Pritam_Chakraborty
zfill() Fills the string with a specified number of 0 values at the beginning