Unit 1 Introduction To Python
Unit 1 Introduction To Python
Problem Solving, Problem Analysis Chart, Developing an Algorithm, Flowchart and Pseudocode,
Interactive and Script Mode, Indentation, Comments, Error messages, Variables, Reserved Words,
Data Types, Arithmetic operators and expressions, Built-in Functions, Importing from Packages.
INTRODUCTION T0 PYTHON
Problem Solving
Understand the problem clearly before attempting to find a solution. This involves
identifying the inputs required and the expected outputs. A thorough analysis helps in
defining the problem accurately.
2. Developing an Algorithm:
3. Coding:
Convert the algorithm into a programming language that the computer can
understand. This step involves writing the actual code that implements the algorithm.
After coding, the program must be tested to ensure it meets the requirements and
produces the correct output. This involves checking for syntax errors and logical
errors. Debugging is the process of identifying and fixing these errors.
A number (N) Check if divisible only by 1 and itself "Prime" or "Not Prime"
If factors found → Not Prime
Problem Analysis Chart has numerous advantages, particularly in the context of designing
and developing computer programs.
ALGORITHM
• For a particular task, multiple algorithms may exist, they differ by their time complexity
and space requirements.
• The programmer chooses the most appropriate algorithm based on the efficiency and
suitability for the task at hand.
• The computer then follows the steps written in the program code. Therefore, the
programmer first prepares a roadmap of the program to be written, before actually writing the
code.
• Without a roadmap, the programmer may not be able to clearly visualise the instructions to
be written and may end up developing a program which may not work as expected.
• Such a roadmap is nothing but the algorithm which is the building block of a computer
program.
• If the algorithm is correct, computer will run the program correctly, every time.
• So, the purpose of using an algorithm is to increase the reliability, accuracy and efficiency
of obtaining solutions.
6. Generality – It should work for a set of inputs, not just one case.
Structure of an Algorithm
1. Start
4. Output (result)
5. Stop
1. Start
3. Initialize Sum = 0
4. Repeat steps 5 and 6 for i = 1 to N
6. Go to next i
7. Print Sum
8. Stop
Algorithm:
1. Start
2. Input number N
3. If N % 2 == 0 then
Print "Even"
Else
Print "Odd"
4. Stop
Algorithm:
1. Start
2. Input number N
3. Set Fact = 1
6. Go to next i
7. Print Fact
8. Stop
• Statements
• State
• Functions
Statements / Instructions
State
• Computational processes in the real-world have state. As a process evolves, the state
changes.
• State is a basic and important abstraction. An algorithm starts from the initial state
with some input values. As actions are performed, its state changes. It ends with a
final state.
• During computational process the state is stored in one or more the data structures.
Control Flow
There are three important control flow statements to alter the control flow depending on the
state.
They are,
These control flows allow the program to make choices, change direction or repeat actions.
FUNCTIONS
In some cases, algorithms can become very complex. The variables of an algorithm and
dependencies among the variables may be too many. Then, it is difficult to build algorithms
correctly.
In such situations, we break an algorithm into parts, construct each part separately, and then
integrate the parts to the complete algorithm.
Any complex problem will become simpler if the problem is broken smaller and the smaller
problems are solved.
A function is a block of organized, reusable code that is used to perform a similar task of
some kind.
Functions avoid the repetition of some codes over and over. It helps easy debugging, testing
and understanding of the program.
Functions provide better modularity and high degree of reusability for the problems.
FLOWCHART
A flowchart is drawn using boxes of different shapes with lines connecting them to show the
flow of control.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual
form.
The logic of the program is communicated in a much better way using a flowchart. Since
flowchart is a diagrammatic representation, it forms a common medium of communication.
Flowchart Symbols
A flowchart is drawn using different kinds of symbols. Every symbol used in a flowchart is
for a specific purpose
Symbol Meaning
drawing a flowchart
3. Only one flow line should come out from a process symbol.
4. Only one flow line should enter a decision symbol. However, two or three flow lines may
leave the decision symbol.
Advantages of flowchart:
1. Communication: - Flowcharts are better way of communicating the logic of a system to all
concerned.
2. Effective analysis: - With the help of flowchart, problem can be analyzed in more
effective way
1. Complex logic: - Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may require re-
drawing completely.
4. Cost: For large application the time and cost of flowchart drawing becomes costly.
PSEUDOCODE:
o Pseudo code consists of short, readable and formally styled English languages
used for explain an algorithm.
o It does not include details like variable declaration, subroutines.
o It is easier to understand for the programmer or non programmer to understand
the general working of the program, because it is not based on any
programming language.
o It gives us the sketch of the program before actual coding.
o It is not a machine readable
o Pseudo code can’t be compiled and executed.
o There is no standard syntax for pseudo code.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.
The interactive mode is a command line shell, which gives immediate feedback for each
statement, fed in the active memory. As new lines are fed into the interpreter, the fed program
is evaluated both in part and in whole.
The script mode is the mode where the scripted and finished .py files are run in the Python
interpreter.
Python Interactive Mode Python allows the user to work in an interactive mode.
It is a way of using the Python interpreter by executing Python commands from the
command line with no script. This allows the user to type an expression, and immediately the
expression is executed and the result is printed.
To start an interactive mode, The “>>>” is the prompt used in the Python interactive mode
which indicates that the prompt is waiting for the Python command and produces the output
immediately.
Example:
>>>5+7
12
>>>print(num)
Hello world !
>>>num=10
>>>num=num/2
5.0
Working in the interactive mode is convenient for testing a single line code for instant
execution. But in the interactive mode, we cannot save the statements for future use and we
have to retype the statements to run them again.
To write multiline code in Python interactive mode, hit Enter key for continuation lines, this
prompts by default three dots (…). The continuation lines are needed only in the case of
procedures, branching, loop constructs. When it happens, press a tab for indentation.
Example:
>>>flag=1
>>>if flag:
… print(“WELCOME TO PYTHON.”)
WELCOME TO PYTHON.
>>>
The Python interpreter is a program that reads and executes Python code, in which Python
statements can be stored in a file. The Python system reads and executes the commands from
the file, rather than from the console. Such a file is termed as Python program. Depending on
the environment, start the interpreter by clicking on an icon, or by typing python on a
command line.
The first three lines contain information about the interpreter and the operating system it is
running on.
The last line >>> is a prompt (chevron) that indicates that the interpreter is ready to enter
code.
If the user types a line of code and hits Enter, the interpreter displays the result:
In the interpreter or script mode, a Python program (script) is written in a file, where file
name has extension “.py”. The Python script is executed by the Python interpreter. By
default, the Python scripts are saved in the Python installation folder. Once the script is
created, it can be executed again and again without retyping. The Scripts are editable.
To execute a script, Type the file name along with the path at the prompt.
For example,
>>>python sum.py
Enter 2 numbers 6 3
The sum is 9
INDENTATION
Indentation in Python refers to the whitespace (spaces or tabs) at the beginning of a line of
code. In contrast to many programming languages that use curly braces or specific keywords
to define code blocks, Python uses indentation to mark the boundaries of its code blocks. This
makes indentation a fundamental and mandatory part of Python's syntax.
The key aspects of indentation in Python Statements with the same level of indentation are
considered part of the same code block.
For example, the statements within an if statement, for loop, while loop, or function
definition are grouped by their shared indentation level.
Indentation is not merely a stylistic choice for readability. It is a strict requirement of the
Python interpreter. Incorrect or inconsistent indentation will result in an Indentation Error.
All lines within a single code block must have the same number of leading spaces or tabs.
Mixing spaces and tabs for indentation within the same file or even the same block is strongly
discouraged and can lead to errors.
The Python community widely recommends using four spaces per indentation level. While
other amounts (e.g., two spaces, eight spaces, or tabs) are technically allowed, four spaces is
the conventional standard for consistency and readability.
Example:
sum=0
i=1
while i<=n:
sum=sum+i*i
i+=1
print('Sum = ',sum)
COMMENTS
Comments are used to explain the code, making it more readable and understandable for
both the programmer and non programmers who might work with the code in the future.
Everything following the # till the end of that line is treated as a comment and the interpreter
simply ignores it while executing the statement.
# swap.py
Python does not have a dedicated syntax for multi-line comments like some other languages,
multi-line strings enclosed in triple quotes (''' or """) are often used for this purpose.
''' This is a multi-line comment. swap.py swapping the values of a two variable program '''
ERROR MESSAGES
A programmer can make mistakes while writing a program, and hence, the program may not
execute or may generate wrong output.
The process of identifying and removing such mistakes, also known as bugs or errors, from a
program is called debugging.
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax Errors Like other programming languages, Python has its own rules that determine its
syntax. The interpreter interprets the statements only if it is syntactically (as per the rules of
Python) correct. If any syntax error is present, the interpreter shows error message(s) and
stops the execution there.
Example: Parentheses must be in pairs, so the expression (20 + 22) is syntactically correct,
whereas (17 + 35 is not due to absence of right parenthesis.
Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly. A logical error
produces an undesired output but without abrupt termination of the execution of the program.
Since the program interprets successfully even when logical errors are present in it, it is
sometimes difficult to identify these errors.
The only evidence to the existence of logical errors is the wrong output.
While working backwards from the output of the program, one can identify what went wrong.
Example: To find the average of two numbers 10 and 12 and we write the code as 10 + 12/2,
it would run successfully and produce the result 16.
The correct code to find the average should have been (10 + 12)/2 to give the correct output
as 11.
Logical errors are also called semantic errors as they occur when the meaning of the program
(its semantics) is not correct.
Runtime Error
Runtime error is when the statement is correct syntactically, but the interpreter cannot
execute it. Runtime errors do not appear until after the program starts running or executing.
Variables
Variables are used to store data that can be referenced and manipulated throughout a
program.
Rules for Naming Variables
name = "Alice"
age = 20
height = 5.4
# Printing values
print(name)
print(age)
print(height)
# Output:
# Alice
# 20
# 5.4
Keywords
Example
import keyword
print(keyword.kwlist)
Statements
⮚ Statement is a unit of code that has an effect, like creating a variable or displaying a
value
>>> n=7
>>> print(n)
Expressions
>>> 42
>>>42
>>>a=2
>>>a+3+2
>>>7
>>>z=("hi"+"friend")
>>>print(z)
>>>hifriend
Output
Operators in Python
⮚ Operators are the constructs which can manipulate the value of operands
⮚ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator
⮚ Types of operators
o Arithmetic Operators
o Comparison Operators
o Logical Operators
o Assignment Operator
o Membership Operator
o Identity Operator
o Bitwise Operator
Arithmetic Operators
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Operator Name Expression Example Output
+ Addition x+y 15+4 19
- Subtraction x-y 15-4 11
* Multiplication x*y 15*4 60
/ Division x/y 15/4 3.75
% Modulus x%y 15%4 3
** Exponentiation x**y 15**4 50625
// Floor Division x//y 40//20 3
Example Program
c=a+b
print("Result of addition", c)
c=a-b
print("Result of subtraction", c)
c=a*b
print("Result of Multiplication", c)
c=a/b
print("Result of Division", c)
c=a%b
print("Result of Modulus", c)
c=a**b
print("Result of Exponent", c)
c=a//b
Output
Comparison Operators
Example Program
x=54
y=18
print('x>y is',x>y)
print('x<y is',x<y)
print('x==y is',x==y)
print('x!=y is',x!=y)
print('x>=y is',x>=y)
print('x<=y is',x<=y)
Output
Logical Operators
Example Program
x='true'
y='false'
print('x or y is', x or y)
Output
Assignment Operators
● Assignment operators are used in Python to assign values to variables. a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.
Example Program
x=12
y=15
x+=y
print("x+=y:",x)
x-=y
print("x-=y:",x)
x*=y
print("x*=y:",x)
x/=y
print("x/=y:",x)
x%=y
print("x%=y:",x)
x**=y
print("x**=y",x)
x//=y
print("x//=y",x)
Output
x+=y: 27
x-=y: 12
x*=y: 180
x/=y: 12.0
x%=y: 12.0
x**=y 1.5407021574586368e+16
x//=y 1027134771639091.0
Membership Operators
Example Program
x="Python Program"
print('y' in x)
print('p' in x)
print('hello' not in x)
print('n' not in x)
Output
Identity Operators
Example Program
x1 = 5
y 1= 5
x2 = 'Hello'
y2 = 'Hello'
print(x2 is y2)
Bitwise Operators
& Bitwise AND X&Y Both operands are true result is true
>> Bitwise right shift X>>2 Operands are shifted right by number of
times specified
<< Bitwise left shift X<<2 Operands are shifted left by number of
times specified
Operator Precedence
Operator Description
BUILT IN FUNCTIONS
Built-in functions are the functions that are always available in Python without needing to
import any module.
They help perform common tasks such as input/output, type conversion, mathematical
operations, and more.
print()
print("Hello World")
input()
type()
Returns the type of a variable or value
type(123) #
len()
len("Python") # 6
max()
max(4, 9, 2) # 9
min()
min(4, 9, 2) # 2
sum()
sum([1,2,3]) # 6
round()
Rounds a number to the nearest integer or given decimal place round(3.14159, 2) # 3.14
abs()
abs(-10) # 10
print("Hello", name)
print("Maximum:", max(numbers))
print("Minimum:", min(numbers))
print("Sum:", sum(numbers))
# Sample Output:
# Hello Alice
# Total elements: 4
# Maximum: 40
# Minimum: 10
Python packages are a way to organize and structure code by grouping related modules into
directories. A package is essentially a folder that contains an __init__.py file and one or more
Python files (modules). This organization helps manage and reuse code effectively, especially
in larger projects. It also allows functionality to be easily shared and distributed across different
applications. Packages act like toolboxes, storing and organizing tools (functions and classes)
for efficient access and reuse.
1. Create a Directory: Make a directory for your package. This will serve as the root
folder.
2. Add Modules: Add Python files (modules) to the directory, each representing specific
functionality.
3. Include __init__.py: Add an __init__.py file (can be empty) to the directory to mark it
as a package.
4. Add Sub packages (Optional): Create subdirectories with their own __init__.py files
for sub packages.
5. Import Modules: Use dot notation to import, e.g., from mypackage.module1 import
greet.
Example :
In this example, we are creating a Math Operation Package 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.
math_operations/__init__.py:
This __init__.py file initializes the main package by importing and exposing the calculate
function and operations (add, subtract, multiply, divide) from the respective sub-packages for
easier access.
math_operations/calculator.py:
This calculate file is a simple placeholder that prints "Performing calculation...", serving as a
basic demonstration or utility within the package.
def calculate():
print("Performing calculation...")
math_operations/basic/__init__.py:
This __init__.py file initializes the basic sub-package by importing and exposing 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.
math_operations/basic/add.py:
return a + b
math_operations/basic/sub.py:
return a – b
In the same way we can create the sub package advanced with multiply and divide modules.
Now, let's take an example of importing the module into a code and using the function:
calculate()
In this segment, we'll explore a diverse array of Python frameworks designed to streamline
web development. From lightweight and flexible options like Flask and Bottle to
comprehensive frameworks like Django and Pyramid, we'll cover the spectrum of tools
available to Python developers. Whether you're building simple web applications or complex,
high-performance APIs, there's a framework tailored to your needs.
• Flask: Flask is a lightweight Python web framework that simplifies building web
applications, APIs, and services with an intuitive interface
• Django: Django is a Python web framework that enables fast, efficient development
with features like URL routing, database management, and authentication
• Bottle: Bottle is a lightweight Python web framework for building small applications
and APIs with minimal effort, ideal for prototyping and simplicity.
In this segment, we'll explore a selection of essential Python packages tailored for AI and
machine learning applications. From performing statistical analysis and visualizing data to
delving into advanced topics like deep learning, natural language processing (NLP),
generative AI, and computer vision, these packages offer a comprehensive toolkit for tackling
diverse challenges in the field.
Statistical Analysis
Here, we'll explore key Python libraries for statistical analysis, including NumPy, Pandas,
SciPy, XGBoost, StatsModels, Yellowbrick, Arch, and Dask-ML. From data manipulation to
machine learning and visualization, these tools offer powerful capabilities for analyzing data
effectively.
• NumPy
• Pandas
• SciPy
• XGBoost
• StatsModels
• Yellowbrick
• Arch
• Dask-ML
Data Visualization
Here, we'll explore a variety of Python libraries for creating stunning visualizations. From
Matplotlib to Seaborn, Plotly to Bokeh, and Altair to Pygal, we've got you covered. By the
end, you'll be equipped to transform your data into compelling visual narratives.
• Matplotlib
• Seaborn
• Plotly
• Bokeh
• Altair
• Pygal
• Plotnine
• Dash
Deep Learning
Here, we'll explore essential frameworks like TensorFlow, PyTorch, Keras, and more. From
Scikit-learn for supervised learning to Fastai for advanced applications, we'll cover a range of
tools to unlock the potential of deep learning.
• Scikit-learn
• TensorFlow
• torch
• Keras
• Keras-RL
• Lasagne
• Fastai
Here, we'll explore essential NLP tools and libraries in Python, including NLTK, spaCy,
FastText, Transformers, AllenNLP, and TextBlob.
• NLTK
• spaCy
• FastText
• Transformers
• fastText
• AllenNLP
• TextBlob
Genrative AI
In this segment, we'll explore a range of powerful tools and libraries that enable the creation
of artificial intelligence models capable of generating novel content. From the renowned deep
learning framework Keras to the natural language processing library spaCy, we'll cover the
essential tools for building generative AI systems.
• Keras
• spaCy
• generative
• GPy
• Pillow
• ImageIO
• Fastai
Computer Vision
Here, we'll explore essential Python libraries like OpenCV, TensorFlow, and Torch,
alongside specialized tools such as scikit-image and Dlib. From basic image processing to
advanced object detection, these libraries empower you to tackle diverse computer vision
tasks with ease.
• OpenCV
• TensorFlow
• torch
• scikit-image
• SimpleCV
• ImageAI
• imageio
• Dlib
• Theano
• Mahotas
• tk-tools
• tkcalendar
• tkvideoplayer
• tkfilebrowser
• PySide: Python PySide is a set of Python bindings for the Qt application framework.
It allows developers to create graphical user interfaces (GUIs) using Qt tools and
libraries within Python code, enabling cross-platform desktop application
development with ease.
• NiceGUI: Nicegui is a Python package that simplifies creating buttons, dialogs, plots,
and 3D scenes with minimal code, ideal for micro web apps, dashboards, robotics,
smart home solutions, and development tasks like machine learning and motor control
adjustments.
• PyGTK: PyGTK is a set of Python bindings for the GTK (GIMP Toolkit) library,
which is a popular toolkit for creating graphical user interfaces (GUIs). With PyGTK,
developers can create cross-platform GUI applications in Python using GTK's rich set
of widgets and tools.
In this concise guide, we'll explore a curated selection of powerful Python packages tailored
for web scraping and automation tasks. From parsing HTML with Beautiful Soup to
automating browser interactions with Selenium, we'll cover the essentials you need to embark
on your web scraping and automation journey. Additionally, we'll introduce other handy tools
like MechanicalSoup, urllib3, Scrapy, Requests-HTML, Lxml, pyautogui, schedule, and
Watchdog, each offering unique functionalities to streamline your development process.
• Request: Python Requests is a versatile HTTP library for sending HTTP requests in
Python. It simplifies interaction with web services by providing easy-to-use methods
for making GET, POST, PUT, DELETE, and other HTTP requests, handling headers,
parameters, cookies, and more.
• BeautifulSoup: Python BeautifulSoup is a library used for parsing HTML and XML
documents. It allows you to extract useful information from web pages by navigating
the HTML structure easily.
• Selenium: Python Selenium is a powerful tool for automating web browsers. It allows
you to control web browsers like Chrome or Firefox programmatically, enabling tasks
such as web scraping, testing, and automating repetitive tasks on websites.
• urllib3: Python urllib3 is a powerful HTTP client library for Python, allowing you to
make HTTP requests programmatically with ease. It provides features like connection
pooling, SSL verification, and support for various HTTP methods.
• Scrapy: Python Scrapy is a powerful web crawling and web scraping framework used
to extract data from websites. It provides tools for navigating websites and extracting
structured data in a flexible and efficient manner.
• Lxml: Python lxml is a powerful library used for processing XML and HTML
documents. It provides efficient parsing, manipulation, and querying capabilities,
making it a popular choice for working with structured data in Python.
Here, we'll explore the exciting world of game development in Python, leveraging powerful
packages and libraries to bring your gaming ideas to life. Let's dive in and discover the tools
that will empower you to create immersive and entertaining gaming experiences.
• PyGame: PyGame is a set of libraries and tools for creating video games and
multimedia applications using Python. It provides functions for handling graphics,
sound, input devices, and more, making it easier to develop games with Python.
• Pyglet: Pyglet is a Python library used for creating games and multimedia
applications. It provides tools for handling graphics, sound, input devices, and
windowing. With Pyglet, developers can build interactive experiences efficiently in
Python.