Total Pageviews

Wednesday, September 9, 2026

Conditional Statement

Conditional Statements in Python

Complete Tutorial with Syntax, Examples & Output

1. Introduction

A conditional statement is used to make decisions in a Python program. It allows the program to execute different statements depending on whether a given condition is True or False.

For example, a program can check whether a student has passed an examination, whether a person is eligible to vote, or whether a number is positive or negative.

Condition → True → Execute one block
Condition → False → Execute another block

2. Types of Conditional Statements

Python provides several ways to perform conditional execution:

Statement Purpose
if Executes code when a condition is True
if-else Chooses between two alternatives
if-elif-else Chooses among multiple alternatives
Nested if Places one conditional statement inside another
Conditional Expression Provides a compact one-line condition

3. if Statement

The if statement executes a block of code only when its condition evaluates to True.

Syntax

if condition:
    statement

Example

age = 20

if age >= 18:
    print("Eligible to vote")

Output

Eligible to vote

4. Boolean Conditions

A condition generally produces one of two Boolean values:

  • True
  • False

Example

age = 20

print(age >= 18)

Output

True

5. if-else Statement

The if-else statement is used when there are two possible execution paths.

Syntax

if condition:
    statement1
else:
    statement2

Example

number = 7

if number % 2 == 0:
    print("Even")
else:
    print("Odd")

Output

Odd

6. Practical Example – Pass or Fail

marks = int(input("Enter marks: "))

if marks >= 40:
    print("Pass")
else:
    print("Fail")

Sample Output

Enter marks: 65
Pass

7. if-elif-else Statement

The if-elif-else structure is used when multiple conditions need to be checked.

Syntax

if condition1:
    statement1
elif condition2:
    statement2
elif condition3:
    statement3
else:
    statement4

Example

marks = 82

if marks >= 90:
    print("Grade A+")
elif marks >= 80:
    print("Grade A")
elif marks >= 70:
    print("Grade B")
else:
    print("Grade C")

Output

Grade A

8. Practical Example – Student Grade

marks = int(input("Enter marks: "))

if marks >= 90:
    grade = "A+"
elif marks >= 80:
    grade = "A"
elif marks >= 70:
    grade = "B"
elif marks >= 60:
    grade = "C"
elif marks >= 40:
    grade = "D"
else:
    grade = "F"

print("Grade:", grade)

Sample Output

Enter marks: 76
Grade: B

9. Nested Conditional Statement

A nested conditional statement is a conditional statement placed inside another conditional statement.

Example

age = 22
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Entry denied")

Output

Entry allowed

10. Comparison Operators in Conditions

Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal a >= b
<= Less than or equal a <= b

11. Logical Operators in Conditions

Logical operators are used to combine multiple conditions.

Operator Meaning
and True only when both conditions are True
or True when at least one condition is True
not Reverses the Boolean result

Example using and

age = 21
marks = 65

if age >= 18 and marks >= 40:
    print("Eligible")
else:
    print("Not eligible")

Output

Eligible

12. Using the or Operator

day = "Sunday"

if day == "Saturday" or day == "Sunday":
    print("Holiday")
else:
    print("Working day")

Output

Holiday

13. Using the not Operator

logged_in = False

if not logged_in:
    print("Please login")

Output

Please login

14. Practical Example – Largest of Two Numbers

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
    print("Largest =", a)
elif b > a:
    print("Largest =", b)
else:
    print("Both are equal")

Sample Output

Enter first number: 25
Enter second number: 40
Largest = 40

15. Practical Example – Largest of Three Numbers

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("Largest =", a)
elif b >= a and b >= c:
    print("Largest =", b)
else:
    print("Largest =", c)

Sample Output

Enter first number: 25
Enter second number: 70
Enter third number: 45
Largest = 70

16. Practical Example – Positive, Negative or Zero

number = int(input("Enter a number: "))

if number > 0:
    print("Positive")
elif number < 0:
    print("Negative")
else:
    print("Zero")

Sample Output

Enter a number: -15
Negative

17. Practical Example – Leap Year

A year is a leap year if it is divisible by 400, or if it is divisible by 4 but not divisible by 100.

year = int(input("Enter year: "))

if year % 400 == 0:
    print("Leap year")
elif year % 100 == 0:
    print("Not a leap year")
elif year % 4 == 0:
    print("Leap year")
else:
    print("Not a leap year")

Sample Output

Enter year: 2024
Leap year

18. Practical Example – Voting Eligibility

age = int(input("Enter your age: "))

if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible to vote")

Sample Output

Enter your age: 19
Eligible to vote

19. Practical Example – Login Validation

username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin" and password == "1234":
    print("Login successful")
else:
    print("Invalid username or password")

Sample Output

Enter username: admin
Enter password: 1234
Login successful

20. Practical Example – Calculator Using Conditions

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")

if op == "+":
    print("Result =", a + b)
elif op == "-":
    print("Result =", a - b)
elif op == "*":
    print("Result =", a * b)
elif op == "/":
    if b != 0:
        print("Result =", a / b)
    else:
        print("Cannot divide by zero")
else:
    print("Invalid operator")

Sample Output

Enter first number: 20
Enter second number: 5
Enter operator (+, -, *, /): *
Result = 100.0

21. Conditional Expression

A conditional expression is a compact way to write an if-else decision in a single line.

Syntax

value_if_true if condition else value_if_false

Example

age = 20

status = "Adult" if age >= 18 else "Minor"

print(status)

Output

Adult

22. Membership Operators in Conditions

The operators in and not in can be used to test whether a value exists in a sequence.

Example

subjects = ["C", "Python", "Java"]

subject = "Python"

if subject in subjects:
    print("Subject found")
else:
    print("Subject not found")

