0% found this document useful (0 votes)
33 views80 pages

FALLFRE2025-26 CSE1012 ETH AP2025263000055 2025-09-15 Reference-Material-I

Uploaded by

spsreeganesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views80 pages

FALLFRE2025-26 CSE1012 ETH AP2025263000055 2025-09-15 Reference-Material-I

Uploaded by

spsreeganesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

Problem Solving using Python

(Course Code: CSE1012)

Dr. M. S. Krishna
Assistant Professor Sr Grade 1
School of Electronics Engineering (SENSE)
VIT-AP University
E-Mail: [email protected]
COURSE SYLLABUS

MODULE 1: Introduction to Problem Solving (8 Hours)


Problem Solving definition and steps, developing an algorithm, flowcharts and
pseudocode, Introduction to Python, Interactive and script mode, Indentation, Comments,
Tokens in Python – Variables, Keywords, Literals, Data types, Expressions, Input and
Print functions.
MODULE 2: Operators and Branching (6 Hours)
Operators and its precedence, Arithmetic Operators, Comparison (Relational) Operators,
Assignment Operators, Logical Operators, Bitwise Operators, Membership Operators,
Identity Operators, Branching Statements-if; if else, nested if; nested if else, elif
MODULE 3: Loops and Regular Expressions (7 Hours)
Creating Loops with while and for, Different versions of Loops, Nested Loops, Loop
Control Statements, Loop Modification with break, continue and pass, Regular
Expressions.
ZERO HOUR
COURSE SYLLABUS
MODULE 4: Basic Data Structures (8 Hours)
Creating, Accessing and Manipulating Lists, Sets, Tuples and Dictionaries, Understanding
the differences among them, Applications of the Data Structures. Using Branching and
Control loops with Data structures, Matrix Operations using Numpy
MODULE 5: Functions (8 Hours)
Pre-defined functions, User defined functions, formal and actual parameters, return
statement, Using Branching, Looping and Data structures in Functions, Recursion,
Internal workflow of Recursion, Modules.
MODULE 6: Working with Numbers, Strings and Files (8 Hours)
Introduction to Different Numeric Types, Type Conversion, Mathematical Functions,
Random Numbers. Creating and Accessing Strings, Operations on Strings, Indexing,
Slicing, String Manipulations, Pre-defined functions on Strings.
File I/O-Opening and Closing files, Different modes, File attributes, Read, Write
Operations, File Positions. Renaming and Deleting Files, various directory handling
functions.

ZERO HOUR
BOOKS
Text Books
1. Kenneth Lambert, “Fundamentals of Python: First Programs”, Cengage Learning, 2019
2. Martin C Brown, “The Complete Reference with Python”, McGrawHill, 2018.

Reference Books
1. John Zelle, Python Programming: An introduction to Computer Science, Franklin Associates, Third
Edition, 2016.
2. Mark Lutz, “Learning Python”, Fifth edition, O’Reilly, 2013.

ZERO HOUR
CONTENT
S

Lecture-1

 Problem Solving definition and steps

 Developing an algorithm
 Flowcharts and pseudocode
 Introduction to Python
 Interactive and script mode
 Indentation, Comments

Number Systems 5
CONTENT
S

Lecture-1

 Tokens in Python – Variables, Keywords,


Literals, Data types, Expressions
 Input and Print functions.

Number Systems 6
Problem Solving definition and steps

Problem solving in Python refers to the process of understanding a problem, designing a


logical solution, and implementing it using Python programming constructs (like variables,
loops, conditionals, functions, etc.) to achieve the desired result.
Problem Solving definition and steps
Problem Solving definition and steps
Algorithm

 Algorithm and flowcharts are two essential problem-solving tools used in computer science and
various other fields to design and represent step-by-step solutions to problems.
 An algorithm is a precise, systematic, and unambiguous step-by-step set of instructions for solving
a particular problem
 An algorithm provides a blueprint to writing a program to solve a particular problem. It is
considered to be
 an effective procedure for solving a problem in a finite number of steps. Algorithm should be:
 Be precise Algorithm: Addition
 Be unambiguous Input:Two numbers, A and B
