COURSE TITLE: PROGRAMMINGFOR PROBLEM
SOLVING USING PYTHON
Mulla Arshiya
Asst. Professor
School of Engineering
2.
10/15/2025
Module 1: Introduction& Onboarding - What’s Problem Solving Using Programming?
• Problem solving is the process of identifying a problem, analyzing it, and finding
the most efficient way to solve it.
• Programming is the process by which you instruct a computer to perform
specific tasks.
• Problem Solving Using Programming - It is the process of using logic,
algorithms, and a programming language to solve a specific real-world problem.
3.
10/15/2025
Understanding the roleof programming in solving real-world problems-
• Programming acts as a bridge between human problems and computer-based
solutions.
Real-World Problem Programming Solution
Need to send messages instantly WhatsApp, Telegram apps
Need to find directions Google Maps uses GPS
Managing bank transactions
Banking software handles deposits,
transfers, etc.
Online shopping and payments
Amazon, Flipkart websites & payment
systems
4.
10/15/2025
Importance of algorithmicthinking and problem-solving skills -
• a set of step-by-step instructions used to solve a problem or perform a task.
• Ex: Add two numbers
Algorithm:
• Start
• Read first number → a
• Read second number → b
• Calculate sum → sum = a + b
• Display sum
• Stop
Logic:
• Take two inputs (numbers)
• Use the + operator to add them
• Store the result in a variable
• Display the result
5.
10/15/2025
Python’s Features andCommunity Support
• Large global community of developers and researchers.
• Rich online resources: W3Schools, GeeksforGeeks, TutorialsPoint.
• Regular updates and improvements.
• Ready-made solutions available (forums, GitHub, StackOverflow).
• Libraries: Biopython, NumPy, Pandas, Matplotlib.
6.
10/15/2025
What Makes PythonSpecial?
• Python is simple and easy to learn
print("Hello, World!")
• Clean and readable syntax
• Highly versatile: Used in web, data science, AI, etc.
• Large standard libraries and third-party modules.
math, random → Built-in, matplotlib, pandas, NumPy → External
• Strong community support and learning resources.
Stack Overflow, Python.org, GitHub projects
• Beginner-friendly and widely used in industry.
7.
10/15/2025
What is anAlgorithm
• An algorithm is a step-by-step method to solve a problem.
• It has a clear start and end.
• Must be unambiguous (no confusion in steps).
• Should be efficient (done in reasonable time).
Steps to Structure an Algorithm
• Understand the problem (what do we want?).
• Identify input(s) (data required).
• Identify output(s) (result we need).
• Break into steps (logical sequence).
• Check correctness (does it solve the problem?).
• Optimize if needed (remove unnecessary steps).
8.
10/15/2025
Problem 1: Findthe Largest of Two Numbers
Algorithm:
1.Start
2.Input two numbers A and B
3.If A > B, then print A
4.Else print B
5.Stop
Problem 2: Check Whether a Number is Even
or Odd
Algorithm:
1.Start
2.Input a number N
3.If N % 2 == 0, print “Even”
4.Else print “Odd”
5.Stop
9.
10/15/2025
Problem 3: CalculateSum of First N Natural Numbers
Algorithm:
1.Start
2.Input N
3.Initialize sum = 0
4.Repeat from 1 to N → Add each number to sum
5.Print sum
6.Stop
10.
10/15/2025
Problem 4: DailyLife Example – Buying a Train Ticket
Algorithm:
1.Start
2.Go to ticket counter
3.Provide journey details (source, destination, date)
4.Pay money
5.Collect ticket
6.Stop
10/15/2025
Writing and ExecutingPython Code -
1. Install Python from the official website: https://www.python.org
2. Open Python IDLE (comes installed with Python)
3. Click on File > New File to open a new editor window
4. Write your Python code in the editor
5. Save the file with a .py extension using File > Save As
6. Run the code using Run > Run Module or press F5
7. View the output in the IDLE Shell window
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
if 5 > 2: if 5 > 2:
print("Five is greater than two!") print("Five is greater than two!")
10/15/2025
• Variables arecontainers for storing data values.
Declaring variables and assigning values -
name = "Arshiya"
variable Value
Assignment Operator
x, y, z = "Orange", "Banana", "Grapes"
x = y = z = "Orange"
Print(y)
Print(x)
Print(z)
print(name)
Variables
15.
10/15/2025
Rules for Pythonvariables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
• A variable name cannot be any of the Python keywords.
16.
10/15/2025
Legal variable names:
myvar= "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Identifiers -
• Identifiers are names used to identify variables, functions, classes, modules, etc.
17.
10/15/2025
Python Keywords -
•Keywords are reserved words that have special meaning in Python.
• They are used to define syntax and structure.
• Cannot be used as variable names.
• if, else, elif, for, while, def, return, import, class, try, except, True, False, None.
• All keywords are in lowercase except True, False, and None.
18.
10/15/2025
Comments -
• Commentsare notes in your code that Python ignores.
• They are used to explain what the code is doing.
• Types of Comments:
• Single-line Comment: Uses #
• Multi-line Comment: Uses triple quotes ''' or """
# This is a single-line comment
"""
This is a
multi-line comment
that spans multiple lines
"""
19.
10/15/2025
Python Escape Characters-
• To insert characters that are illegal in a string, use an escape character.
• An escape character is a backslash followed by the character you want to
insert.
eg: #You will get an error if you use double quotes inside a string that are surrounded by double
quotes: Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python3.12/py_compile.py", line 150,
in compile
raise py_exc
py_compile.PyCompileError: File "./prog.py", line 1
txt = "Hello, "WELCOME To Chanakya
University"."
^^^^^^^
SyntaxError: invalid syntax
Print("Hello, "WELCOME To Chanakya University".")
Print("Hello, "WELCOME To Chanakya University".")
Hello, "WELCOME To Chanakya University".
10/15/2025
1. Create avariable named student_name and assign your name to it. Print
the value.
2. Write a single-line comment and a multi-line comment in your Python file.
Print "Comments practiced!"
3. Create three variables of your choice. Print all three using a single print()
statement.
4. Identify the invalid variable from below and correct it in your code to
make it run:
5. Use escape characters to print the following
output exactly
Name: your name
tAge: 25
Location: "Bangalore"
1st_place = "Gold"
second-place = "Silver"
print(1st_place, second-place)
22.
10/15/2025
Python Data Types
Adata type defines the type of value a variable holds.
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set
Boolean Type: bool
None Type: NoneType
23.
10/15/2025
Python Numbers -
•int
• float
• Complex
To verify the type of any object in Python, use the type() function.
x = 1 # int
y = 2.8 # float
z = 1j #complex
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'float'>
<class 'complex'>
24.
10/15/2025
Python Casting -
Youcan convert from one type to another with
the int(), float(), and complex() methods.
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
25.
10/15/2025
1. Create variablesof different numeric types:
a = 25 (integer)
b = 12.75 (float)
c = 4 + 5j (complex)
Print each variable and its data type.
2. Type Casting
• Take an integer value, cast it to float.
• Take a float value, cast it to integer.
• Print both results with their types.
26.
10/15/2025
Strings -
• Stringsin python are surrounded by either single quotation marks, or
double quotation marks.
• Strings can contain letters, digits, symbols, and even spaces.
• Strings are used to represent textual data in Python.
'hello' is the same as "hello".
Quotes Inside Quotes
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
It's alright
He is called 'Johnny'
He is called "Johnny"
27.
10/15/2025
Operation Example Output
Concatenation"Hello" + "World" "HelloWorld"
Repetition "Hi" * 3 "HiHiHi"
Indexing "Python"[0] 'P'
Slicing "Python"[1:4] 'yth'
Length len("hello") 5
String Operations:
word = "Hello"
print(word[0]) # H
print(word[-1]) # o
text = "Python"
print(text[0:3]) # Pyt
print(text[2:]) # thon
first = "Good"
second = "Morning"
print(first + " " +
second) #Good Morning
28.
10/15/2025
Method Use ExampleOutput
.upper() Convert to uppercase "python".upper() 'PYTHON'
.lower() Convert to lowercase "HELLO".lower() 'hello'
.strip() Remove spaces " hi ".strip() 'hi'
.replace() Replace text "cat".replace("c", "b") 'bat'
String Methods:
29.
10/15/2025
Escape Code DescriptionExample Output
n New Line print("HellonWorld")
Hello
World
t Tab print("Name:tAli") Name: Ali
" Double Quote print("She said "Hi"") She said "Hi"
Backslash print("C:pathfile") C:pathfile
Escape Characters:
30.
10/15/2025
Input and Output
•Input: Receiving data from the user.
• Output: Displaying results or information to the user.
1.input() Function – Getting User Input
• Used to accept input from the keyboard.
• Always returns data as a string.
Syntax:
variable = input("Enter something: ")
Eg:
name = input("Enter your name: ")
print("Hello", name)
31.
10/15/2025
Type Casting withinput()
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)
Print Function
• Used to show messages, variables, or results.
Syntax:
print("Text or variable")
Eg:
print("Welcome to Python!")
32.
10/15/2025
1.Take your nameas input and print a greeting message.
2.Create a string "Python Programming" and print only the word "Python".
3.Use the len() function to find the length of "Hello World".
4.Print the string "PythontRocks!" to show tab escape character.
5.Take a number as input, convert it to integer and print it.
6.Take a sentence as input and count how many times the letter "a" appears.
33.
10/15/2025
name = input("Enteryour name: ")
print("Hello, " + name + "!")
text = "Python Programming"
print(text[0:6])
text = "Hello World"
print(len(text))
print("PythontRocks!")
num = input("Enter a number: ")
num = int(num)
print(num)
1.
2.
3.
4.
5.
34.
10/15/2025
1. Take twostrings as input and print the combined string with a space in
between.
2. Replace the word "bad" with "good" in the sentence: "This is a bad idea."
3. Accept a number input, convert it to float, divide by 3, and print the result.
4. Format Full Name Output
Input Format:
Two strings – first name and last name.
Output Format:
Print as Welcome, <Last>, <First>
35.
10/15/2025
first = input("Enterfirst word: ")
second = input("Enter second word: ")
print(first + " " + second)
text = "This is a bad idea."
new_text = text.replace("bad", "good")
print(new_text)
num = input("Enter a number: ")
num = float(num)
print(num / 3)
first = input("Enter first name: ")
last = input("Enter last name: ")
print("Welcome,", last + ",", first)
1.
2.
3.
4.
36.
10/15/2025
Boolean Data Typein Python
• The Boolean data type has only two possible values: True or False (with the
first letter capitalized).
• Used in decision making, comparisons, and conditions.
• Commonly used in if statements, loops, and comparisons.
• You can get a Boolean result from comparison operators (==, !=, <, >, etc.)
10/15/2025
Comparison Operators -
Usedto compare two values; returns Boolean (True/False).
Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 4 != 3 True
> Greater than 6 > 2 True
< Less than 3 < 5 True
>=
Greater than or
equal
5 >= 5 True
<= Less than or equal 3 <= 2 False
41.
10/15/2025
Logical Operators -
Usedto combine multiple conditions.
Operator Meaning Example Result
and
Returns True if
both are True
5 > 2 and 4 > 3 True
or
Returns True if
one is True
5 > 2 or 4 < 1 True
not
Reverses the
result
not(5 > 2) False
42.
10/15/2025
Assignment Operators -
Assignmentoperators are used to assign values to variables:
Operator Meaning Example
Equivalent
Expression
Result (x = 10)
= Assigns a value x = 10 x = 10 10
+= Adds and assigns x += 3 x = x + 3 13
-=
Subtracts and
assigns
x -= 3 x = x - 3 7
*=
Multiplies and
assigns
x *= 3 x = x * 3 30
/=
Divides and
assigns (float
result)
x /= 3 x = x / 3 3.33 (approx.)
43.
10/15/2025
%=
Modulus and
assigns
x %=3 x = x % 3 1
//=
Floor division and
assigns
x //= 3 x = x // 3 3
**=
Exponentiation and
assigns
x **= 3 x = x ** 3 1000
>>= Bitwise right shift
and assigns x >>= 2 x = x >> 2 2
<<= Bitwise left shift and
assigns x <<= 2 x = x << 2 40
44.
10/15/2025
Identity Operators -
Identityoperators are used to compare the objects, not if they are equal, but if they
are the same object, with the same memory location
Operator Meaning Example Output
is
Returns True if
both variables
point to the same
object
a is b True or False
is not
Returns True if
both variables
point to different
objects
a is not b True or False
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True
print(a is c) # False
print(a is not c) #
True
45.
10/15/2025
Python Membership Operators-
Membership operators are used to test if a sequence is presented in an object
Operator Meaning Example Output
in
True if value
is found in
the sequence
'a' in 'apple' True
not in
True if value
is not found
in sequence
'x' not in
'apple'
True
text = "Python"
print('P' in text) # True
print('z' not in text)
# True
46.
10/15/2025
Operator Name DescriptionExample
& AND Sets each bit to 1 if both bits are 1 x & y
| OR Sets each bit to 1 if one of two bits is 1 x | y
^ XOR Sets each bit to 1 if only one of two bits is 1 x ^ y
~ NOT Inverts all the bits ~x
<< Zero fill left
shift
Shift left by pushing zeros in from the right and let
the leftmost bits fall off
x << 2
>> Signed right
shift
Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
x >> 2
Python Bitwise Operators -
Bitwise operators are used to compare (binary) numbers:
47.
10/15/2025
Operator Precedence -
Operatorprecedence describes the order in which operations are performed.
Precedence Operators Description
1 (Highest) ()
Parentheses (expression
grouping)
2 ** Exponentiation
3 +x, -x, ~x
Unary plus, minus, bitwise
NOT
4 *, /, //, %
Multiplication, division,
floor division, modulo
5 +, - Addition, subtraction
6 <<, >> Bitwise shift operators
48.
10/15/2025
7 & BitwiseAND
8 ^ Bitwise XOR
9 ==, !=, >, <, >=, <=, is, is
not, in, not in Comparisons
10 not Logical NOT
11 and Logical AND
12 or Logical OR
13 =, +=, -=, etc. Assignment operators
14 (Lowest) lambda Lambda function
x = 3 + 2 * 5
# * has higher precedence than + # So, 2 * 5 = 10 → 3 + 10 = 13
49.
10/15/2025
1. Take twonumbers as input and print their sum, difference, product, and quotient.
2. Declare a variable x = 10. Use the += operator to increase its value by 5 and print the
result.
3. Compare two numbers using == and print True or False.
4. Use a logical and operator to check if x > 5 and x < 20.
5. Use assignment operators (-=, *=, /=) on a variable x = 10 and print after each
operation.
6. Demonstrate membership using in with a string (e.g., "Py" in "Python").
7. Demonstrate identity operators using is and is not with two variables referring to the
same value.
50.
10/15/2025
a = int(input("Enterfirst number: "))
b = int(input("Enter second number: "))
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Quotient:", a / b)
x = 10
x += 5
print("Result:", x)
a = 5
b = 5
print(a == b)
x = 15
(x > 5 and x < 20)
x = 10
x -= 2
print("After -= :", x)
x *= 3
print("After *= :", x)
x /= 2
print("After /= :", x)
text = "Python"
print("Py" in text)
a = 100
b = 100
print(a is b) # True, because both
point to same object
print(a is not b) # False
1.
2.
3.
4.
5.
6.
7.
51.
10/15/2025
1. Show theuse of all arithmetic operators in one program with inputs from the user.
2. Take two strings and check if they are identical using identity operator (is).
3. Check if a user-input word exists in a predefined string using in.
4. Accept a number and use assignment operators in sequence (+=, -=, *=, //=, %=),
print after each.
5. Evaluate and explain this expression: 5 + 3 * 2 > 10 and 4 < 2
6. Input a value and evaluate this complex expression:
result = (10 + 5) * 2 > 20 or (15 / 3 == 5 and not 10 == 5)
7. Show the difference between == and is using numbers and strings.
52.
10/15/2025
a = int(input("Enterfirst number: "))
b = int(input("Enter second number: "))
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
print(str1 is str2)
1.
2.
text = "Python is awesome"
word = input("Enter a word:
") print(word in text)
x = int(input("Enter a number: "))
x += 2
print("After += 2:", x)
x -= 1
print("After -= 1:", x)
x *= 3
print("After *= 3:", x)
x //= 2
print("After //= 2:", x)
x %= 4
print("After %= 4:", x)
3.
4.
53.
10/15/2025
result = 5+ 3 * 2 > 10 and 4 < 2
print(result) # Output will be False
val = input("Enter anything as input")
result = (10 + 5) * 2 > 20 or (15 / 3 == 5
and not 10 == 5)
print(result) # Output will be True
#Number
a = 100
b = 100
print("a == b:", a == b)
print("a is b:", a is b)
# Strings
x = "hello"
y = "hello"
print("x == y:", x == y)
print("x is y:", x is y)
5.
6.
7.
54.
10/15/2025
Conditional Statements inPython
Conditional statements allow the program to make decisions and execute different
code blocks based on conditions.
1. if Statement - Executes the block only if the condition is True.
age = 18
if age >= 18:
print("You are eligible to vote.")
2. if-else Statement - else block executes if the if condition is False.
marks = 45
if marks >= 50:
print("Pass")
else:
print("Fail")
55.
10/15/2025
3. if-elif-else -Checks multiple conditions in sequence and Stops when one
condition is True.
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 40:
print("Grade: D")
else:
print("Grade: F (Fail)")
56.
10/15/2025
1. Even orOdd
Input: A number
Task: Check if it is even or odd.
2. Positive, Negative or Zero
• Input: A number
• Task: Print whether it is positive, negative, or
zero.
3. Greatest of Three Numbers
• Input: Three numbers
• Task: Print the greatest number among them.
4. Student Grade System
Input: Marks
Task: Print grade using:
A: 90-100
B: 75-89
C: 60-74
D: 40-59
F: < 40
57.
10/15/2025
num = int(input("Entera number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
num = float(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num < 0:
print("Negative number")
else:
print("Zero")
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a >= b and a >= c:
print("Greatest number is:", a)
elif b >= a and b >= c:
print("Greatest number is:", b)
else:
print("Greatest number is:", c)
1.
2.
3.
58.
10/15/2025
Looping Statements inPython
Loops allow executing a block of code multiple times, useful for repetition and
automation.
1. while Loop
With the while loop we can execute a set of statements as long as a condition is
true.
count = 1
while count <= 5:
print(count)
count += 1
correct_pin = "1234"
attempt = ""
while attempt != correct_pin:
attempt = input("Enter your 4-digit PIN: ")
if attempt != correct_pin:
print("Incorrect PIN. Try again.")
print("PIN accepted. Welcome!")
59.
10/15/2025
2. For Loops-
A for loop is used for iterating over a sequence.
range(start, stop) generates numbers from start to stop – 1
for i in range(1, 6):
print(i)
break and continue -
• break: exits loop early.
• continue: skips current iteration.
60.
10/15/2025
# break example
fori in range(1, 10):
if i == 5:
break
print(i) #output: 1 2 3 4
# continue example
for i in range(1, 6):
if i == 3:
continue
print(i) #output: 1 2 4 5
61.
10/15/2025
1.Print Numbers from1 to 10 using a for loop.
2. Sum of First n Natural Numbers
Input: n
Task: Find sum using while loop.
3.Multiplication Table
• Input: Number n
• Task: Print table of n up to 10 (e.g., n x 1 = ...)
4. Reverse a Number
• Input: 1234
• Output: 4321
5.Factorial of a Number
Input: Number
Output: Factorial using a loop (no
math module).
62.
10/15/2025
for i inrange(1, 11):
print(i)
n = int(input("Enter a number: "))
sum = 0
i = 1
while i <= n:
sum += i
i += 1
print("Sum is:", sum)
n = int(input("Enter a number: "))
for i in range(1, 11):
print(n, "x", i, "=", n * i)
num = int(input("Enter a number: "))
rev = 0
while num > 0:
digit = num % 10
rev = rev * 10 + digit
num = num // 10
print("Reversed number:", rev)
num = int(input("Enter a number: "))
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial is:", fact)
1.
2.
3.
4.
5.