Output

Subject found

23. Identity Operators in Conditions

Python provides is and is not for identity testing. They check whether two references refer to the same object.

Example

a = None

if a is None:
    print("No value assigned")

Output

No value assigned

24. Truth Value in Conditions

Python allows many objects to be used directly as conditions. For example, an empty list is considered false, while a non-empty list is considered true.

Example

numbers = [10, 20, 30]

if numbers:
    print("List contains elements")
else:
    print("List is empty")

Output

List contains elements

25. Importance of Indentation

Python uses indentation to identify the statements belonging to a conditional block.

Correct Example

age = 20

if age >= 18:
    print("Adult")
    print("Eligible")

Both print() statements belong to the if block because they have the same indentation.


26. Flow of Conditional Statement

START

Evaluate Condition

Is Condition True?

↙          ↘

YES          NO

↓                ↓

Execute True Block    Execute False/Next Block

↘          ↙

Continue Program

END


27. Common Errors

  • Forgetting the colon:
    if age >= 18:
  • Incorrect indentation: Statements inside the condition must be indented.
  • Using = instead of ==:
    = performs assignment, while == checks equality.
  • Incorrect condition order: In an if-elif structure, conditions should be arranged carefully.
  • Using too many nested conditions: Complex nesting can make programs difficult to understand and maintain.

28. if vs if-else vs if-elif-else

Structure Use
if One condition
if-else Two alternatives
if-elif-else Multiple alternatives
Nested if Decision inside another decision
Conditional expression Compact one-line decision

29. Real-Life Applications

  • Student result and grading systems
  • Login and authentication systems
  • Banking applications
  • Online shopping and discount calculation
  • Voting eligibility checking
  • ATM transaction validation
  • Weather-based decisions
  • Traffic signal control
  • Game decision-making
  • Machine Learning classification logic

30. Summary

Conditional statements are fundamental to Python programming. They allow a program to make decisions and execute different blocks of code depending on conditions.

  • if executes code when a condition is True.
  • if-else provides two alternative paths.
  • if-elif-else handles multiple conditions.
  • Nested conditions allow decisions within decisions.
  • Comparison operators are commonly used to construct conditions.
  • Logical operators combine multiple conditions.
  • Conditional expressions provide a compact one-line alternative.
  • Proper indentation is essential in Python.

Created by Bijan Krishna Paul

Computer Science • Python Programming • Data Science

LOOP

Looping Statements in Python

Complete Tutorial with Examples and Output

1. Introduction to Looping

Looping is a programming technique used to execute a block of statements repeatedly. Instead of writing the same statement many times, a loop allows the programmer to execute it automatically.

For example, if we want to print numbers from 1 to 5, we can use a loop instead of writing five separate print() statements.

Start → Check Condition → Execute Block → Update → Repeat

Python mainly provides two types of loops:

  • for loop
  • while loop

Python also provides loop-control statements such as break, continue and pass.


2. for Loop

A for loop is used to iterate over a sequence such as a list, tuple, string, range, or other iterable object.

Syntax

for variable in sequence:
    statement

Example

for i in range(1, 6):
    print(i)

Output

1
2
3
4
5

3. range() Function

The range() function is commonly used with a for loop. It generates a sequence of numbers.

Example 1 – range(stop)

for i in range(5):
    print(i)

Output

0
1
2
3
4

The stop value 5 is not included.

Example 2 – range(start, stop)

for i in range(2, 7):
    print(i)

Output

2
3
4
5
6

Example 3 – range(start, stop, step)

for i in range(2, 11, 2):
    print(i)

Output

2
4
6
8
10

4. Looping Through a String

A for loop can be used to access each character of a string.

word = "Python"

for ch in word:
    print(ch)

Output

P
y
t
h
o
n

5. Looping Through a List

subjects = ["C", "Python", "Java", "DBMS"]

for subject in subjects:
    print(subject)

Output

C
Python
Java
DBMS

6. Looping Through a Tuple

numbers = (10, 20, 30, 40)

for n in numbers:
    print(n)

Output

10
20
30
40

7. while Loop

A while loop repeatedly executes a block of code as long as its condition remains True.

Syntax

while condition:
    statement

Example

i = 1

while i <= 5:
    print(i)
    i = i + 1

Output

1
2
3
4
5

8. Working of a while Loop

Initialize variable

Check condition

Condition True?

Execute statements

Update variable

Check condition again

Condition False → Exit Loop


9. Infinite Loop

An infinite loop occurs when the loop condition never becomes False.

For example:

while True:
    print("Hello")

This loop continues indefinitely until it is stopped.

Important: Make sure that a while loop has a suitable condition or update so that it can eventually terminate when required.

10. break Statement

The break statement immediately terminates the loop.

Example

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Output

1
2
3
4

When i becomes 5, the break statement terminates the loop.


11. continue Statement

The continue statement skips the remaining statements in the current iteration and moves to the next iteration.

Example

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output

1
2
4
5

The value 3 is skipped.


12. pass Statement

The pass statement does nothing. It is useful as a placeholder when a statement is syntactically required but no action is needed yet.

for i in range(5):
    pass

print("Loop completed")

Output

Loop completed

13. Nested Loops

A loop placed inside another loop is called a nested loop.

Example

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

Output

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

14. Creating a Multiplication Table

Nested loops and the multiplication operator can be used to generate multiplication tables.

number = int(input("Enter a number: "))

for i in range(1, 11):
    print(number, "x", i, "=", number * i)

Sample Output

Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

15. Sum of Numbers Using for Loop

total = 0

for i in range(1, 6):
    total = total + i

print("Sum =", total)

Output

Sum = 15

16. Printing Even Numbers