Output:The sum of A and B
 Not even a single instruction must be repeated infinitely. 1. Start
 After the algorithm gets terminated, the desired result 2. Input A
3. Input B
 must be obtained 4. Calculate the sum = A + B
5. Output the sum
6. End
ALGORITHMS
Different Approaches to Design an Algorithm (Software design strategies used to structure
and develop algorithms and systems)
Top-down approach starts by dividing the complex algorithm into one or more modules.
This approach is often used when you have a clear understanding of the system's requirements and
you want to create a structured and organized design from the top-level goal down to the specific
implementation details.
Bottom-up approach is just the reverse of top-down approach. In the bottom-up design, we start
with designing
the most basic or concrete modules and then proceed towards designing higher level modules.
Once the lower-level modules are designed and tested, you integrate them to create larger
modules
The bottom-up approach is often used when you have existing components or libraries that you
want to reuse or when you want to incrementally build a system by adding functionality in smaller
increments. 11
Control Structures Used in Algorithms

Sequence means that each step of the algorithm is executed in the specified order.
Decision statements are used when the outcome of the process depends on some condition
Repetition, which involves executing one or more steps for a number of times, can be implemented
using constructs such as the while, do-while, and for loops.
Recursion is a technique of solving a problem by breaking it down into smaller and smaller sub-
problems
until you get to a small enough problem that it can be easily solved. Usually, recursion involves a
function calling itself until a specified condition is met.

12
Pseudocode

Pseudocode is a simple and informal way of representing an algorithm that uses the structural
conventions of a programming language. It uses keywords and phrases that are similar to those used
in programming languages, such as "if", "else", "for", and "while.
An ideal pseudocode must be complete, describing the entire logic of the algorithm, so that it
can be translated straightaway into a programming language.
Feature Algorithm Pseudocode
Precision More precise Less precise
Formality More formal Less formal
Purpose Solving problems Describing algorithms

Can be directly implemented Cannot be directly implemented in a


Implementatio in a programming
n programming language language 45

© OXFORD UNIVERSITY PRESS 2017. ALL


RIGHTS RESERVED.

13
Flowcharts
A flowchart is a graphical or symbolic representation of a process. It is basically used to
design and document virtually complex processes to help the viewers to visualize the logic of
the process.
an parallelogra Example: Draw a flowchart to calculate the
oval m sum of the first 10 natural numbers.

rectangl circl
e e

14
Flowcharts
Example: Draw a flowchart to add two numbers

1. Read the value of num1 from the user.


2. Read the value of num2 from the user.
3. Add num1 and num2
4. Display the value of sum as the result

15
Flow Charts
EXAMPLES

In the above flowchart, the logic fails at the


decision box. So Navigation in flowchart is
important
EXAMPLES
SOLVE: Exchange the Values of Two Variables

1. Start.
2. Store the value of a in a temporary
variable,c.
3. Store the value of b in a.
4. Store the value of a in b.
5. End.
SOLVE: COUNT NUMBER OF DIGITS IN AN INTEGER

Step 1: Initialize n to 0
Step 2: Repeat until
number is 0
Step 2a: Increment n by
1
Step 2b: Divide number
by 10 (integer division)
Step 3: Output n as the
count of digits
Step 4: End
SOLVE: FACTORIAL COMPUTATION

Step 1: Start
Step 2: Read a number n
Step 2: Initialize variables:
i = 1, fact = 1
Step 3: if i <= n go to step 4 otherwise
go to step 7 Step 4: Calculate fact = fact
*i
Step 5: Increment the i by 1 (i=i+1) and
go to step 3 Step 6: Print fact
Step 7: Stop
SOLVE: GENERATION OF THE FIBONACCI SEQUENCE
Introduction of Python

 What is Python?
• Python is
 programming language

 general-purpose

 high-level
 Who developed Python?
• Guido van Rossum

• Feb 20 1991
Introduction of Python

 Why Python?
