1. Introduction of Python Programming
1. Emphasis on code readability, shorter codes, ease of writing
2. Programmers can express logical concepts in fewer lines of code in comparison to
languages such as C++ or Java.
3. Python supports multiple programming paradigms, like object-oriented and functional
programming or procedural.
4. There exists inbuilt functions for almost all of the frequently used concepts.
Philosophy is “Simplicity is the best
5. Internally, Python converts the source code into an intermediate form called bytecodes
which is then translated into native language of specific computer to run it.
6.Python programs can be developed and executed on multiple operating system platforms.
2. Rich Library Support
The Python Standard Library is very vast Known as the “batteries included” philosophy of
Python
It can help do various things involving regular expressions, documentation generation, unit
testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV files,
cryptography, GUI and many more.
Besides the standard library, there are various other high-quality libraries such as the Python
Imaging Library which is an amazingly simple image manipulation library
3. input ():
• This function first takes the input from the user and converts it into a string.
• The type of the returned object always will be <class ‘str’>.
• It does not evaluate the expression it just returns the complete statement as String.
• When the input function is called it stops the program and waits for the user’s input.
• When the user presses enter, the program resumes and returns what the user typed.
input = input('STATEMENT')
Example:
1. name = input('What is your name?n')
# n ---> newline ---> It causes a line break
What is your name?
Ram
print(name)
Ram
# comment in python
4. • When input() function executes program flow will be stopped until the user has given input.
• The text or message displayed on the output screen to ask a user to enter an input value is
optional i.e. the prompt, which will be printed on the screen is optional.
• Whatever you enter as input, the input function converts it into a string. if you enter an integer
value still input() function converts it into a string.
• You need to explicitly convert it into an integer in your code using typecasting
5. Python# Program to check input
# type in Python
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)
# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))
Output:
Enter number: 123
123
Enter name : vbit
vbit
6. # Python program showing how to taking two inputs at a time
# multiple input using split function
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
# taking two inputs at a time
a, b = input("Enter two values: ").split()
print("First number is {} and second number is {}".format(a, b))
7. Output:
Enter values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15
Enter two values: 5 10
First number is 5 and second number is 10
Enter multiple values: 5 10 15 20 25
List of students: [5, 10, 15, 20, 25]
# taking multiple inputs at a time
# and type casting using list() function
x = list(map(int, input("Enter multiple values: ").split()))
print("List of students: ", x)
8. 1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined as
Python int , Python float , and Python complex classes in Python .
•Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
•Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
•Complex Numbers – A complex number is represented by a complex class. It is specified
as (real part) + (imaginary part)j . For example – 2+3j
9. Example:
a = 5
print(type(a))
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
Output: <class 'int'> <class 'float'> <class 'complex'>
10. 2.String Data Type in python
• Python Strings are arrays of bytes representing Unicode characters. In Python, there is no
character data type , a character is a string of length one. It is represented by str class.
• Strings in Python can be created using single quotes, double quotes, or even triple quotes. We
can access individual characters of a String using index.
s = 'Welcome to the VBIT'
print(s)
# check data type
print(type(s))
# access string with index
print(s[1])
print(s[2])
print(s[-1])
11. 3.List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is
very flexible as the items in a list do not need to be of the same type.
Access List Items
• In order to access the list items refer to the index number.
• In Python, negative sequence indexes represent positions from the end of the array.
• Instead of having to compute the offset as in List[len(List)-3],
• it is enough to just write List[-3].
• Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
12. Ex: accessing list
a = [10, 20, 30, 40, 50]
# Accessing the first item
print(a[0])
# Accessing the last item
print(a[-1])
Output
10 50
Ex: for loop
a = [10, 20, 30, 40, 50]
# Loop through the list and print each item
for item in a:
print(item)
Output
10 20 30 40 50
13. 4.Tuple Data Type in python: Just like a list, a tuple is also an ordered collection of Python
objects. The only difference between a tuple and a list is that tuples are immutable. Tuples cannot
be modified after it is created.
Creating a Tuple in Python: In Python Data Types, tuples are created by placing a sequence of
values separated by a ‘comma’ with or without the use of parenthesis for grouping the data
sequence. Tuples can contain any number of elements and of any datatype (like strings, integers,
lists, etc.).
initiate empty tuple
t1 = ()
t2 = (‘Vbit', ‘CSB')
print("nTuple with the use of String: ", t2)
Output: Tuple with the use of
String: (‘Vbit’, ‘CSB')
14. Access Tuple Items
• In order to access the tuple items refer to the index number.
• Use the index operator [ ] to access an item in a tuple.
t1 = tuple([1, 2, 3, 4, 5])
# access tuple items
print(t1[0])
print(t1[-1])
print(t1[-3])
Output: 1 5 3
15. # Creating a Tuple with the use of Strings
Tuple = (‘vbit', ‘csb')
print("nTuple with the use of String: ")
print(Tuple)
# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print("nTuple using List: ")
Tuple = tuple(list1)
# Accessing element using indexing
print("First element of tuple")
print(Tuple[0])
# Accessing element from last negative indexing
print("nLast element of tuple")
print(Tuple[-1])
print("nThird last element of tuple")
print(Tuple[-3])
Output : Tuple with the use of
String: (‘vbit’, ‘csb’)
Tuple using List:
First element of tuple
1
Last element of tuple
6
Third last element of tuple
4
16. 5.Boolean Data Type in python
• Python Data type with one of the two built-in values, True or False.
• Boolean objects that are equal to True (true), and those equal to False (false).
• However non-Boolean objects can be evaluated in a Boolean context as well and determined to
be true or false. It is denoted by the class bool.
Example: The first two lines will print the type of the Boolean values True and False, which
is <class ‘bool’>. The third line will cause an error, because true is not a valid keyword in
Python. Python is case-sensitive, which means it distinguishes between uppercase and lowercase
letters
print(type(True))
print(type(False))
print(type(true)
Output:
<class 'bool'>
<class 'bool'>
17. Dictionary
• Python dictionary is like hash tables in any other language with the time complexity of 0(1).
• It is an unordered collection of data values, used to store data values like a map, which, unlike
other Data Types that hold only a single value as an element,
• Dictionary holds the key value pair. Key-value is provided in the dictionary to make it more
optimized.
18. # Creating a Dictionary
Dict = {'Name': ‘vbit', 1: [1, 2, 3, 4]}
print("Creating Dictionary: ")
print(Dict)
# accessing a element using key
print("Accessing a element using key:")
print(Dict['Name'])
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(1))
# creation using Dictionary comprehension
myDict = {x: x**2 for x in [1,2,3,4,5]}
print(myDict)
OutputCreating Dictionary:
{'Name': ‘vbit’, 1: [1, 2, 3,
4]} Accessing a element using
key: vbit
Accessing a element using get:
[1, 2, 3, 4] {1: 1, 2: 4, 3:
9, 4: 16, 5: 25}
19. Python program by using else if
marks = 80
result = ""
if marks < 30:
result = "Failed"
elif marks > 75:
result = "Passed with distinction"
else:
result = "Passed"
print(result)
Output: Passed with distinction
Control flow in Python
20. for Loop:
The for loop iterates over the items of any sequence, such as a list, tuple or a string .
Ex:
words = ["one", "two", "three"]
for x in words:
print(x)
Output:
one
two
Three
while Loop:
The while loop repeatedly executes a target statement as long as a given boolean expression is
true.
Ex:
i = 1
while i < 6:
print(i)
i += 1
output: 1 2 3 4 5
21. Data Structures in Python
•Python lists are just like the arrays, declared in other languages which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.
•The implementation of Python List is similar to Vectors in C++ or Array List in JAVA.
• The costly operation is inserting or deleting the element from the beginning of the List as all the
elements are needed to be shifted.
•Insertion and deletion at the end of the list can also become costly in the case where the pre
allocated memory becomes full
List = [1, 2, 3, “hello", 2.3]
print(List)
Output[1, 2, 3, ‘hello', 2.3]
22. Ex
a = [“vbit", "For", “csb"]
print("Accessing element from the list")
print(a[0])
print(a[2])
print("Accessing element using negative indexing")
print(a[-1])
print(a[-3])
Output
Accessing element from the list
vbit vbit
Accessing element using negative indexing
csb vbit
23. Creating a Function in Python
• We can define a function in Python, using the def keyword.
• We can add any type of functionalities and properties to it as we require.
• we can create Python function definition by using def keyword.
Calling a Function in Python: After creating a function in Python we can call it by using the
name of the functions Python followed by parenthesis containing parameters of that particular
function.
Below is the example for calling def function Python.
# A simple Python function
def fun():
print("Welcome to VBIT")
# Driver code to call a function
fun()
# A simple Python function def fun():
("Welcome to VBIT")
Output:
Welcome to VBIT
24. Ex:2
def add(num1:int ,num2: int)
num3 = num1 + num2
return num3
res = add(num1, num2)
print("The addition of {num1} and {num2} results {res}.")
Output:
he addition of 5 and 15 results 20.
25. What is Python Module
• A Python module is a file containing Python definitions and statements.
• A module can define functions, classes, and variables.
• A module can also include runnable code.
• Grouping related code into a module makes the code easier to understand and use.
• It also makes the code logically organized
Create a Python Module
• To create a Python module, write the desired code and save that in with .py extension.
Example: Let’s create a simple calc.py in which we define two functions, one add and
another subtract.
# A simple module, calc.py
def add(x, y):
return (x + y)
def subtract(x, y):
return (x-y)
26. import module in Python
• We can import the functions, and classes defined in a module to another module using
the import statement in some other Python source file.
• When the interpreter encounters an import statement, it imports the module if the module is
present in the search path.
Syntax to Import Module in Python
import module
# importing sqrt() and factorial from the module math
#from math import sqrt, factorial
# if we simply do "import math", then
# math.sqrt(16) and math.factorial(6)
print(sqrt(16))
print(factorial(6)) Output:
4.0
720
27. Classes in Python
• A class in Python is a user-defined template for creating objects.
• It bundles data and functions together, making it easier to manage and use them.
• When we create a new class, we define a new type of object.
• We can then create multiple instances of this object type.
• Classes are created using class keyword.
• Attributes are variables defined inside the class and represent the properties of the class.
Attributes can be accessed using the dot . operator (e.g., My Class. my_attribute).
define a class class Dog: sound = "bark" # class attribute
28. Creating Object
An Object is an instance of a Class. It represents a specific implementation of the class and holds its own data.
Now, let’s create an object from Dog class.
# Creating an object of the Dog class
dog1 = Dog("Buddy", 3)
print(dog1.name)
print(dog1.species)
class Dog:
species = "Canine"
# Class attribute
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
Output: Buddy Canine
29. Python Exception Handling
• It handles errors that occur during the execution of a program.
• Exception handling allows to respond to the error, instead of crashing the running program.
• It enables you to catch and manage errors, making your code more robust and user-friendly.
Example: Trying to divide a number by zero will cause an exception.
# Example of an exception
n = 10
try:
res = n / 0 # This will raise a Zero Division Error
except ZeroDivisionError:
print("Can't be divided by zero!")
Output: Can't be divided by zero!
30. File Handling in Python
Reading a File
• Reading a file can be achieved by file.read() which reads the entire content of the file.
• After reading the file we can close the file using file.close()
• which closes the file after reading it, which is necessary to free up system resources.
Example: Reading a File in Read Mode (r)
file = open(“vbit.txt", "r")
content = file.read()
print(content)
file.close()
Output:
Vbit
123 456
31. Writing to a File
• Writing to a file is done using file.write()
• which writes the specified string to the file. If the file exists, its content is erased.
• If it doesn’t exist, a new file is created.
Ex:
file = open(“vbit.txt", "w")
file.write("Hello, World!")
file.close() output : Hello world
Writing to a File in Append Mode (a)
• It is done using file.write() which adds the specified string to the end of the file without
erasing its existing content.
ex:
file = open(‘vbit.txt', 'a')
file.write(“welcome to vbit")
file.close() output: welcome to vbit
32. Date and time operations:
We can generate date objects from the date class. A date object represents a date
having a year, month, and day.
Syntax: datetime.date( year, month, day)
1.current.strftime(“%m/%d/%y”) that print in month(Numeric)/date/year format
2.current.strftime(“%b-%d-%Y”) that prints in month(abbreviation)-date-
year format
3.current.strftime(“%d/%m/%Y”) that prints in date/month/year format
4.current.strftime(“%B %d, %Y”) that prints in month(words) date, year format
33. #program to create a date object containing the current date by class method today()
current = date.today()
# print current year, month, and year individually
print("Current Day is :", current.day)
print("Current Month is :", current.month)
print("Current Year is :", current.year)
#strftime() creates string representing date in various formats
print("n")
print("Let's print date, month and year in different-different ways")
format1 = current.strftime("%m/%d/%y")
# prints in month/date/year format
print("format1 =", format1)
format2 = current.strftime("%b-%d-%Y")
# prints in month(abbreviation)-date-year format
34. print("format2 =", format2)
format3 = current.strftime("%d/%m/%Y")
# prints in date/month/year format
print("format3 =", format3)
format4 = current.strftime("%B %d, %Y")
# prints in month(words) date, year format
print("format4 =", format4)
Output:
Current Day is : 23 Current Month is : 2 Current Year is : 2025
Let's print date, month and year in different-different ways
format1 = 02/23/25
format2 = Feb-23-2025
format3 = 23/02/2025
format4 = February 23, 2025
35. # python program to print time ,minutes ,seconds if no parameter is passed in time() by default
defaultTime = time()
print("default_hour =", defaultTime.hour)
print("default_minute =", defaultTime.minute)
print("default_second =", defaultTime.second)
print("default_microsecond =", defaultTime.microsecond)
# passing parameter in different-different ways
# hour, minute and second respectively is a default
time1= time(10, 5, 25)
print("time_1 =", time1)
# assigning hour, minute and second to respective variables
time2= time(hour = 10, minute = 5, second = 25)
print("time_2 =", time2)
# assigning hour, minute, second and microsecond
time3= time(hour=10, minute= 5, second=25, microsecond=55)
print("time_3 =", time3)
Output:
default_hour = 0
default_minute = 0
default_second = 0
default_microsecond = 0
time_1 = 10:05:25
time_2 = 10:05:25
time_3 = 10:05:25.000055
36. Math Operation Package
• It is to organize Python code into a structured package with two sub-packages:
• basic (for addition and subtraction) and advanced (for multiplication and division).
• Each operation is implemented in separate modules, allowing for modular, reusable and
maintainable code.
# Initialize the main package
from.calculate import calculate
from.basic import add, subtract
from.advanced import multiply, divide
37. math_operations/basic/__init__.py:
This __init__.py file initializes the basic sub-package by importing and exporting the add and
subtract functions from their respective modules (add.py and sub.py). This makes these functions
accessible when the basic sub-package is imported.
# Export functions from the basic sub-package
from.add import add
from.sub import subtract
from math_operations import calculate, add, subtract
# Using the placeholder calculate function
calculate()
# Perform basic operations
print("Addition:", add(5, 3))
print("Subtraction:", subtract(10, 4))
Output:
6
8
38. Packages in IoT using Numpy it is implemented by MAT-LAB handle with Arrays.
• Python on the other hand operates with a list of substitute arrays.
• It determines its character a set of scientific computing implemented by Python and familiar to
MAT-LAB.
• Generally it is used to Read sensor Data in huge from data bases and implement on them by
Inbuilt Functions.
39. # Python code to perform arithmetic operations on NumPy array
import numpy as np
# Initializing the array
arr1 = np.arange(4, dtype = np.float_).reshape(2, 2)
print('First array:')
print(arr1)
print('nSecond array:')
arr2 = np.array([12, 12])
print(arr2)
print('nAdding the two arrays:')
print(np.add(arr1, arr2))
print('nSubtracting the two arrays:')
print(np.subtract(arr1, arr2))
print('nMultiplying the two arrays:')
print(np.multiply(arr1, arr2))
print('nDividing the two arrays:')
print(np.divide(arr1, arr2))
Output:
First array: 0 1
2 3
Second array: [12 12]
Adding the two arrays: [ 12 13]
[ 14 15]
Subtracting the two arrays: [-12 -11]
[-10 -9]
Multiplying the two arrays: [ 0 12 ]
[ 24 36]
Dividing the two arrays: [ 0. 0.08333333]
[ 0.16666667 0.25 ]
40. Tkinter:
• Tkinter, library is installed with Python and more useful.
• It is GUI operated library that comes with all the methods of Python.
• For techies it is more flexible , other than Object oriented Scripting.
• Knowing how to implement this Package may be watching complex at first and Essential
Packages in Python and IoT.