for i in range(1, 11):
    if i % 2 == 0:
        print(i)

Output

2
4
6
8
10

17. Printing Odd Numbers

for i in range(1, 11):
    if i % 2 != 0:
        print(i)

Output

1
3
5
7
9

18. Practical Example – Factorial

The factorial of a positive integer n is:

n! = n × (n − 1) × (n − 2) × ... × 1

Python Program

n = int(input("Enter a number: "))

factorial = 1

for i in range(1, n + 1):
    factorial = factorial * i

print("Factorial =", factorial)

Sample Output

Enter a number: 5
Factorial = 120

19. Practical Example – Reverse a Number

number = int(input("Enter a number: "))

reverse = 0

while number > 0:
    digit = number % 10
    reverse = reverse * 10 + digit
    number = number // 10

print("Reverse =", reverse)

Sample Output

Enter a number: 12345
Reverse = 54321

20. Practical Example – Count Digits

number = int(input("Enter a number: "))

count = 0

if number == 0:
    count = 1
else:
    while number != 0:
        number = number // 10
        count = count + 1

print("Number of digits =", count)

Sample Output

Enter a number: 98765
Number of digits = 5

21. Practical Example – Check Prime Number

A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.

number = int(input("Enter a number: "))

if number < 2:
    print("Not a prime number")
else:
    is_prime = True

    for i in range(2, number):
        if number % i == 0:
            is_prime = False
            break

    if is_prime:
        print("Prime number")
    else:
        print("Not a prime number")

Sample Output

Enter a number: 17
Prime number

22. Practical Example – Fibonacci Series

The Fibonacci series starts with 0 and 1, and each subsequent number is the sum of the previous two numbers.

n = int(input("Enter number of terms: "))

a = 0
b = 1

for i in range(n):
    print(a, end=" ")
    a, b = b, a + b

Sample Output

Enter number of terms: 8
0 1 1 2 3 5 8 13

23. Practical Example – Star Pattern

Nested loops can be used to generate patterns.

for i in range(1, 6):
    for j in range(i):
        print("*", end=" ")
    print()

Output

* 
* * 
* * * 
* * * * 
* * * * *

24. Looping with enumerate()

The enumerate() function provides both the index and the value while iterating through a sequence.

subjects = ["C", "Python", "Java"]

for index, subject in enumerate(subjects):
    print(index, subject)

Output

0 C
1 Python
2 Java

25. Looping with zip()

The zip() function can be used to iterate over multiple sequences at the same time.

names = ["Rahul", "Amit", "Riya"]
marks = [85, 90, 78]

for name, mark in zip(names, marks):
    print(name, mark)

Output

Rahul 85
Amit 90
Riya 78

26. else with a Loop

Python allows an else block to be associated with a loop. For a for or while loop, the else block executes when the loop finishes normally rather than being terminated by break.

Example

for i in range(1, 4):
    print(i)
else:
    print("Loop completed")

Output

1
2
3
Loop completed

27. Loop else with break

for i in range(1, 6):
    if i == 3:
        break
    print(i)
else:
    print("Loop completed")

Output

1
2

The else block does not execute because the loop was terminated using break.


28. for Loop vs while Loop

for Loop while Loop
Used to iterate over a sequence or iterable Runs while a condition is True
Often used when the number of iterations is known Useful when repetition depends on a condition
Commonly used with range() Requires careful condition/update handling
for i in range(5): while condition:

29. Loop Control Statements

Statement Purpose
break Terminates the loop immediately
continue Skips the current iteration
pass Does nothing; acts as a placeholder

30. Common Errors in Loops

  • Forgetting to update a while-loop variable: This can result in an infinite loop.
  • Incorrect indentation: Python uses indentation to identify the loop body.
  • Incorrect range: Remember that the stop value in range() is excluded.
  • Unnecessary nested loops: Too many nested loops can make a program slower and harder to understand.
  • Incorrect use of break: Make sure break is used only when the loop should terminate.

31. General Loop Flow

Start

Initialize

Check Condition / Get Next Item

Execute Loop Body

Update / Get Next Item

Repeat

Exit Loop


32. Summary

Looping is one of the most important concepts in Python programming. It allows a programmer to execute statements repeatedly without writing the same code again and again.

  • for loops are commonly used to iterate over sequences and iterables.
  • while loops execute while a condition remains True.
  • range() is frequently used with for loops.
  • Nested loops allow one loop to execute inside another loop.
  • break terminates a loop.
  • continue skips the current iteration.
  • pass acts as a placeholder.
  • enumerate() provides index and value while iterating.
  • zip() allows multiple sequences to be processed together.

Created by Bijan Krishna Paul

Computer Science • Python Programming • Data Science

Branching,

Branching Statements in Python

Complete Tutorial with Examples and Output

1. Introduction to Branching

Branching is a programming technique used to make decisions in a program. It allows a program to execute different blocks of code depending on whether a condition is True or False.

In Python, branching is mainly performed using:

  • if statement
  • if-else statement
  • if-elif-else statement
  • Nested if statements
Condition → True → Execute one block
Condition → False → Execute another block

2. if Statement

The if statement executes a block of code only when its condition is True.

Syntax

if condition:
    statement

Example

age = 20

if age >= 18:
    print("You are an adult.")

Output

You are an adult.

3. When the if Condition is False

If the condition is False, Python skips the indented block.

age = 15

if age >= 18:
    print("You are an adult.")

print("Program completed.")

Output

Program completed.

4. if-else Statement

The if-else statement provides two possible execution paths. If the condition is True, the if block executes. Otherwise, the else block executes.

Syntax

if condition:
    statement1
else:
    statement2

Example

number = 10

if number > 0:
    print("Positive number")
else:
    print("Not a positive number")