Python is widely used because:
✅ Easy to learn and use – simple syntax, similar to English.
✅ Versatile –used in web development, Data science, AI, Automation, etc.
 Web Development (Django, Flask)
 Data Science & AI (NumPy, Pandas, TensorFlow, PyTorch)
 Automation/Scripting (automating tasks, writing utilities)
 Software Development (desktop apps, games, GUIs)
✅ Large community support – plenty of libraries and frameworks.
✅ Cross-platform – works on Windows, Linux, and Mac.
✅ Productive and efficient – reduces development time.
FEATURES

• Simple
• Extensible
• Easy to Learn
• Embeddable
• Versatile
• Extensive
• Free and Open
Source • Easy
• High-level maintenance
Language • Secure
• Interactive • Robust
• Portable • Multi-threaded
• Object Oriented • Garbage
• Interpreted Collection

• Dynamic
Advantages:

• Simple and Easy to Learn

• Cross-Platform and Interpreted

• Extensive Libraries and Frameworks

• Versatility (General-Purpose)

• Integration and Extensibility

• Rapid Development and Prototyping


Limitations of Python

• Parallel processing can be done in Python but not as elegantly as done in some
other languages (like JavaScript and Go Lang).
• Being an interpreted language, Python is slow as compared to C/C++. Python is
not a very good choice for those developing a high-graphic 3d game that takes up
a lot of CPU.
• It lacks true multiprocessor support.
• It has very limited commercial support point.

• It is difficult to pack up a big Python application into a single executable file.

This makes it difficult to distribute Python to non-technical.


Applications of Python
Applications of Python
Applications of Python
Interactive and script mode
Interactive mode
• Interactive means “working simultaneously and creating impact of our work on the other’s
work”.

• Interactive mode is based on this ideology only. In the interactive mode as we


enter a command and press enter, the very next step we get the output.
• The output of the code in the interactive mode is influenced by the last
command we give.
• Interactive mode is very convenient for writing very short lines of code.
• In python it is also known as REPL which stands for Read Evaluate Print Loop.
• Here, the read function reads the input from the user and stores it in memory.
• Eval function evaluates the input to get the desired output. Print function
outputs the evaluated result.
• The loop function executes the loop during the execution of the entire program
and terminates when our program ends.
Interactive mode

This mode is very suitable for beginners in programming as it helps them evaluate their code
line by line and understand the execution of code well.
Interactive mode

To check the version:


python --version
Disadvantages of interactive mode

• The interactive mode is not suitable for large programs.


• The interactive mode doesn’t save the statements. Once we make a
program it is for that time itself, we cannot use it in the future. In
order to use it in the future, we need to retype all the statements.
• Editing the code written in interactive mode is a tedious task. We
need to revisit all our previous commands and if still, we could not
edit we need to type everything again
Script Mode

• Script means a system of writing. In the script mode, a python program can
be written in a file.
• This file can then be saved and executed using the command prompt.
• We can view the code at any time by opening the file and editing becomes
quite easy as we can open and view the entire code as many times as we
want.
• Script mode is very suitable for writing long pieces of code. It is much
preferred over interactive mode by experts in the program.
• The file made in the script mode is by default saved in the Python
installation folder and the extension to save a python file is “.py”.
Example
Example
Differences between Interactive Mode and Script Mode
Differences between Interactive Mode and Script Mode
Indentation

• Whitespace at the beginning of the line is called indentation.


• Indentation helps determine which lines of code are part of a specific block,
such as a function, loop, or conditional statement.
Example:
Indentation

Rules of Indentation in Python


1. Indentation is mandatory
Every block of code (inside if, for, while, def, class, etc.) must be indented.
Without proper indentation, Python will raise an Indentation Error.
2. Consistent indentation
Use either spaces or tabs — but do not mix them.
The common standard is 4 spaces per indentation level.
3. Nested blocks need more indentation
Each deeper block requires additional indentation.
Indentation

Correct indentation:
print(“Hello world”)
if True:
print("Inside if block")
for i in range(3):
print(" Inside for loop:", i)
print("Outside all blocks")
Incorrect indentation:
if True:
print("This will cause an error")
Comments

