Programming for Problem Solving
in Python Language
by
Dr. Sumona Sinha
Why Python Programming Language?
•Easy to read and write: Python uses clear and concise syntax, which
makes it great for beginners.
•Interpreted: Code is executed line-by-line, making debugging easier.
•Dynamically typed: You don’t have to declare variable types.
•Versatile: Used for web development, data science, AI, automation,
game development, scripting, and more.
•Huge standard library: Comes with many built-in modules and
supports external packages via tools like pip.
Creating First Program
• In Python IDLE, go to the menu and click File -> New File
Program(pr1.py) print(“Soham Sen")
print(“Newtown, Kolkata")
• To run the program, click on Run -> Run Module.
Output
Soham Sen
Newtown, Kolkata
How to print more than one object by separating them
by a comma?
Program(pr2.py) print("Orange", "Mango", "Apple")
Output
Orange Mango Apple
sep parameter
• Specifies how to separate more than one object.
• It is an optional parameter default is ' '.
Program(pr3.py) print("Orange", "Mango", "Apple",sep="#")
Output
Orange#Mango#Apple
Line Break
'\n' character is used to insert a line break in a string
Program(pr4.py)
print("Everybody\nHas a name\nSome are different\nSome the same")
Output
Everybody
Has a name
Some are different
Some the same
end parameter
• specifies what character you want at the end of a print statement.
• Normally, print() adds a newline (\n) at the end of its output.
Program(pr5.py) print("apple", end = " ")
print("banana", end = " ")
print("mango")
Output
apple banana mango
Comments in Python
• Comments are important for making your code more readable and
for explaining what your code is doing.
• Comments are not executed by Python interpreter.
Single-Line Comments
# This program displays an address.
print(“Soham Sen") #Displays Person Name
print(“Newtown, Kolkata")
Multi-Line Comments
They start and end with three double quotes """ or three single
quotes '''.
"""
This is a multi-line comment
that explains a block of code.
"""
print("Hello, world!")
Variables
• In programming language, variables are names used to store data
values, acting as containers for information that can be referenced and
manipulated during program execution.
• Unlike some other programming languages, Python does not require
explicit declaration of a variable's data type; the type is dynamically
inferred based on the value assigned to it.
Variable Definition & Declaration
x = 10
Naming Rule of Variable
To name variables in Python, you must follow these rules:
• A variable name can be of any size.
• A variable name have allowed characters, which are a-z, A-Z, 0-9 and
underscore (_).
• A variable name should begin with an alphabet.
• A variable name should not be a keyword.
• A variable name cannot contain spaces.
• Uppercase and lowercase characters are distinct.
Valid Variable Names
• age = 25
• name = "John"
• email_address = "[email protected]"
• total_sales = 500.50
• first_name = "Mary"
Invalid variable names
• 2nd_grade = 80 # cannot start with a number
• first-name = "John" # cannot use hyphens
• total/sales = 500 # cannot use forward slash
• email address = "john @example.com" # cannot use spaces
• if = 10 # cannot use Python keywords as variable names
Datatype
• In Python, the datatype of a variable is determined dynamically at
runtime, based on the value assigned to it. This means that you do
not need to declare the datatype of a variable before assigning a
value to it.
• Python automatically assigns the appropriate datatype based on
the value you provide.
Example:
x = 10 # int
y = 3.14 # float
z = "Hello" # str
Check: datatype of a variable
using the type() function
x = 10
print(type(x)) # Output: <class 'int'>
y = 3.14
print(type(y)) # Output: <class 'float'>
z = "Hello"
print(type(z)) # Output: <class 'str'>
Classifications of Datatype
Keywords
There are some reserved words in Python which have predefined meaning.
Python keywords List
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
Reading input from Keyboard
Input function reads data that has been entered by the keyboard and
returns that data, as a string
# Get the user's name.
Reading String name = input("Enter your name: ")
# Print a greeting to the user.
print("Hello", name)
print(type(name))
Output
Enter your name: Soham
Hello Soham
<class 'str'>
Example:
# Get the user's age.
age = input("What is your age? ") Output:
What is your age? 12
# Display the age. Age: 12
print("Age:", age) <class 'str'>
print(type(age))
Reading integer Example:
# Get the user's age.
age = int(input("What is your age? "))
Output:
# Display the age. What is your age? 12
print("Age:", age) Age: 12
print(type(age)) <class ‘int'>
Reading Floating Example:
# Get the user's age.
point age = float(input("What is your age? "))
# Display the age.
print("Age:", age)
print(type(age))
Output:
What is your age? 12.5
Age: 12.5
<class ‘float'>
Reading Any Type Input
Example:
# Get the user's age.
age = eval(input("What is your age? "))
# Display the age.
print("Age:", age)
print(type(age))
Output:
What is your age? 12.5
Age: 12.5
<class ‘float'>
Operators
Operators are symbols that perform operations on variables
and values.
Arithmetic Operators
Operator Description Example Output
+ Addition a = 5, b = 3; a+b 8
- Subtraction a = 5, b = 3; a-b 2
* Multiplication a = 5, b = 3; a*b 15
/ Division (float) a = 5, b = 2; a/b 2.5
// Floor Division a = 5, b = 2; a//b 2
% Modulus a = 5, b = 2; a%b 1
** Exponentiation a = 5, b = 2; a**b 25
Write a program to print sum of two integers
a = 10
b = 12
s=a+b
print("Sum:", s)
Write a program that prompts the user to
enter two integers and display their sum on the
screen.
a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))
s=a+b
print("Sum:", s)
Write a Python program to find the last digit of a
number and delete the last digit.
# Input from user
n = int(input("Enter a number: "))
# Logical Instruction for last digit
l_d = n% 10
print("Last digit is:", l_d)
# Remove the last digit using integer division
n= n // 10
print("Number after deleting last digit is:", n)
Write a program that prompts the user to input the
radius of a circle and outputs the area and
circumference of the circle.
r = float(input("Enter the radius of the circle: "))
a= 3.14 * r ** 2
c= 2 * 3.14 * r
print("The area of the circle is:", a)
print("The circumference of the circle is:", c)
Write a program that prompts the user to input the
length of sides of a triangle and outputs the area of
the triangle.
import math
a = int(input("Enter the length of side a: "))
b = int(input("Enter the length of side b: "))
c = int(input("Enter the length of side c: "))
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print("Area of the triangle:", area)
References.
1. Python Computing Fundamentals and
Applications, Abhijit Kar Gupta, Techno World.
2. Python for Everybody: Exploring Data in Python
3, Charles Severance, SPD
Write a program that prompts the user to
enter number in two variables and swap the
contents of the variables.
# Input
n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))
# swap the values
temp = n1
n1 = n2
n2 = temp
# Output
print("After swapping, first number is", n1,"and second number is", n2)
Assignment Operators
a=5 Assigns the value 10 to variable a
Operator Description Example Same As
+= Add and assign a += 3 a=a+3
-= Subtract and assign a -= 3 a=a-3
*= Multiply and assign a *= 3 a=a*3
/= Divide and assign a /= 3 a=a/3
%= Modulus and assign a %= 3 a=a%3
**= Exponent and assign a**= 3 a=a**3
Relational Operators
Relational Operators are also known as Comparison Operators
Operator Description
==
Equal to
!=
Not Equal to
> Greater than
< Less than
>= Greater than
Equal to
<= Less than
Equal to
Logical Operators
Operator Description Same As
and Holds if both statements are Valid x < 5 and x < 10
or Holds if one of the statements is x < 5 or x < 4
Valid
not Reverse the result, returns False if not(x < 5 and x
the result is Valid < 10)
ASCII Value
Example mappings:
• C is a case-sensitive language.
CharacterStandard
• ASCII➔American ASCII Value
Code for Information Interchange.
A 65
What isaASCII? 97
• ASCII0is a character
48encoding standard used to represent text
in computers and other devices.
Space 32
• It assigns a unique number (0–127) to each character.
! 33
Example: ASCII value of a character
char = input("Enter a character: ")
ascii_value = ord(char)
print("ASCII value:",ascii_value )
Output:
Enter a character: A
ASCII value of 'A' is 65
Decision Structures
• Sometimes the program needs to be executed depending upon a
particular condition.
• Python provides the following statements for implementing the
decision structure.
• if statement
• if else statement
• if-elif-else statement
• nested if statement
if statement
Syntax:
if condition:
statement
statement
etc.
If the condition is valid, the statement is executed;
otherwise, it is skipped.
Write a program that prints only the absolute
value.
n = int(input("Enter a number:"))
if n < 0:
n= -n
print("The absolute value of number is", n)
Flowchart:
if-else statement
Syntax: if condition:
statement 1
etc.
else:
statement 2
etc.
If the condition is true, statement 1 is executed. If the condition is false,
statement 2 is executed.
Write a program to check a number is even or
odd.
n = int(input("Enter a number:"))
if n%2 == 0:
print(n, “is even.”)
else:
print(n, “is odd.”)
Flowchart:
if-elif-else Statement Syntax:
if condition_1:
When there are more than two statement
possibilities and we need more statement
than two branches, if-elif-else etc.
statement is used. elif condition_2:
statement
• elif is an abbreviation of "else if.“ statement
etc.
• There is no limit of the number else:
of elif statements. statement
• But the last branch has to be an statement
else statement. etc.
Write a program to find out the larger number
between two numbers.
a = int(input("Enter first number:"))
b = int(input("Enter second number:"))
if a < b:
print (“Larger number:", b)
elif a > b:
print (“Larger number:", a)
else:
print (“Both are equal“)
Nested Decision Structures Syntax:
if condition1:
if condition2:
A nested decision structure in # Code block executed if
Python refers to a decision-making both conditions are Valid
else:
process where one decision # Code block executed if
structure is inside another. condition1 is True but
condition2 is False
else:
# Code block executed if
condition1 is False
Write a program to find out the larger number
between two numbers.
a = int(input("Enter first number:"))
b = int(input("Enter second number:"))
if a == b:
print (“Both are equal“)
else:
if a < b:
print (“Larger number:", b)
else:
print (“Larger number:", a)
Write a program in Python to check whether an input is leap
year or not
• Leap Years are any year that can be evenly divided by
4.
• A year that is evenly divisible by 100 is a leap year
only if it is also evenly divisible by 400.
• Example :
1992 Leap Year
2000 Leap Year
1900 NOT a Leap Year
1995 NOT a Leap Year
Leap year check using logical operators
year = int(input("Enter a year: "))
# Leap year check using logical operators
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
What is Indentation?
• Indentation refers to the whitespace (spaces or
tabs) at the beginning of a line.
• Python uses indentation to define blocks of code.
• Unlike other languages, indentation is mandatory
in Python.
What is an Indentation Error?
• Indentation Error occurs when indentation is
missing or incorrect.
• Happens if expected blocks are not properly
indented.
Example of Indentation Error
x = 10
if x > 5:
print("x is greater than 5") # No indentation!
Output:
IndentationError: expected an indented
block
Corrected Version
x = 10
if x > 5:
print("x is greater than 5") # Proper indentation
Tips to Avoid Indentation Errors
• Use either spaces or tabs consistently
(not both).
• Standard recommendations: 4 spaces or
1 tab per level.
Write a program that prompts the user to enter their weight (in
kilograms) and height (in meters). The program should calculate
the Body Mass Index (BMI) using the formula:
BMI = weight / (height * height).
The program should then classify the BMI into one of the
following categories:
• Underweight: BMI less than 18.5
• Normal weight: BMI between 18.5 and 24.9
• Overweight: BMI between 25 and 29.9
• Obesity: BMI 30 or greater
wt = eval(input("Enter your weight in kilograms: "))
ht = eval(input("Enter your height in meters: "))
# Calculate the BMI
BMI = wt / (ht * ht)
# Classify the BMI
if BMI < 18.5:
print("Category: Underweight")
elif BMI <= 24.9:
print("Category: Normal weight")
elif BMI <= 29.9:
print("Category: Overweight")
else:
print("Category: Obesity")