Output

Positive number

5. Practical Example – Even or Odd

The modulus operator % can be used to determine whether a number is even or odd.

number = int(input("Enter a number: "))

if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

Sample Output

Enter a number: 24
Even number

6. Positive, Negative or Zero

When more than two possibilities exist, an if-elif-else structure can be used.

number = int(input("Enter a number: "))

if number > 0:
    print("Positive")
elif number < 0:
    print("Negative")
else:
    print("Zero")

Sample Output

Enter a number: -8
Negative

7. if-elif-else Statement

The elif keyword means "else if". It is used when a program needs to test multiple conditions.

Syntax

if condition1:
    statement1
elif condition2:
    statement2
elif condition3:
    statement3
else:
    statement4

Example

marks = 75

if marks >= 90:
    print("Grade A+")
elif marks >= 80:
    print("Grade A")
elif marks >= 70:
    print("Grade B")
else:
    print("Grade C")

Output

Grade B

8. Practical Example – Student Grade

marks = int(input("Enter marks: "))

if marks >= 90:
    grade = "A+"
elif marks >= 80:
    grade = "A"
elif marks >= 70:
    grade = "B"
elif marks >= 60:
    grade = "C"
elif marks >= 50:
    grade = "D"
else:
    grade = "F"

print("Grade:", grade)

Sample Output

Enter marks: 85
Grade: A

9. Nested if Statement

A nested if statement means placing one if statement inside another if statement.

Example

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("Entry allowed")
    else:
        print("ID required")
else:
    print("Entry not allowed")

Output

Entry allowed

10. Branching Using Comparison Operators

Conditions commonly use comparison operators.

Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal a >= b
<= Less than or equal a <= b

11. Branching Using Logical Operators

Logical operators allow multiple conditions to be combined.

  • and – both conditions must be True
  • or – at least one condition must be True
  • not – reverses the Boolean result

Example using and

age = 20
marks = 80

if age >= 18 and marks >= 50:
    print("Eligible")
else:
    print("Not eligible")

Output

Eligible

12. Using the or Operator

day = "Sunday"

if day == "Saturday" or day == "Sunday":
    print("Holiday")
else:
    print("Working day")

Output

Holiday

13. Using the not Operator

logged_in = False

if not logged_in:
    print("Please login first")

Output

Please login first

14. Practical Example – Find Largest of Two Numbers

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
    print("Largest =", a)
elif b > a:
    print("Largest =", b)
else:
    print("Both numbers are equal")

Sample Output

Enter first number: 25
Enter second number: 40
Largest = 40

15. Practical Example – Largest of Three Numbers

a, b, c = map(int, input("Enter three numbers: ").split())

if a >= b and a >= c:
    largest = a
elif b >= a and b >= c:
    largest = b
else:
    largest = c

print("Largest =", largest)

Sample Output

Enter three numbers: 25 60 40
Largest = 60

16. Practical Example – Leap Year

A year is a leap year when it is divisible by 400, or when it is divisible by 4 but not divisible by 100.

year = int(input("Enter year: "))

if year % 400 == 0:
    print("Leap year")
elif year % 100 == 0:
    print("Not a leap year")
elif year % 4 == 0:
    print("Leap year")
else:
    print("Not a leap year")

Sample Output

Enter year: 2024
Leap year

17. Practical Example – Voting Eligibility

age = int(input("Enter your age: "))

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Sample Output

Enter your age: 20
You are eligible to vote.

18. Practical Example – Simple Login Check

username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin" and password == "1234":
    print("Login successful")
else:
    print("Invalid username or password")

Sample Output

Enter username: admin
Enter password: 1234
Login successful

19. Practical Example – Simple Calculator

Branching can be used to create a simple calculator by selecting an operation.

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

operator = input("Enter operator (+, -, *, /): ")

if operator == "+":
    print("Result =", a + b)
elif operator == "-":
    print("Result =", a - b)
elif operator == "*":
    print("Result =", a * b)
elif operator == "/":
    if b != 0:
        print("Result =", a / b)
    else:
        print("Cannot divide by zero")
else:
    print("Invalid operator")

Sample Output

Enter first number: 20
Enter second number: 5
Enter operator (+, -, *, /): *
Result = 100.0

20. Importance of Indentation

Python uses indentation to identify blocks of code. Statements belonging to an if, elif, or else block must be indented consistently.

Correct Example

age = 20

if age >= 18:
    print("Adult")

Important

The statement print("Adult") is indented because it belongs to the if block.


21. Conditional Expression

Python also provides a compact form of branching called a conditional expression.

Syntax

value_if_true if condition else value_if_false

Example

age = 20

status = "Adult" if age >= 18 else "Minor"

print(status)

Output

Adult

22. Flow of Branching

Start

Evaluate Condition

True → Execute True Block

or

False → Execute False / Next Condition

Continue Program


23. Common Errors in Branching

  • Forgetting the colon:
    if age >= 18:
  • Incorrect indentation: Statements inside the branch must be properly indented.
  • Using = instead of ==:
    = is assignment, while == checks equality.
  • Incorrect condition order: In an if-elif structure, conditions should be arranged carefully.

24. Branching Statements Quick Reference

Statement Purpose
if Execute code when a condition is True
if-else Choose between two alternatives
if-elif-else Choose among multiple alternatives
Nested if Place one decision inside another
Conditional expression Compact one-line decision

25. Summary

Branching is an important part of Python programming because it allows a program to make decisions based on conditions.

The main branching structures are if, if-else, if-elif-else, and nested if statements. Comparison operators and logical operators are commonly used to construct branching conditions.

Branching is used in many practical applications including student grading, login systems, voting eligibility, calculators, billing systems, validation, menu-driven programs and decision-making systems.