• In Python, comments are notes you add in the code to explain what it does. They
are ignored by the Python interpreter and are only for humans reading the code.
Types of Comments in Python:
i. Single-line comments:
Start with # (hash symbol).Everything after # on that line is considered a comment.
Example:
x = 10 # Assigning 10 to x
ii. Multi-line comments:
Python doesn’t have a specific multi-line comment syntax. You can write multiple
single-line comments:
Comments

Alternatively, you can use triple quotes (''' or """) as a docstring-style comment (though
technically they are strings, not comments, unless used as documentation).
Tokens

• In Python, tokens are the smallest units in a program that the interpreter can
understand.
• When Python code is run, it is broken down into tokens during the lexical analysis
phase of compilation.
Types of Tokens in Python
1. Keywords
Reserved words in Python that have a special meaning.
Cannot be used as identifiers (variable names).
2. Identifiers
Names given to variables, functions, classes, etc.
Rules:
Must begin with a letter (a-z, A-Z) or underscore _.
Followed by letters, digits, or underscores.
Case-sensitive.
3. Literals
Constant values used in the program.
P Y T H O N VARIABLES

 Variable is a name which is usedto refer


memory location. Variable also known as identifier and
used to hold value
 An Identifier is used to identify the literals used in the
program. An variable starts with a letter alphabet or an
underscore (_)
 Variable does not allow other characters such as @, $, and %
 Variable is a case sensitive programming language
 Variable name should not match with keyword
 Variables can be re-declared even after you have declared
them for once
QUESTIO
N

 Comment on the validity of the following variables with


the reasoning?
a) VIT-AP b) VIT c) d)
AP VIT_AP Vit@AP
e)
17_VitAP f) g) f)
vIT_AP #VITAP VITap123
A SS I G N I N G O R I NIT I AL I Z I NG VALUES T O
VARIABLES

• InPython, programmers need not explicitly


declare variables to reserve memory space.
• The declaration is done automatically when a value is assigned
to the variable
using the equal sign (=).
• The operand on the left side of equal sign is the name of the
variable and the operand on its right side is the value to be
stored in that variable.
Example:
Types of Variables

There are two types of variables in Python - Local variable and Global
variable.
Local Variable:
The variables that are declared within the function and have scope within the
function are known as local variables. Let's examine the following illustration.
Example -
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)

# Calling a function
add()
Output:
The sum is: 50
Global Variables:
Global variables can be utilized all through the program, and its extension is in the
whole program. Global variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global variable.
Example -
def greet():
global b
a=30
b=20
print(a+b)
greet()
print(b)
print(a)
Output:
20
NameError: name 'a' is not defined
Delete a variable

Syntax :
del <variable_name>
In the following example, we create a variable x and assign value to it. We
deleted variable x, and print it, we get the error "variable x is not defined".
The variable x will no longer use in future.
Example -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Output:
NameError: name 'x' is not defined
COMMENTS

• Comments are the non-executable statements in a program.


• Python comments are used to add notes and explanations of the
code
• Comments make the program easily readable
and understandable by the programmer as well as
other users who are seeing the code.
• While executing the interpreter simply ignores the comments
• There are two types of comments in Python
 Single-line comments: Start with a hash symbol (#) and continue to
the end of the line. # This is a single-line comment.
 Multi-line comments: Start and end with three single quotes (''') or
