Introduction to Python
Computer Programming: It is a set of instructions or a code written by a programmer in a
syntax to deliver instructions to the computer to accomplish a task.
Logic and Flow: Logic in programming is the systematic approach to problem-solving that
enables a program to process data, make decisions, and execute tasks using defined
rules and structures.
Flow is the sequence in which a program’s instructions are executed, including decisions,
loops, and function calls.
Pseudocode: Pseudocode is a simplified, informal way of writing algorithms using plain
language and basic programming concepts, without specific syntax rules of a
programming language. It helps in planning and understanding logic before actual coding.
Algorithm: Algorithm is a step-by-step set of instructions or rules designed to solve a
problem or perform a task efficiently.
An algorithm has several key characteristics that make it effective and efficient:
1. Well-defined – Each step must be clear and unambiguous.
2. Input – It may accept zero or more inputs to process.
3. Output – Produces at least one output or result.
4. Finiteness – The algorithm must complete in a finite number of steps.
5. Effectiveness – Each step should be feasible and executable.
6. Definiteness – It should follow a precise sequence without ambiguity.
7. Generalizability – The algorithm should work for a wide range of inputs.
FlowChart: A flowchart is a graphical representation of an algorithm or process, using
symbols to show the sequence of operations and decision-making. It helps visualize the
logical flow of a program or system.
Common Flowchart Symbols:
● Oval – Represents the start and end (Start, End).
● Rectangle – Represents a process or action (Calculation, Assignment).
● Parallelogram- Represents input or Output
● Diamond – Represents a decision (Yes/No, True/False).
● Arrow – Shows the flow direction between symbols.
Here are some advantages of using flowcharts:
1. Easy to Understand – Provides a visual representation of processes, making
complex logic simpler.
2. Efficient Debugging – Helps identify errors or inefficiencies in a system before
implementation.
3. Improves Documentation – Serves as a useful reference for developers and
stakeholders.
4. Enhances Communication – Makes discussions about logic and processes clearer
among teams.
5. Systematic Problem-Solving – Helps break down a task into smaller, manageable
steps.
6. Standardized Representation – Uses universally recognized symbols for
consistency.
7. Saves Time – Streamlines planning and execution of programming logic.
Introduction to Programming
Computer Program: A computer program is a set of instructions written in a programming
language that a computer follows to perform specific tasks. It tells the computer how to
process data, make decisions, and execute operations, enabling software, applications,
and systems to function.
Programming languages can be categorised into three main levels:
● Machine code is the low-level binary language (0s and 1s) that a computer’s
processor directly understands and executes.
● A low-level language is a programming language close to machine code that
directly interacts with hardware, like assembly language and machine code.
● High-level languages are programming languages that are user-friendly, closer to
human language, and abstract away hardware details, like Python, Java, and C++.
AI Programming Languages:
● LISP is an old but powerful programming language designed for AI and symbolic
computation, known for its list-based structure, recursion, and ability to
manipulate its own code.
● Prolog is a logic-based programming language used for AI, expert systems, and
natural language processing, relying on facts, rules, and queries to perform
reasoning and pattern matching.
● Python is a high-level, general-purpose programming language known for its
simplicity, readability, and versatility. It was created by Guido van Rossum and
is widely used in web development, data science, artificial intelligence, automation,
and more.
Key Features of Python:
● Easy to Learn & Read – Uses simple, clear syntax.
● Interpreted Language – Executes code line by line without compilation.
● Extensive Libraries – Supports AI, machine learning, data analysis, and
more.
● Cross-Platform – Works on Windows, macOS, and Linux.
● Large Community Support – Extensive resources and community
contributions.
● R is a programming language used for data analysis, statistics, and
visualization, widely popular in data science and research due to its powerful
tools and libraries.
● JavaScript is a powerful programming language used to create interactive and
dynamic web pages. It allows developers to control website behavior, respond to
user actions, and manipulate content in real time.
Python Introduction:
Python is a high-level, general-purpose programming language known for its simplicity,
readability, and versatility. It was created by Guido van Rossum and released in 1991.
Python is widely used in web development, data science, artificial intelligence, automation,
and more.
In python source code is not compiled directly into machine code. Instead, the python
interpreter reads and translates the human-written source code, line by line an interpreter
reads and translates the human written source code, line by line into an intermediate form,
known as bytecode.
Python's Suitability for AI:
● Easy to Learn & Use – Simple syntax makes AI development accessible.
● Extensive Libraries – Supports AI with tools like TensorFlow, PyTorch, and
scikit-learn.
● Strong Community Support – Large developer base for guidance and resources.
● Cross-Platform – Works on Windows, Linux, and macOS effortlessly.
● Integration-Friendly – Compatible with C++, Java, and R for AI projects.
● High Flexibility – Enables quick prototyping and scaling for complex AI models.
● Interactive mode– Python supports an interactive mode, facilitating real-time
testing and debugging code snippets.
● Database support and scalability– Python offers interfaces to both major
commercial and open-source databases.
Applications of Python:
Python is used in various fields due to its flexibility and powerful libraries. Here are some
key applications:
● Web Development – Frameworks like Django and Flask help build dynamic
websites.
● Data Science & Machine Learning – Libraries like NumPy, Pandas, TensorFlow,
and scikit-learn make data analysis and AI development easy.
● Automation & Scripting – Used for automating tasks, testing, and workflow
optimization.
● Game Development – Libraries like Pygame help create interactive games.
● Cybersecurity – Used for ethical hacking and security analysis.
● Internet of Things (IoT) – Helps in IoT-based projects with frameworks like
MicroPython.
● Finance & FinTech – Used for stock market analysis, risk assessment, and
algorithmic trading.
● Scientific Computing – Supports complex calculations in physics, chemistry, and
engineering.
● Robotics & Embedded Systems – Helps in robotic programming and hardware
control.
Primary working Modes in Python:
Interactive Mode: This mode allows the user to directly run commands on the Python
interpreter prompt denoted by “>>>”.
Script Mode: As Interactive mode cannot save our source code for future references, i.e
all the typed instructions get erased as we close the shell mode. This is why we switch to
script mode, which allows us to save the set of commands or programs we type.
Python Building Blocks: Statements and Expressions
In programming, a statement is an instruction that a computer executes to perform an
action. Statements can include variable assignments, function calls, loops, and conditional
operations. Types of Statements:
● Assignment Statements – Assign values to variables (e.g., x = 10).
● Conditional Statements – Control flow based on conditions (e.g., if x > 5:
print("Greater")).
● Loop Statements – Repeat actions (e.g., for i in range(5): print(i)).
● Function Call Statements – Execute functions (e.g., print("Hello!")).
An expression in programming is a combination of values, variables, operators, and
function calls that produce a result. It can perform calculations, comparisons, or
manipulate data.
Examples of Expressions:
● Arithmetic Expression: x + y (Adds two numbers)
● Logical Expression: x > y (Checks if x is greater than y)
● String Expression: "Hello" + "World" (Joins two strings)
Multi-line Statements in Python
In Python, statements are usually written in a single line, but sometimes they need to be
extended across multiple lines for readability and complexity. Here are ways to handle
multi-line statements:
● Using a Backslash (\) – Explicitly continues a statement across multiple lines:
total = 100 + 200 + \
300 + 400
print(total) # Output: 1000
● Using Parentheses (()) – Automatically continues inside parentheses:
numbers = (1, 2, 3,
4, 5, 6)
print(numbers)
● Using Brackets ([]) – Works similarly for lists:
fruits = ["apple", "banana",
"cherry", "mango"]
print(fruits)
● Using Curly Braces ({}) – Helps in dictionaries and sets:
person = {"name": "Alice",
"age": 25,
"city": "New York"}
print(person)
Comments in Python
Comments in Python are used to explain code, increase readability, and prevent execution
of specific lines. They help developers understand and maintain their programs.
Types of Comments in Python:
● Single-line Comments (#) – Used for short explanations:
# This is a single-line comment
x = 10 # Assigning value to x
● Multi-line Comments (Using """ or ''') – Ideal for longer descriptions:
"""
This is a multi-line comment.
It explains a block of code.
"""
print("Hello, Python!")
● Inline Comments – Placed at the end of a code line for clarification:
y = 20 # Setting y to 20
Keywords and Identifiers:
Keywords in Python are reserved words that have special meaning in the language and
cannot be used as variable names. They define the syntax and structure of Python
programs.
All the python keywords are in lower case, whereas three keywords such as None, True &
False start with upper case.
False await else import pass None break except in
raise True class finally is return and continue for
lambda try as def from nonlocal while assert del
global not with async elif if or yield
Identifiers in Python
An identifier in Python is the name given to variables, functions, classes, or objects. It
helps uniquely define elements within a program.
Rules for Identifiers:
● Must start with a letter (A-Z or a-z) or an underscore (_).
● Can contain letters, digits (0-9), and underscores.
● Cannot use Python keywords as identifiers.
● Case-sensitive (name and Name are different).
● Space and special characters like @ # $ % ^ & (except underscore) are not allowed
in identifiers.
Examples of Identifiers in Python
Valid Identifiers:
myVariable = 10 # Uses letters
_studentName = "Alice" # Can start with an underscore
PI_value = 3.14 # Uses a mix of uppercase and lowercase letters
user123 = "John" # Can include numbers (but not at the start)
Invalid Identifiers:
2number = 20 # ❌
❌ Cannot start with a digit
class = "data"
user-name = "Alice"
my variable = 50
#
#
#
❌ Cannot use Python keywords
❌ Hyphens (-) are not allowed
Spaces are not allowed in identifiers
Python Variables:
A variable in Python is used to store data that can be reused and modified throughout a
program. Variables help in organizing and managing information efficiently.
Key Features of Variables in Python:
● Dynamic Typing – No need to declare a type; Python automatically assigns it.
● Flexible Storage – Variables can hold numbers, strings, lists, dictionaries, etc.
● No Explicit Declaration – Just assign a value to create a variable.
● Case-Sensitive – name and Name are treated as different variables.
● Easy Modification – Changing a variable's value updates its usage throughout the
program.
Variable: Creation and Assignment:
To create a variable in python you simply choose one name for the variable and use
the assignment operator (=) to assign a value to it.
Variable_name= value
Reassigning variable: Python allows you to re assign a new value to an existing variable
simply by using the assignment operator again.
>>>a=10
>>>print(a)
>>>10
>>>a=15
>>>print(a)
>>>15
Assigning multiple variables in a single line: Python allows you to assign multiple
variables in a single line by separating the variable names and values with commas.
>>>a,b,c=5,6,7
>>>print(a)
>>>5
>>>print(b)
>>>6
>>>print(c)
>>>7
Data types in python: Data types in Python define the nature of the values that variables
can hold. They specify how the data is stored and manipulated. The primary data types
include:
● Integer (int) – Represents whole numbers (e.g., 5, -20).
○ Boolean (bool) – Represents truth values (True or False).
● Floating Point (float) – Represents decimal numbers (e.g., 3.14, -0.5).
● String (str) – Represents text enclosed in quotes (e.g., "hello", 'Python').
● List (list) – Ordered, mutable collection of items (e.g., [1, 2, 3]).
● Tuple (tuple) – Ordered, immutable collection of items (e.g., (10, 20, 30)).
● Dictionary (dict) – Key-value pairs for data mapping (e.g., {"name": "Alice", "age":
25}).
Python operators: Operators in Python are symbols that perform operations on variables
and values. They help in computations and logic execution. Python supports various types
of operators:
● Arithmetic Operators (+, -, *, /, %, **, //) – Perform mathematical operations.
● Relational Operators (==, !=, >, <, >=, <=) – Compare values and return True or
False.
● Logical Operators (and, or, not) – Used for conditional logic.
● Assignment Operators (=, +=, -=, *=, /=, %=, **=, //=) – Assign or modify values.
Python Input and output: Input and output operations allow users to interact with a
program by providing data and receiving results.
print() function in Python: The print() function in Python displays output on the screen. It
helps show text, numbers, and results from a program.
What It Does:
● Displays messages or variables.
● Helps with debugging by showing values.
● Formats output using separators or special formatting.
Basic Example:
>>> print("Hello, world!")
>>> Output:
>>> Hello, world!
Printing Multiple Items:
>>> name = "Alice"
>>> age = 25
>>> print("Name:", name, "Age:", age)
>>> Name: Alice Age: 25