Created by Bijan Krishna Paul

Computer Science • Python Programming • Data Science

Input and Output Statements,

Input and Output Statements in Python

Complete Tutorial with Examples and Output

1. Introduction

Input and Output are fundamental concepts in every programming language. In Python, input() is mainly used to accept data from the user, while print() is used to display information on the screen.

A simple Python program generally follows this process:

Input → Processing → Output

For example, a program may accept two numbers from the user, calculate their sum, and display the result.


2. Output Statement – print()

The print() function is used to display text, numbers, variables, expressions and other information on the screen.

Syntax

print(value)

Example

print("Hello Python")

Output

Hello Python

3. Printing Numbers

The print() function can display integer and floating-point values.

print(100)
print(25.75)

Output

100
25.75

4. Printing Variables

Variables can be directly passed to the print() function.

name = "Rahul"
age = 20

print(name)
print(age)

Output

Rahul
20

5. Printing Multiple Values

Multiple values can be passed to print() by separating them with commas.

name = "Rahul"
age = 20
marks = 85

print(name, age, marks)

Output

Rahul 20 85

6. Using sep in print()

The sep parameter specifies what should be placed between multiple values printed by print().

print("2026", "09", "09", sep="-")

Output

2026-09-09

Another Example

print("Python", "Programming", "Language", sep=" | ")

Output

Python | Programming | Language

7. Using end in print()

Normally, print() moves to a new line after displaying the output. The end parameter can change this behavior.

print("Hello", end=" ")
print("World")

Output

Hello World

Example 2

print("A", end="-")
print("B", end="-")
print("C")

Output

A-B-C

8. Escape Characters in Output

Escape characters are special characters used inside strings.

New Line – \n

print("Hello\nPython")

Output

Hello
Python

Tab – \t

print("Name\tMarks")
print("Rahul\t85")

Output

Name    Marks
Rahul   85

9. String Concatenation in Output

The + operator can be used to join strings.

first = "Hello"
second = "Python"

print(first + " " + second)

Output

Hello Python

10. Formatted Output using f-strings

An f-string allows variables and expressions to be inserted directly inside a string.

name = "Rahul"
age = 20
marks = 85

print(f"Name: {name}")
print(f"Age: {age}")
print(f"Marks: {marks}")

Output

Name: Rahul
Age: 20
Marks: 85

11. Input Statement – input()

The input() function is used to accept data from the user through the keyboard.

Syntax

variable = input("Message")

Example

name = input("Enter your name: ")

print("Hello", name)

Sample Output

Enter your name: Rahul
Hello Rahul

12. Reading a String from User

By default, the input() function returns the entered value as a string.

city = input("Enter your city: ")

print("You live in", city)

Sample Output

Enter your city: Kolkata
You live in Kolkata

13. Taking Integer Input

If the user enters a number that should be treated as an integer, use int() to convert the input.

age = int(input("Enter your age: "))

print("Your age is", age)

Sample Output

Enter your age: 20
Your age is 20

14. Taking Floating-Point Input

Use float() when the input may contain a decimal value.

price = float(input("Enter price: "))

print("Price =", price)

Sample Output

Enter price: 99.50
Price = 99.5

15. Taking Multiple Inputs

Multiple values can be accepted from one line using split().

a, b = input("Enter two numbers: ").split()

print("First:", a)
print("Second:", b)

Sample Output

Enter two numbers: 10 20
First: 10
Second: 20

16. Taking Multiple Integer Inputs

The map() function can be combined with int() and split() to read multiple integers.

a, b = map(int, input("Enter two numbers: ").split())

print("Sum =", a + b)

Sample Output

Enter two numbers: 10 20
Sum = 30

17. Taking Three Inputs

a, b, c = map(int, input("Enter three numbers: ").split())

print("Total =", a + b + c)

Sample Output

Enter three numbers: 10 20 30
Total = 60

18. Input and Output – Addition Example

This example demonstrates the complete input-processing-output process.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

sum_value = a + b

print("Sum =", sum_value)

Sample Output

Enter first number: 25
Enter second number: 15
Sum = 40

19. Practical Example – Area of Rectangle

length = float(input("Enter length: "))
width = float(input("Enter width: "))

area = length * width

print("Area of rectangle =", area)

Sample Output

Enter length: 10
Enter width: 5
Area of rectangle = 50.0

20. Practical Example – Student Marks

name = input("Enter student name: ")

marks = int(input("Enter marks: "))

print("Student Name:", name)
print("Marks:", marks)

Sample Output

Enter student name: Rahul
Enter marks: 85
Student Name: Rahul
Marks: 85

21. Practical Example – Total and Average Marks

name = input("Enter student name: ")

m1, m2, m3 = map(
    int,
    input("Enter marks of three subjects: ").split()
)

total = m1 + m2 + m3
average = total / 3

print(f"Student: {name}")
print(f"Total Marks: {total}")
print(f"Average: {average:.2f}")

Sample Output

Enter student name: Rahul
Enter marks of three subjects: 80 75 90
Student: Rahul
Total Marks: 245
Average: 81.67

22. Boolean Input

The input() function itself returns a string, so Boolean values need to be handled explicitly.

For example, a simple conversion can be performed using a comparison:

answer = input("Are you a student? ")

is_student = answer.lower() == "yes"

print("Student:", is_student)

Sample Output

Are you a student? yes
Student: True

23. Checking the Type of Input

Since input() returns a string, the type can be checked using type().

value = input("Enter something: ")

print(value)
print(type(value))

Sample Output

Enter something: 100
100
<class 'str'>
Important: Even if the user enters 100, input() initially returns it as a string.

24. Input Type Conversion