three double quotes
(""").
""" This is a multi-line comment.
It can span multiple lines"""
INPUT OPERATION

• The input() function in Python is used to read a line of text input


from the user via the console or terminal.

 f-string, which is a way to format strings by embedding


expressions inside them.
 Inside the string, expressions are enclosed in curly braces
{}
 These expressions are evaluated at runtime, and their
values are inserted
into the string.
 F-strings are available in Python 3.6 and later versions.
Tokens

 Keywords: print, input


 Identifiers: Variables
 Literals: Constants
 Operators +,- etc
 Delimiters (), {},[] etc.
 Comment lines
Literals also referred as constants are data items that does not
change its value during program execution.
Python allows following types of literals:
String literals
Numeric literals
Boolean Literals
Special Literals

String Literals : Group of characters enclosed in single or


double quotation marks is known as String literals.
e.g. "Atomic‟, “Hello World”,
"12876‟ “8+9”, “12/1
RRCAT”
Python allows two types of string :
i) Single line strings : Text enclosed in single or double
quotation marks and terminate in single line.
e.g Text1=“Hello World”
ii)Multiline Strings : Text spread across multiple lines.
Multiline strings can be created in two ways:
a) By adding a backlash at the end of string before pressing
Enter to continue typing text on the next line.
e.g. Text=“Hello\
World”
b) By typing the text in
triple quotation marks.
e.g. “””Program to
calculate
area of
circle,
Numeric literals are of three different
types:
Numeric
Literals

int float complex

Decimal Octal
Fractional Exponent
Integer Integer
Form Form
Literals Literals

Hexadecimal
Integer
Literals
Integer literals are whole numbers without any fractional part. It must
have at least one digit and must not contain any decimal point.
It may contain either (+) or (-) sign.
Python allows three types of Integer literals:
i) Decimal Integer Literals :
An integer literals consisting of a sequence of digits in decimal
number system involving digits 0 to 9.
e.g. 786, 67, -4783
ii) Octal Integer Literals :
A sequence of digits starting with 0o (zero followed by letter o) in Octal
Number System involving digits 0 to 7.
e.g. 0o563, 0o2761
iii) Hexadecimal Integer Literals :
A sequence of digits starting with 0x or 0X (zero followed by letter x or
X) in Hexadecimal Number System involving digits 0 to 9 and letter A to
F. e.g. 0xAB8,0XC9B
iv. Binary Literals :
A sequence of digits starting with 0b or 0B (zero followed by letter x or
X) in binary Number System involving digits 0 and 1. e.g. 0b1010, 0b111
Floating literals are also called real literals. Real literals are numbers
having fractional parts.
They can be written in one of the two forms :
1. Fractional Form : A real literal in Fractional Form must consists of at
least one signed or unsigned digit either before or after a decimal point.
e.g. 2.0, 17.5, -0.3489, .7
2. Exponent Form : A real literal in Exponent form consists of
two parts : mantissa and exponent.
• . This is the first part of the notation and can be either an
integer (e.g., 183) or a proper real constant (e.g., 1.786, -
0.1894).The mantissa can include decimal points and may
be positive or negative.
• The mantissa is followed by a letter E or e. The
exponent must be an integer.
e.g. 1.786E05, 0.1786e1, 183E4, -0.1894E-3
A Boolean literal in Python is used to represent one of the two Boolean
values i.e. True or False.
e.g. Fees_Paid=True
Concession=False

Python has a special literal None. The None literal is used to indicate
absence of value in a data object. Python doesn‟t display anything if a
variable contains None value.
e.g. amount=None
Data Types in
Python

• In general, Data Types specifies what type of data will be stored in


variables.
Variables can hold values of different data types.

• Python is a dynamically typed or loosely typed language, hence we need


not define the type of the variable while declaring it.

• The interpreter implicitly binds the value with its type.

• Python provides us the type () function which enables us to


check the type of the variable.
Mutable vs. Immutable Data
Types
 Data objects of all types are values stored at specific locations in a computer’s memory
 All data types fall into one of two categories:
□ Immutable
 Values cannot be modified after the variable is created in memory
 Numbers – int , float, complex
 Stri ngs – str
 Tuples – tuple
□ Mutable
 Values can be modified after variable creation
 C a n add, delete, insert, and rearrange items in a mutable sequence
 Lists – list
 Dictionaries – dict
Webb ENGR 102
 Sets – set
D a t a Types – i n t

 Integers
□ Zero, positive, and negative whole
numbers
>>> a = 7
>>> x = -
4
 >>> a N
If you assign = 0
whole-number value to a variable, it will
automatically be cast as an int
D a t a Types – fl o at

 Floating point numbers


□ Positive, and negative non-whole
numbers >>> a = 2.71
>>> x = -4.5
> > > big N u m = 1.8e12
> > > smallNum = 6.4E-9
 If you assign a non-whole-number value to a variable, it will automatically be
cast as a float
D a t a Types – c o m p l e x

 Complex numbers
□ Numbers with real and imaginary parts
> > > z = 3 + 2j
> > > b = -4.5 + 6j
> > > V = 105 – 18.6j
 j is the imaginary unit
□ j = −1
D a t a Types – s t r

 Strings
□ Sequences of alpha-numeric characters
□ Enclosed in single, double, or triple quotes

> > > str_1 = 'Hello, World!'

> > > Name = "John Doe"

> > > ml_string = '''Multi-line strings are enclosed in


triple quotes.'''
Data Types – str– Escape
Characters
 Escape characters
□ Allows you to insert special characters in strings
□ Backslash, \, followed by a special character

Escape Result
Characte
r
\' S i n g l e quote
\" Double quote
\\ Backslash
\n New line
\t Tab
D a t a Types – li s t

 Lists
□ Ordered, mutable collections of one or more different data
types
□ Enclosed in square brackets, [ ], separated by commas
> > > list1 = [3, 15.2, 12e3, -459]
> > > names = ['Jane', ‘Bob', 'Sally']
> > > mixed = [3, 'Hello', 4 + 9j]
D a t a Types – tu p le

 Tuples
□ Ordered, immutable collections of one or more different data
types
□ Like a list, but immutable
□ Enclosed in parentheses, ( ), separated by commas
> > > tup1 = (3, 15.2, 12e3, -459)
> > > names = ('Jane', 'Bob', 'Sally')
> > > mixtup = (3, 'Hello', 4 + 9j)
D a t a Types – set
 Sets
□ Unordered, mutable collections of one or more different data types
□ Enclosed in curly brackets, { } , separated by commas
□ Sets do not store duplicate objects
□ Suitable for mathematical set operations, e . g . , union, intersection,
difference, etc.

> > > numset = {3, 15.2, 12e3, -459}


> > > names = {'Jane', 'Bob', 'Sally'}
> > > set3 = {3, 'Hello', 4 + 9j}
D a t a Types – d i c t
 Dictionaries
□ Ordered, mutable collections of data stored as key:value pairs
□ Enclosed in curly brackets, { }
□ Keys and values separated by colons
□ Key:value pairs separated by commas
□ Duplicate keys are not allowed

> > > person1 = {'Name':, 'Joe', 'Age':, 32, 'Hair':, 'brown', 'Eyes':, 'green'}

> > > capitals = {'OR':, 'Salem', 'WA':, 'Olympia',


'CA':, 'Sacremento', 'ID':, 'Boise}
D a t a Types – bool

 Booleans
□ One of two logical values: Trueor
False
□ Often the result of a logical
expression , e . g . , a > b
□ Any value can be cast as a Boolean
using the bool()function
 True:
 Non-zero numbers
 Non-empty strings, lists, tuples, sets,
or dictionaries
 False:
 Zero
 Empty strings, lists, tuples, sets, or
dictionaries
D a t a Ty p e s i n P y t h o n

Example: “datatypesdemo.py”
a=1 0
b=“Python"
c = 10.5
d=2.14j
print("Data type of Variable a :",type(a))
print("Data type of Variable b :",type(b))
print("Data type of Variable c :",type(c))
print("Data type of Variable d :",type(d))

Output:
python3 datatypesdemo.py
Datatype of Variable a : <cl as s ‘int’>
Datatype of Variable b : <cl as s ‘str’>
Datatype of Variable c : <cl as s
‘float’>
Datatype of Variable d : < c l as s
‘complex’>
Ty p e C o n v e r s i o n i n P y t h o n

• Python provides Explicit type conversion functions to


directly convert one data type to another. It is also called as Type Casting in
Python
• Python supports following functions
1. int () : This function converts any data type to integer.
2. float() : This function is used to convert any data type to a floating
point number.
3. str() : This function is used to convert any data type to a string.
Example:“Typeconversiondemo.py”
x = int(2.8) Output:
y = int("3") typeconversiondemo.py
z = float(2) 2
s = str(10) 3
print(x); 2.0
print(y) 10
print(z);
print(s)
Boolean Algebra 42

You might also like