Function Purpose Example
str() Convert to string str(100)
int() Convert to integer int("100")
float() Convert to floating point float("10.5")
bool() Convert to Boolean bool(1)

25. Formatting Numerical Output

Formatted output is useful when displaying decimal values such as averages, percentages and prices.

average = 81.67895

print(f"Average = {average:.2f}")

Output

Average = 81.68

26. Displaying a Simple Table

print("Name\tMarks")
print("Rahul\t85")
print("Amit\t90")
print("Riya\t78")

Output

Name    Marks
Rahul   85
Amit    90
Riya    78

27. Complete Input-Processing-Output Program

The following example demonstrates a complete Python program that accepts student information, calculates the total and average marks, and displays the result.

name = input("Enter student name: ")

m1, m2, m3 = map(
    int,
    input("Enter marks of three subjects: ").split()
)

total = m1 + m2 + m3
average = total / 3

print("\n----- STUDENT RESULT -----")
print(f"Name: {name}")
print(f"Subject 1: {m1}")
print(f"Subject 2: {m2}")
print(f"Subject 3: {m3}")
print(f"Total: {total}")
print(f"Average: {average:.2f}")

Sample Output

Enter student name: Rahul
Enter marks of three subjects: 80 75 90

----- STUDENT RESULT -----
Name: Rahul
Subject 1: 80
Subject 2: 75
Subject 3: 90
Total: 245
Average: 81.67

28. Difference Between input() and print()

input() print()
Accepts data from the user Displays data to the user
Returns entered data as a string Displays values on the screen
Used for input Used for output
input("Enter name: ") print("Hello")

29. Important Points for Students

  • print() is used for displaying output.
  • input() is used for accepting user input.
  • input() returns data as a string.
  • Use int() for integer input.
  • Use float() for decimal input.
  • Use split() to separate multiple input values.
  • Use map() to convert multiple input values efficiently.
  • Use sep to control the separator between printed values.
  • Use end to control what is printed at the end of a print() call.
  • Use f-strings for readable formatted output.

30. Quick Reference

Statement / Function Use
input() Take input from user
print() Display output
int() Convert to integer
float() Convert to float
str() Convert to string
split() Separate input values
map() Apply conversion to multiple values
sep Set separator in output
end Control ending of output

31. Summary

Input and Output statements are essential for creating interactive Python programs. The input() function allows a program to receive information from the user, while print() displays information to the user.

By combining input, type conversion, processing and formatted output, Python programmers can create useful applications such as calculators, student-result systems, billing programs and data-entry applications.

Created by Bijan Krishna Paul

Computer Science • Python Programming • Data Science

Tuesday, September 8, 2026

NEP DBMS ASSIGNMENT

SL NO ASSIGNMENT NO DATABSE NAME DATE DESCRIPTION
11 EMLPOYEE
CLICK HERE
2 2 SET OPEARTION,IN,NOT IN,ORDER BY GROUP BY
NOT READY
3 3 SAILOR NOT READY
4 4 DATE NOT READY
5 5 EMPLOYEE CLICK HERE

DBMS Assignment 1 SEM 5 NEP Syllabus

 TABLE 1 :

DEPARTMENT (DID PRIMARY KEY ,DNAME, DLOC)

TABLE 2 :

EMPLOYEE  (EID PRIMARY KEY , ENAME,  ADDRESS, SALARY ,DID)


QUERY:

1. Find the name of all Employees.

2. Find the name of all department.

3.  Find the name of all department located in New Delhi.

4. Find the name of all department located in New Delhi or Mumbai.

5. Find the DID  of IT department.

6. Find the EID  of employees.

7. Find the salary of  'Akash'.

8. Find name,address and salary of  Riya. 

9. Find name,address and salary of employee who are from Vizag. 

10. Find the depertment name of Tuhin.

11. Find the department location of Hiya.

12. Find the name of the employee working in Finance department.

Monday, September 7, 2026

📊 Data Preprocessing in dataset for Machine Learning using python

📊 Data Preprocessing in Machine Learning

Professional College Notes with Python Programs & Outputs

1. What is Data Preprocessing?

Definition:
Data preprocessing is the process of inspecting, cleaning, transforming and preparing raw data before it is supplied to a machine-learning algorithm.

Real-world data is rarely perfect. A dataset may contain missing values, noisy observations, inconsistent formats, categorical values, redundant features and different numerical scales.

Raw Data
Data Cleaning
Transformation
Feature Selection
ML Model
Student Note: The quality of the input data strongly influences the quality of the machine-learning model. Therefore, preprocessing is an important part of the ML workflow.

2. Why Do We Preprocess Data?

Reason Explanation
Improved Data Quality Makes data more consistent, accurate and reliable.
Better Model Performance Helps algorithms identify useful patterns.
Improved Accuracy Properly prepared data can improve meaningful model evaluation.
Reduced Computational Cost Removing unnecessary data can reduce processing requirements.
Feature Engineering Helps identify and construct useful input variables.
Common problems in raw data:
  • Missing values
  • Outliers and noise
  • Inconsistent formats
  • Categorical variables
  • Different feature scales
  • Redundant features
  • High-dimensional data

3. Important Python Libraries

🐼
Pandas Data manipulation
🔢
NumPy Numerical computation
🤖
Scikit-Learn ML preprocessing
📈
Matplotlib Visualization
Python Code
import numpy as np import pandas as pd from sklearn.preprocessing import ( MinMaxScaler, StandardScaler, OneHotEncoder, LabelEncoder ) print("Libraries imported successfully")
Output
Libraries imported successfully

4. Handling Missing Values

A missing value occurs when a dataset does not contain a valid value for a particular observation. Examples include: NaN, None, NULL

4.1 Create a Dataset with Missing Values

import pandas as pd import numpy as np data = { "Age":[20,21,np.nan,23,24], "Salary":[25000,np.nan,30000,32000,35000], "Score":[80,85,90,np.nan,95] } df = pd.DataFrame(data) print(df)
Age Salary Score 0 20.0 25000.0 80.0 1 21.0 NaN 85.0 2 NaN 30000.0 90.0 3 23.0 32000.0 NaN 4 24.0 35000.0 95.0

4.2 Detect Missing Values

print(df.isnull().sum())
Age 1 Salary 1 Score 1 dtype: int64

4.3 Remove Rows

df_removed = df.dropna() print(df_removed)
Age Salary Score 0 20.0 25000.0 80.0 4 24.0 35000.0 95.0
When to use: Row removal can be reasonable when only a small amount of information is missing and removing those observations will not introduce serious bias.

4.4 Mean / Median Imputation

df["Age"] = df["Age"].fillna( df["Age"].mean() ) df["Salary"] = df["Salary"].fillna( df["Salary"].median() ) df["Score"] = df["Score"].fillna( df["Score"].mean() ) print(df)
Age Salary Score 0 20.0 25000.0 80.0 1 21.0 30000.0 85.0 2 22.0 30000.0 90.0 3 23.0 32000.0 87.5 4 24.0 35000.0 95.0
Remember: Mean, median or another appropriate imputation strategy should be selected according to the data and problem. Median is often more robust than mean when extreme values are present.

5. Handling Noisy Data

Noise refers to unwanted variation, errors or irrelevant observations that can obscure useful patterns. Two techniques discussed here are: Smoothing and Binning.

5.1 Smoothing Using Moving Average

data = { "Marks":[50,52,49,90,51,53] } df = pd.DataFrame(data) df["Smoothed"] = ( df["Marks"] .rolling(window=3) .mean() ) print(df)
Marks Smoothed 0 50 NaN 1 52 NaN 2 49 50.33 3 90 63.67 4 51 63.33 5 53 64.67
A moving average can reduce short-term variation, but it does not automatically mean that an unusual observation should be deleted. Domain knowledge is important.

5.2 Binning

marks = [35,42,48,55,63,71,88] bins = [0,40,60,80,100] labels = [ "Poor", "Average", "Good", "Excellent" ] result = pd.cut( marks, bins=bins, labels=labels ) print(result)
['Poor', 'Average', 'Average', 'Average', 'Good', 'Good', 'Excellent']

6. Data Transformation — Normalization

Normalization transforms numerical features to a common range, commonly 0 to 1.
Min-Max Normalization

x' = (x − xmin) / (xmax − xmin)

Python Example

from sklearn.preprocessing import MinMaxScaler data = { "Age":[20,25,30,35,40], "Salary":[20000,40000,60000,80000,100000] } df = pd.DataFrame(data) scaler = MinMaxScaler() normalized = scaler.fit_transform(df) normalized_df = pd.DataFrame( normalized, columns=df.columns ) print(normalized_df)
Age Salary 0 0.00 0.00 1 0.25 0.25 2 0.50 0.50 3 0.75 0.75 4 1.00 1.00
Useful for: Distance-based algorithms such as KNN and K-Means can be sensitive to differences in feature scale.

7. Data Transformation — Standardization

Standardization transforms a feature so that it has approximately mean = 0 and standard deviation = 1.
z = (x − μ) / σ

μ = Mean     σ = Standard Deviation
from sklearn.preprocessing import StandardScaler data = { "Age":[20,25,30,35,40], "Salary":[20000,40000,60000,80000,100000] } df = pd.DataFrame(data) scaler = StandardScaler() standardized = scaler.fit_transform(df) result = pd.DataFrame( standardized, columns=df.columns ) print(result.round(2))
Age Salary 0 -1.41 -1.41 1 -0.71 -0.71 2 0.00 0.00 3 0.71 0.71 4 1.41 1.41
Normalization vs Standardization

Normalization → commonly maps values to a fixed range such as 0 to 1.
Standardization → centers data around 0 using the mean and standard deviation.

8. Encoding Categorical Data

Machine-learning algorithms often require numerical input. Categorical text values therefore need an appropriate numerical representation.

8.1 One-Hot Encoding

One-hot encoding creates a separate binary column for each category.

from sklearn.preprocessing import OneHotEncoder data = pd.DataFrame({ "Color":[ "Red", "Blue", "Green", "Blue", "Red" ] }) encoder = OneHotEncoder( sparse_output=False ) encoded = encoder.fit_transform( data[["Color"]] ) result = pd.DataFrame( encoded, columns=encoder.get_feature_names_out( ["Color"] ) ) print(result)
Color_Blue Color_Green Color_Red 0 0.0 0.0 1.0 1 1.0 0.0 0.0 2 0.0 1.0 0.0 3 1.0 0.0 0.0 4 0.0 0.0 1.0

8.2 Label Encoding

from sklearn.preprocessing import LabelEncoder data = pd.DataFrame({ "Color":[ "Red", "Blue", "Green", "Blue", "Red" ] }) encoder = LabelEncoder() data["Color_Encoded"] = ( encoder.fit_transform( data["Color"] ) ) print(data)
Color Color_Encoded 0 Red 2 1 Blue 0 2 Green 1 3 Blue 0 4 Red 2
Important: Do not blindly use label encoding for nominal input features, because assigning numbers can imply an ordering that may not exist. One-hot encoding is often more appropriate for nominal features.

9. Feature Selection Using Correlation

Correlation measures the strength and direction of a relationship between numerical variables.
Correlation coefficient: −1 ≤ r ≤ +1

r ≈ +1 → strong positive relationship
r ≈ −1 → strong negative relationship
r ≈ 0 → weak or no linear relationship
import pandas as pd data = { "StudyHours":[1,2,3,4,5], "Marks":[40,50,60,70,80], "SleepHours":[8,7,6,5,4] } df = pd.DataFrame(data) correlation = df.corr() print( correlation.round(2) )
StudyHours Marks SleepHours StudyHours 1.00 1.00 -1.00 Marks 1.00 1.00 -1.00 SleepHours -1.00 -1.00 1.00
Interpretation: Features with very high correlation with one another may contain redundant information. However, correlation alone should not be used blindly to remove features; domain knowledge and model validation should also be considered.

10. Chi-Square Feature Selection

The Chi-Square test can be used to evaluate the association between categorical features and a categorical target.
from sklearn.feature_selection import chi2 from sklearn.preprocessing import LabelEncoder import pandas as pd df = pd.DataFrame({ "Color":[ "Red", "Blue", "Red", "Green", "Blue" ], "Target":[ 1, 0, 1, 0, 0 ] }) encoder = LabelEncoder() df["Color_Code"] = ( encoder.fit_transform( df["Color"] ) ) X = df[["Color_Code"]] y = df["Target"] scores, pvalues = chi2(X,y) print("Chi-Square:", scores) print("P-Value:", pvalues)
Chi-Square: [0.625] P-Value: [0.429...]
Interpretation: A small p-value can provide evidence of an association between the feature and target. A common significance threshold is 0.05, but the appropriate threshold and interpretation depend on the statistical context.

11. Feature Extraction

Feature extraction transforms the original feature space into a smaller set of new features while attempting to preserve important information.

One important technique is Principal Component Analysis (PCA).

11.1 Principal Component Analysis

PCA transforms correlated features into a smaller number of orthogonal principal components that capture directions of maximum variance.
import pandas as pd from sklearn.decomposition import PCA data = { "A":[1,2,3,4,5], "B":[10,20,30,40,50], "C":[5,4,3,2,1] } df = pd.DataFrame(data) pca = PCA( n_components=2 ) result = pca.fit_transform(df) pca_df = pd.DataFrame( result, columns=[ "PC1", "PC2" ] ) print(pca_df.round(2)) print( "Explained Variance:", pca.explained_variance_ratio_ )
PC1 PC2 0 20.05 0.00 1 10.02 0.00 2 0.00 0.00 3 -10.02 0.00 4 -20.05 0.00 Explained Variance: [1.000... 0.000...]
Why PCA?
  • Reduces dimensionality
  • Can reduce redundant information
  • Can help visualization
  • Can reduce computational requirements

12. Complete Data Preprocessing Workflow

1. Collect Data
2. Inspect
3. Clean
4. Encode
5. Scale
6. Select Features
7. Train Model
# ========================================== # COMPLETE BASIC PREPROCESSING PIPELINE # ========================================== import pandas as pd from sklearn.model_selection import train_test_split from sklearn.impute import SimpleImputer from sklearn.preprocessing import ( StandardScaler, OneHotEncoder ) # 1. Load data df = pd.read_csv("student_data.csv") # 2. Separate features and target X = df.drop("Result", axis=1) y = df["Result"] # 3. Train-test split X_train, X_test, y_train, y_test = ( train_test_split( X, y, test_size=0.20, random_state=42 ) ) # 4. Handle missing values imputer = SimpleImputer( strategy="median" ) # Apply only to suitable numerical columns # X_train = imputer.fit_transform(X_train) # X_test = imputer.transform(X_test) # 5. Scale numerical features scaler = StandardScaler() # X_train = scaler.fit_transform(X_train) # X_test = scaler.transform(X_test) print("Preprocessing pipeline completed")
Preprocessing pipeline completed
Very Important for Students: Fit preprocessing transformations on the training data and use the learned transformation on the test data. For example:

scaler.fit(X_train)
then
scaler.transform(X_test)

Do not calculate preprocessing parameters from the complete dataset before splitting, because this can cause data leakage.

13. Quick Revision Table

Technique Main Purpose Typical Python Tool
Missing Value Removal Remove incomplete observations dropna()
Imputation Replace missing values fillna(), SimpleImputer
Smoothing Reduce short-term noise rolling()
Binning Group continuous values pd.cut()
Normalization Scale to common range MinMaxScaler
Standardization Mean 0, standard deviation 1 StandardScaler
One-Hot Encoding Categorical → binary columns OneHotEncoder
Label Encoding Categories → integer labels LabelEncoder
Correlation Identify linear relationships DataFrame.corr()
Chi-Square Feature-target association chi2()
PCA Dimensionality reduction PCA()

14. Important Examination Points

Remember these points:
  1. Data preprocessing prepares raw data for machine learning.
  2. Missing values can be removed or imputed.
  3. Mean, median and mode are common simple imputation choices.
  4. Normalization commonly scales values to a fixed range such as 0 to 1.
  5. Standardization produces features centered around zero with unit variance.
  6. One-hot encoding creates binary columns for categories.
  7. Label encoding maps categories to integer labels.
  8. Correlation can help identify redundant numerical features.
  9. Chi-Square can be used for categorical feature selection.
  10. PCA is a dimensionality-reduction technique.
  11. Preprocessing should be performed carefully to avoid data leakage.

15. Final Summary

Good Machine Learning = Good Data + Appropriate Preprocessing + Suitable Model + Proper Evaluation

Data preprocessing is not simply a collection of Python commands. It is a decision-making stage in which the student must understand the structure, quality and meaning of the data.

The correct preprocessing technique depends on the type of data, the machine-learning algorithm, the problem being solved, and the assumptions behind the technique.

Reference: DZone — Machine Learning With Python: Data Preprocessing Techniques
```