Saturday, September 27, 2025

UNIT - I & WEEK 1 PROGRAMS

UNIT - I

 

History of Python Programming Language

 

1. Origin and Creation

  • Creator: Guido van Rossum
  • Year of Creation: Late 1980s (1989)
  • Place: Netherlands, at Centrum Wiskunde & Informatica (CWI)
  • Purpose: To design a language that is easy to read, write, and understand — combining the power of C with the simplicity of shell scripting.

 

2. Inspiration

  • Python was inspired by:
    • ABC language (a simple teaching language)
    • Features from C, Modula-3, and Unix shell scripting
  • The name “Python” comes from the British comedy show “Monty Python’s Flying Circus”, not from the snake.

 

3. Development Timeline

Version

Year Released

Key Features

Python 1.0

1991

Introduced core features like functions, exceptions, and core data types (list, dict, str)

Python 2.0

2000

Added garbage collection and Unicode support

Python 3.0

2008

Major redesign; improved readability, removed old features

Python 3.x series

2010–present

Continuous improvements — performance, security, async programming, etc.

 

4. Growth and Popularity

  • Open source and supported by a large community.
  • Gained popularity due to:
    • Easy syntax (close to English)
    • Cross-platform support
    • Huge library ecosystem
  • Extensively used in:
    • Web Development (Django, Flask)
    • Data Science & AI (NumPy, Pandas, TensorFlow)
    • Automation & Scripting
    • Education and Research

 

5. Current Status

  • Latest version (as of 2025): Python 3.12 / 3.13
  • Maintained by the Python Software Foundation (PSF).
  • Python is one of the most popular programming languages in the world today, widely used in academics, industry, and research.

 

Thrust Areas of Python Programming Language

 

The thrust areas of Python refer to the main domains or fields where Python is most widely applied and has shown significant impact in recent years.

 

1. Artificial Intelligence (AI) and Machine Learning (ML)

  • Python is the most preferred language for AI and ML.
  • Popular libraries: TensorFlow, Keras, Scikit-learn, PyTorch
  • Used for:
    • Predictive modeling
    • Image and speech recognition
    • Natural Language Processing (NLP)
    • Recommendation systems

 

2. Data Science and Data Analytics

  • Python simplifies data collection, cleaning, analysis, and visualization.
  • Libraries: NumPy, Pandas, Matplotlib, Seaborn, Plotly
  • Applications:
    • Big data handling
    • Business intelligence
    • Statistical analysis and visualization

 

3. Web Development

  • Python supports dynamic and scalable web applications.
  • Frameworks: Django, Flask, FastAPI
  • Used for:
    • Backend server programming
    • RESTful APIs
    • Database-driven websites

 

4. Automation and Scripting

  • Python is ideal for automating repetitive tasks.
  • Applications:
    • File management
    • Data entry automation
    • Web scraping (using BeautifulSoup, Selenium)
    • System administration scripts

 

5. Internet of Things (IoT)

  • Python runs efficiently on small devices (e.g., Raspberry Pi).
  • Used to:
    • Collect and process sensor data
    • Control hardware devices
    • Build smart home and industrial IoT systems

 

6. Game Development

  • Python is used for prototyping and creating 2D/3D games.
  • Library: Pygame
  • Example: Building educational games and simulations.

 

7. Scientific and Research Computing

  • Extensively used in academic and research fields.
  • Libraries: SciPy, SymPy, Matplotlib
  • Used for:
    • Mathematical modeling
    • Scientific simulations
    • Research data visualization

 

8. Software Development and Testing

  • Python aids in developing and testing applications efficiently.
  • Tools: PyTest, Robot Framework, Selenium
  • Benefits:
    • Rapid prototyping
    • Easy debugging
    • Platform independence

 

9. Cyber security and Ethical Hacking

  • Used for penetration testing, malware analysis, and automation of security tools.
  • Tools built with Python: Scapy, Requests, Paramiko

 

10. Cloud Computing and DevOps

  • Python integrates well with cloud platforms and DevOps tools.
  • Used for:
    • Cloud automation (AWS, Azure, Google Cloud SDKs)
    • Continuous Integration/Deployment (CI/CD) scripts

 

 

Thrust Area

Main Use

Key Libraries/Tools

AI & ML

Intelligent systems

TensorFlow, Keras

Data Science

Data handling & visualization

Pandas, NumPy

Web Development

Dynamic websites

Django, Flask

Automation

Task automation

Selenium, OS, PyAutoGUI

IoT

Embedded devices

Raspberry Pi, MicroPython

Game Dev

Simple games

Pygame

Scientific Computing

Simulations, research

SciPy, SymPy

Testing

QA and automation

PyTest, Robot Framework

Cybersecurity

Ethical hacking

Scapy, Requests

Cloud & DevOps

Deployment automation

Boto3, Fabric

 

Anaconda Python Distribution

 

1. Introduction

  • Anaconda is a free and open-source Python (and R) distribution.
  • It is mainly used for Data Science, Machine Learning, and Scientific Computing.
  • It simplifies package management and deployment.

 

2. Developer

  • Developed by Anaconda, Inc.
  • Initially released in 2012.

 

3. Why Anaconda?

  • Installing Python libraries manually (like NumPy, Pandas, etc.) can be difficult due to dependency issues.
  • Anaconda solves this by providing:
    • Pre-installed scientific libraries
    • Easy package installation using Conda
    • An environment manager to handle multiple projects

 

Component

Description

Conda

A package and environment manager used to install and update Python packages.

Spyder

A Python IDE (Integrated Development Environment) included with Anaconda.

Jupyter Notebook

A web-based interactive tool for writing and running Python code with visual outputs.

Anaconda Navigator

A GUI (Graphical User Interface) to manage environments, packages, and tools easily without command line.

Pre-installed Libraries

Includes over 150+ scientific packages such as NumPy, Pandas, Matplotlib, SciPy, and Scikit-learn.

 

5. Features of Anaconda

  • Cross-platform (works on Windows, macOS, Linux)
  • Comes with data science and machine learning tools
  • Easy package management using conda
  • Supports virtual environments
  • Includes Jupyter Notebook for interactive programming
  • Reduces setup time for data analysis and AI projects

 

6. Installing Anaconda

  1. Download from official site: https://www.anaconda.com
  2. Install using the installer for your OS (Windows/macOS/Linux)
  3. Verify installation by typing in Command Prompt or Anaconda Prompt:

 

conda --version

python –version

 

  1. Launch Anaconda Navigator to access tools like Spyder and Jupyter Notebook.

 

 

Working with Anaconda

  • To create a new environment:

conda create -n myenv python=3.12

 

  • To activate the environment:

conda activate myenv

 

  • To install a package:

conda install numpy

 

  • To list installed packages:

             conda list

 

8. Advantages

  • Simplifies Python setup for beginners
  • Ideal for students and researchers
  • Provides stable versions of data science packages
  • Works well for large-scale projects

 

9. Limitations

  • Large installation size (~3 GB)
  • May be slower to start compared to a basic Python setup
  • Some users prefer lightweight options like Miniconda

 

Installing and Using Jupyter Notebook.

 

1. Introduction to Jupyter Notebook

  • Jupyter Notebook is an open-source interactive web-based tool used for:
    • Writing and running Python code
    • Visualizing data
    • Creating reports and presentations
  • It allows combining code, text, images, and visualizations in a single document — great for learning, data analysis, and research.

 

2. What is Jupyter?

  • The name “Jupyter” comes from JUlia, PYThon, and R — the main languages it initially supported.
  • Commonly used by students, engineers, data scientists, and researchers.

 

3. Requirements

To use Jupyter Notebook, you must have:

  • Python installed
  • Or preferably, Anaconda Distribution, which includes Jupyter Notebook by default

 

4. Installation Methods

A. Using Anaconda (Recommended for Students)

  1. Download Anaconda:
    Visit
    👉 https://www.anaconda.com
  2. Install it:
    Follow the installation wizard (Next → Next → Finish).
  3. Launch Jupyter Notebook:
    • Open Anaconda Navigator
    • Click “Launch” under Jupyter Notebook

 

B. Using Command Prompt (Without Anaconda)

If you have only Python installed, you can install Jupyter manually:

pip install notebook

Then, to launch Jupyter Notebook:

jupyter notebook

 

5. Starting Jupyter Notebook

  • After launching, it will open automatically in your default web browser.
  • The homepage (called the Dashboard) shows:
    • Files and folders on your computer
    • Options to create a new notebook or open existing ones

 

 

 

6. Creating a New Notebook

  1. Click “New” → Python 3 (ipykernel)
  2. A new notebook will open with empty cells
  3. You can type Python code inside a cell and press:
    • Shift + Enter → to run the code
    • Ctrl + Enter → to run the code and stay in the same cell

 

7. Structure of a Notebook

A Jupyter Notebook contains:

  • Code Cells → where you write and execute code
  • Markdown Cells → for notes, headings, and explanations using simple text formatting

Example of Markdown syntax:

# This is a heading

**Bold text**

*Italic text*

 

8. Example in Jupyter Notebook

# Python Example

import math

radius = 5

area = math.pi * radius**2

print("Area of Circle:", area)

✅ When you run this cell, the output will be displayed just below the code.

 

9. Saving and Exporting Notebook

  • Save: Click on đź’ľ icon or press Ctrl + S
  • Export: You can download your notebook as:
    • .ipynb (default format)
    • .html or .pdf (via File → Download as)

 

10. Advantages of Using Jupyter Notebook

 

Feature

Description

Interactive

Run and modify code instantly

Visualization

Displays charts and graphs inline

Documentation

Combine code with notes and explanations

Beginner-Friendly

Simple interface for learning Python

Supports Libraries

Works well with NumPy, Pandas, Matplotlib, etc.

 

11. Tips for Students

  • Always rename your notebook properly (e.g., Python_Lab_Exp1.ipynb)
  • Use Markdown cells for writing experiment aims, outputs, and conclusions
  • Keep your work organized in folders

 

Aspect

Details

Tool Name

Jupyter Notebook

Use

Writing, running, and documenting Python programs interactively

Installation

Via Anaconda or pip

Ideal For

Learning, Data Science, AI, and Research

File Extension

.ipynb

 

Parts of Python Programming Language

 

1. Introduction

Python is a high-level, interpreted, and user-friendly programming language.
It is widely used in software development, data science, artificial intelligence, and web applications.

To learn Python effectively, students must understand the basic parts or building blocks of the language.

 

S.No

Part

Description

1

Identifiers

Names used to identify variables, functions, classes, etc.

2

Keywords

Reserved words with predefined meanings in Python.

3

Statements and Expressions

Instructions or operations that perform specific tasks.

4

Variables

Used to store data values in memory.

5

Operators

Symbols that perform operations on variables and values.

6

Operator Precedence and Associativity

Define the order in which operators are executed.

7

Data Types

Specify the type of data stored in variables.

8

Indentation

Space used to represent code blocks.

9

Comments

Notes added in code for explanation (ignored by interpreter).

10

Input and Output

Taking input from the user and displaying output.

11

Type Conversion

Converting one data type into another.

 

 

3. Explanation of Each Part

 

1. Identifiers

  • Identifiers are names given to variables, functions, classes, etc.
  • They must begin with a letter or underscore (_) and cannot use Python keywords.
    Example:

student_name = "Anu"

age = 20

 

2. Keywords

  • Keywords are reserved words that have special meaning in Python.
  • Examples: if, else, for, while, class, def, True, False, None
    Example:

if age >= 18:

    print("Eligible to vote")

 

3. Statements and Expressions

  • Statement: A complete line of code that performs some action.
  • Expression: A combination of values and operators that produces a result.
    Example:

x = 10 + 5   # Expression inside a statement

 

📦 4. Variables

  • Variables are used to store values.
  • Python automatically assigns data type when value is given.
    Example:

name = "Python"

year = 1991

 

5. Operators

  • Operators are symbols that perform mathematical or logical operations.
    Example:

x = 10

y = 5

print(x + y)   # Arithmetic

print(x > y)   # Relational

 

6. Operator Precedence and Associativity

  • Precedence: Determines which operator is evaluated first.
  • Associativity: Determines the direction (left to right / right to left).
    Example:

result = 10 + 2 * 3   # Multiplication has higher precedence

 

7. Data Types

Python supports different data types:

  • Numeric: int, float, complex
  • Sequence: str, list, tuple
  • Mapping: dict
  • Set types: set, frozenset
  • Boolean: bool
    Example:

a = 10

b = 12.5

c = "Hello"

 

8. Indentation

  • Indentation in Python defines code blocks instead of using { }.
    Example:

if x > 0:

    print("Positive number")

else:

    print("Negative number")

 

9. Comments

  • Used to add explanations or notes in the program.
  • Single-line comment: Starts with #
  • Multi-line comment: Enclosed in triple quotes ''' ''' or """ """
    Example:

# This is a single-line comment

'''This is

a multi-line comment'''

 

10. Input and Output

  • Input: input() function is used to take user input.
  • Output: print() function displays output.
    Example:

name = input("Enter your name: ")

print("Hello,", name)

 

11. Type Conversion

  • Changing data type from one form to another using functions like int(), float(), str().
    Example:

x = "5"

y = int(x)

print(y + 10)

 

 

Part

Purpose

Example

Identifiers

Naming variables/functions

name, total_marks

Keywords

Reserved words

if, else, for

Variables

Store data

age = 21

Operators

Perform operations

+, -, and

Data Types

Define value type

int, float, str

Indentation

Define code blocks

if x > 0:

Comments

Add explanations

# comment

Input/Output

Interact with user

input(), print()

 

 

Identifiers,

 

  • Identifiers are names given to variables, functions, classes, objects, or modules.
  • They help to uniquely identify different elements in a Python program. In simple terms:
    An identifier is just a name you give to something you create in your code.

 

Examples of Identifiers

student_name = "Madhu"

age = 20

def calculate_total():

    pass

Here:

  • student_name → Identifier for a variable
  • age → Identifier for another variable
  • calculate_total → Identifier for a function

 

Rules for Writing Identifiers

Rule

Description

Example

1

Must begin with a letter (A–Z or a–z) or an underscore (_) only

name, _student

2

Can contain letters, digits, and underscores

student1, student_name

3

Cannot start with a digit

1name

4

No special symbols like @, $, %

name@123

5

Case-sensitive (Name ≠ name)

age and Age are different

6

Cannot use Python keywords as identifiers

class, def, if

7

Should be meaningful and readable

total_marks, x1y2z3

 

Valid Identifiers

student = "Asha"

_student = "B.Tech"

student_123 = "Roll No"

totalMarks = 95

 

Invalid Identifiers

1student = "Asha"     # starts with a digit

student-name = "Asha" # contains a special character '-'

class = "CSE"         # 'class' is a keyword

 

 

Python Keywords

  • Keywords are predefined reserved words in Python.
  • They cannot be used as identifiers.

Example:

# Invalid

def = 10  # ❌ 'def' is a keyword

You can check all Python keywords using:

import keyword

print(keyword.kwlist)

 

Example Program

name = "Ravi"

roll_number = 45

def display_details():

    print("Name:", name)

    print("Roll Number:", roll_number)

 

display_details()

Output:

Name: Ravi

Roll Number: 45

 

Concept

Explanation

Example

Identifier

Name used to identify variables, functions, etc.

student_name

Starts with

Letter or underscore

_value

Allowed characters

Letters, digits, underscore

mark_1

Not allowed

Keywords, special symbols

class, total$

Case sensitive

Yes

Namename

 

 

Keywords

 

Definition

  • Keywords are special reserved words in Python that have predefined meanings and purposes.
  • They are used by the Python interpreter to understand the structure and logic of the program.
  • You cannot use keywords as variable names, function names, or identifiers.

 

In simple words:
Keywords are the building blocks of Python syntax — they tell Python what to do.

 

Example

if age > 18:

    print("Eligible to vote")

else:

    print("Not eligible")

Here,
if and else are keywords that control the flow of the program.

 

Feature

Description

Predefined

Keywords are built into Python — they cannot be created or changed by users.

Cannot be used as identifiers

You can’t name a variable or function with a keyword (e.g., class = 10 ).

Case-sensitive

Python keywords are always lowercase (True, False, and None are exceptions).

Fixed Number

The number of keywords may change between Python versions (usually ~35–36).

 

 

Common Python Keywords

Category

Keywords

Control Flow

if, else, elif, for, while, break, continue, pass

Boolean / Logical

True, False, and, or, not

Loop Control

break, continue, pass

Function Definition

def, return, lambda

Class & Object

class, self, del

Exception Handling

try, except, finally, raise, assert

Import / Modules

import, from, as

Variable Handling

global, nonlocal, None

Others

in, is, yield, with

 

Example Program using Keywords

class Student:

    def __init__(self, name, marks):

        self.name = name

        self.marks = marks

 

    def display(self):

        if self.marks >= 50:

            print(self.name, "passed")

        else:

            print(self.name, "failed")

 

# Object creation

s1 = Student("Asha", 75)

s1.display()

Keywords used:
class, def, if, else, self

 

Invalid Example (Using Keyword as Variable Name)

class = "CSE"   # ❌ Error — 'class' is a reserved keyword

 

Viewing All Python Keywords

You can check all the keywords in your Python version using:

import keyword

print(keyword.kwlist)

 

Example Output (Python 3.11+):

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

 

 

Statements and Expressions

 

Introduction

Every Python program is made up of statements and expressions.
They form the basic structure of how a program performs actions and produces results.

 

Expression in Python

Definition:

An expression is a combination of values, variables, operators, and function calls that produces a value.

 

In simple terms:
An expression is something that evaluates to a value.

Examples:

5 + 3

a + b

x * (y + 2)

len("Python")

Each of the above produces a result:

  • 5 + 3 → 8
  • len("Python") → 6

Example in Code:

x = 10

y = 5

z = x + y   # 'x + y' is an expression

print(z)

Output:

15

 

Expression always has a value and can be used inside statements.

 

Statement in Python

Definition:

A statement is a complete instruction that tells the Python interpreter to perform an action.

In simple terms:
A statement is a command or instruction.

 

Examples:

x = 10            # Assignment statement

print(x)          # Print statement

if x > 5:         # Conditional statement

    print("Big")

Statements do something — assign values, display output, make decisions, etc.

 

Types of Statements

 

Type

Description

Example

Assignment Statement

Assigns a value to a variable

x = 10

Print Statement

Displays output

print("Hello")

Conditional Statement

Makes decisions

if x > 0: print("Positive")

Looping Statement

Repeats actions

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

Import Statement

Imports a module

import math

Function Definition

Defines a function

def add():

Pass Statement

Placeholder, does nothing

pass

 

Difference between Expression and Statement

 

Feature

Expression

Statement

Definition

Produces a value

Performs an action

Example

x + y

x = x + y

Has a result?

Yes, gives a value

No, executes a command

Used inside

Statements

Programs / Blocks

Evaluated by

Returns a value

Executes instruction

 

Example to Compare

x = 5 + 3

  • Expression: 5 + 3 (produces 8)
  • Statement: x = 5 + 3 (assigns 8 to x)

 

Example Program

x = 10

y = 20

 

# Expression inside statement

if (x + y) > 25:

    print("Sum is greater than 25")

else:

    print("Sum is smaller")

Output:

Sum is greater than 25

 

Here:

  • (x + y) → Expression
  • if, else, print → Statements

 

Expression Statement

An expression statement is when an expression is written alone, and its result is used or displayed.

Example:

print(5 + 3)

Here 5 + 3 is an expression, but the entire line is an expression statement.

 

Compound Statements

Some statements contain other statements inside them — e.g.:

  • if
  • for
  • while
  • def
  • class

Example:

def greet():

    print("Hello Students!")

Here, the function definition is a compound statement containing a simple statement (print()).

 

Concept

Definition

Example

Expression

Combination of values and operators that gives a value

x + y, 5 * 2

Statement

Instruction executed by Python

x = 10, if, for

Expression Statement

Expression + action

print(5 + 3)

Compound Statement

Contains other statements

if, for, def, class

 

 

 

Variables and Operators in Python

In any programming language, variables are used to store data, and operators are used to perform operations on that data.
Python makes working with both very simple and flexible.

Variables in Python

Definition:

A variable is a name that refers to a memory location where data is stored.
It acts as a container for holding values.

In simple words:
A variable is like a box where you can store information and use it later.

 

Example:

name = "Asha"

age = 20

marks = 87.5

 

Here:

  • name stores a string value
  • age stores an integer
  • marks stores a floating-point value

Rules for Naming Variables

Rule

Example

Must start with a letter or underscore (_)

student, _name

Can contain letters, digits, and underscores

student_1

Cannot start with a digit

1name

Cannot use Python keywords

class, for

Case-sensitive

Name ≠ name

 

Dynamic Typing in Python

 

Python automatically detects the data type of a variable.

x = 10        # integer

x = "Hello"   # now becomes string

You don’t need to declare variable types explicitly.

Variable Assignment

a = 10

b = 20

c = a + b

print(c)      # Output: 30

 

You can assign the same value to multiple variables:

x = y = z = 50

Or assign multiple values in one line:

a, b, c = 5, 10, 15

 

Operators in Python

Definition:

Operators are special symbols or keywords that perform operations on values and variables.

 

Example: +, -, *, /, ==, and, or

 

Types of Operators in Python

Type

Description

Example

1. Arithmetic Operators

Perform mathematical operations

+, -, *, /, %, //, **

2. Relational (Comparison)

Compare values

==, !=, >, <, >=, <=

3. Logical Operators

Combine conditions

and, or, not

4. Assignment Operators

Assign values to variables

=, +=, -=, *=, /=

5. Bitwise Operators

Perform bit-level operations

&, `

6. Membership Operators

Test membership in sequence

in, not in

7. Identity Operators

Compare object memory locations

is, is not

1. Arithmetic Operators

a = 10

b = 3

print(a + b)   # 13

print(a - b)   # 7

print(a * b)   # 30

print(a / b)   # 3.3333

print(a // b)  # 3 (Floor Division)

print(a % b)   # 1 (Remainder)

print(a ** b)  # 1000 (Power)

 

2. Relational Operators

Used for comparison — result is always True or False.

a = 5

b = 10

print(a < b)   # True

print(a == b)  # False

 

3. Logical Operators

Used for combining multiple conditions.

x = 5

print(x > 2 and x < 10)   # True

print(x > 10 or x < 2)    # False

print(not(x > 2))         # False

 

4. Assignment Operators

Used to assign values with arithmetic operations.

x = 10

x += 5     # same as x = x + 5

print(x)   # 15

5. Bitwise Operators

Work at the binary (bit) level.

a = 5    # 0101

b = 3    # 0011

print(a & b)   # 1  (AND)

print(a | b)   # 7  (OR)

print(a ^ b)   # 6  (XOR)

print(~a)      # -6 (NOT)

6. Membership Operators

Used to check if a value exists in a sequence.

name = "Python"

print('P' in name)       # True

print('z' not in name)   # True

 

7. Identity Operators

Compare memory locations of two objects.

x = [1, 2, 3]

y = x

z = [1, 2, 3]

print(x is y)      # True  (same object)

print(x is z)      # False (different object)

 

Operator Precedence

When multiple operators appear, Python follows a specific order of execution.

Precedence

Operator

1

() Parentheses

2

** Exponent

3

*, /, //, %

4

+, -

5

<, >, <=, >=, ==, !=

6

not

7

and

8

or

 

Example:

x = 10 + 2 * 5

print(x)    # Output: 20 (multiplication first)

Precedence and Associativity

Introduction

When an expression in Python contains more than one operator, it is important to know which operation is performed first.
Python follows two main rules for this:

  1. Operator Precedence — decides which operator is evaluated first.
  2. Operator Associativity — decides the direction (left or right) in which operators of the same precedence are evaluated.

 

What is Operator Precedence?

Definition:

Operator Precedence determines the priority of operators in an expression.
Operators with higher precedence are evaluated before those with lower precedence.

Think of precedence as “who gets to act first” in a math expression.

 

Example:

x = 10 + 2 * 3

print(x)

Explanation:
Multiplication (*) has higher precedence than addition (+),
so Python evaluates 2 * 3 first → 6, then 10 + 6 → 16.

Output:

16

 

Precedence Table (Highest → Lowest)

Precedence Level

Operator

Description

1

()

Parentheses (used to group expressions)

2

**

Exponentiation (Power)

3

+x, -x, ~x

Unary plus, minus, bitwise NOT

4

*, /, //, %

Multiplication, Division, Floor Division, Modulus

5

+, -

Addition and Subtraction

6

<<, >>

Bitwise Shift Operators

7

&

Bitwise AND

8

^, `

`

9

<, <=, >, >=, ==, !=

Comparison Operators

10

not

Logical NOT

11

and

Logical AND

12

or

Logical OR

13

=, +=, -=, *=, /=, etc.

Assignment Operators

 

Example Demonstration:

result = 5 + 2 * 3 ** 2

print(result)

Step-by-step Evaluation:

  1. ** → 3 ** 2 = 9
  2. * → 2 * 9 = 18
  3. + → 5 + 18 = 23

Output:

23

 

What is Associativity?

Definition:

Associativity defines the order of evaluation when two or more operators of the same precedence appear in an expression.

It tells whether Python evaluates from Left to Right or Right to Left.

 

Types of Associativity

Associativity

Example Operators

Direction

Left-to-Right

+, -, *, /, %, <, >, ==, !=, and, or

Left → Right

Right-to-Left

**, =, +=, -=, not

Right → Left

 

Example 1: Left-to-Right Associativity

x = 10 - 5 + 2

print(x)

Explanation:
10 - 5 → 5 → 5 + 2 → 7

Output:

7

 

Example 2: Right-to-Left Associativity

x = 2 ** 3 ** 2

print(x)

Explanation:

  • Both are ** (same precedence)
  • Associativity is Right to Left
  • So 3 ** 2 = 9, then 2 ** 9 = 512

Output:

512

 

Combining Precedence and Associativity

Example:

x = 100 / 10 * 5

print(x)

  • Both / and * have the same precedence
  • Associativity is Left to Right
  • So, 100 / 10 = 10, then 10 * 5 = 50

Output:

50

 

Parentheses Have Highest Priority

Use parentheses () to change the order of evaluation.

Example:

x = (10 + 5) * 2

print(x)

Without parentheses: 10 + 5 * 2 = 20
With parentheses: (10 + 5) * 2 = 30

Output:

30

Data Types in Python

Introduction

  • In Python, data type represents the type of value stored in a variable.
  • It tells what kind of data can be stored and what operations can be performed on it.

Python is a dynamically typed language — you don’t need to declare the type of variable explicitly.
The interpreter decides the type automatically based on the value assigned.

✅ Example:

x = 10        # integer

y = 3.14      # float

name = "Madhu"  # string

 

Major Categories of Data Types

Python has several built-in data types, grouped as follows:

Category

Data Types

Examples

Numeric

int, float, complex

10, 3.5, 2 + 3j

Sequence

str, list, tuple

"hello", [1,2,3], (4,5,6)

Set

set, frozenset

{1,2,3}

Mapping

dict

{'name':'Latha', 'age':20}

Boolean

bool

True, False

Binary

bytes, bytearray, memoryview

b'Hello'

 

Numeric Data Types

(a) int

  • Represents whole numbers (positive or negative) without decimals.
  • No size limit in Python.

a = 25

b = -100

print(type(a))   # <class 'int'>

 

(b) float

  • Represents numbers with a decimal point.

pi = 3.14159

print(type(pi))  # <class 'float'>

 

(c) complex

  • Represents complex numbers in the form a + bj,
    where a is the real part, and b is the imaginary part.

z = 2 + 3j

print(type(z))   # <class 'complex'>

 

Sequence Data Types

(a) str (String)

  • Sequence of characters enclosed in single (' '), double (" "), or triple quotes (''' ''').

name = "Python"

print(name[0])   # P

print(type(name))

 

(b) list

  • Ordered, mutable (changeable) collection of items.
  • Items can be of different types.

fruits = ['apple', 'banana', 'cherry']

fruits[1] = 'orange'

print(fruits)

 

(c) tuple

  • Ordered but immutable (unchangeable) collection of items.

colors = ('red', 'green', 'blue')

print(colors[0])   # red

 

Set Data Types

(a) set

  • Unordered, unique collection of items.
  • Does not allow duplicates.

numbers = {1, 2, 3, 2}

print(numbers)   # {1, 2, 3}

 

(b) frozenset

  • Similar to set, but immutable.

fs = frozenset([1, 2, 3])

Mapping Data Type

dict (Dictionary)

  • Stores data as key-value pairs.
  • Keys are unique and immutable.

student = {'name': 'Madhu', 'age': 20, 'branch': 'CSE'}

print(student['name'])   # Madhu

 

Boolean Data Type

 

bool

  • Represents logical values True or False.
  • Used in conditions and comparisons.

x = True

y = False

print(10 > 5)   # True

 

Binary Data Types

Type

Description

Example

bytes

Immutable sequence of bytes

b'Hello'

bytearray

Mutable version of bytes

bytearray([65,66,67])

memoryview

Access buffer data without copying

memoryview(b'Python')

Type Conversion

Python allows conversion between data types using built-in functions.

Function

Purpose

Example

int()

Converts to integer

int(3.9) → 3

float()

Converts to float

float(5) → 5.0

str()

Converts to string

str(25) → '25'

list()

Converts to list

list('abc') → ['a','b','c']

 

Checking Data Type

 

Use the built-in type() function.

a = 10

b = "hello"

print(type(a))   # <class 'int'>

print(type(b))   # <class 'str'>

 

Data Type

Mutable?

Ordered?

Example

int, float, complex

N/A

10, 3.14, 2+3j

str

"hello"

list

[1,2,3]

tuple

(1,2,3)

set

{1,2,3}

dict

✅ (v3.7+)

{'a':1, 'b':2}

bool

N/A

True

bytes

b'ABC'

Indentation, Comments, Input, and Output

Indentation in Python

Definition:
Indentation refers to the spaces at the beginning of a line of code.
In Python, indentation is used to define blocks of code, such as loops, functions, and conditionals.
Unlike other languages (like C, C++, or Java) that use { } braces, Python uses indentation to represent scope.

Syntax Example:

if 5 > 2:

    print("Five is greater than two!")

Key Points:

  • Standard indentation = 4 spaces
  • Improper indentation → IndentationError
  • Consistent indentation is mandatory.

 

Example of Error:

if 5 > 2:

print("Error due to no indentation")  #

 

Comments in Python

 

Definition:
Comments are used to explain code and are ignored by the Python interpreter.

Types of Comments:

  1. Single-line Comment
  2. # This is a single-line comment
  3. print("Hello, Python!")
  4. Multi-line Comment
    (There’s no special multi-line comment symbol, but we use triple quotes)
  5. """
  6. This is a multi-line comment
  7. used for documentation or explanations.
  8. """
  9. Inline Comment
  10. x = 10  # Assigning value to x

 

Reading Input in Python

 

Definition:
Used to take input from the user through the keyboard.

 

Syntax:

variable = input("Enter something: ")

 

Example:

name = input("Enter your name: ")

print("Hello,", name)

Important Note:

  • The input() function always returns data as a string.
  • Convert it to another type if needed:
  • age = int(input("Enter your age: "))

 

Print Output in Python

Definition
The print() function is used to display output on the screen.

 

Syntax:

print(object, sep=' ', end='\n')

 

Examples:

print("Hello, World!")

print("Python", "is", "fun", sep="-")

print("This is line 1", end=" ")

print("This is line 2")

 

Output:

Hello, World!

Python-is-fun

This is line 1 This is line 2

Concept

Description

Example

Indentation

Defines code blocks

if x>0:\n print("Positive")

Comments

Explain code

# This is a comment

Input

Takes user input

name = input("Enter name: ")

Output

Displays information

print("Hello", name)

 

 

Type Conversions in Python

Definition:

Type conversion is the process of changing one data type into another.

Python performs two types of conversions:

 

Implicit Type Conversion (Automatic)

Done automatically by Python — no user involvement.
Python converts smaller data types to larger ones to avoid data loss.

 

Example:

x = 5      # int

y = 2.5    # float

z = x + y  # Python converts x into float

print(z)

print(type(z))

 

Output:

7.5

<class 'float'>

Here, Python automatically converts int → float.

 

Explicit Type Conversion (Type Casting)

User manually converts one type to another using built-in functions like:
int(), float(), str(), list(), tuple(), etc.

 

Example:

x = 10

y = float(x)    # Convert int to float

print(y)

 

a = "25"

b = int(a)      # Convert string to int

print(b + 5)

 

Output:

10.0

30

 

Common Type Conversion Functions

 

Function

Description

Example

Output

int(x)

Converts to integer

int(3.7)

3

float(x)

Converts to float

float(5)

5.0

str(x)

Converts to string

str(25)

'25'

list(x)

Converts to list

list((1,2,3))

[1,2,3]

tuple(x)

Converts to tuple

tuple([1,2,3])

(1,2,3)

 

The type() Function

 

Definition:
The type() function is used to find the data type of a variable or value.

 

Syntax:

type(object)

 

Example:

a = 10

b = 3.14

c = "Python"

 

print(type(a))

print(type(b))

print(type(c))

 

Output:

<class 'int'>

<class 'float'>

<class 'str'>

✅ Used widely for debugging and data validation.

 

The is Operator

Definition:
The is operator is used to compare the identity of two objects, i.e.,
to check whether two variables refer to the same object in memory.

 

Syntax:

x is y

x is not y

 

Example:

a = [1, 2, 3]

b = [1, 2, 3]

c = a

print(a == b)   # True (values are same)

print(a is b)   # False (different memory locations)

print(a is c)   # True (same memory location)

Output:

True

False

True

== → Compares values
is → Compares memory identity

 

Concept

Description

Example

Output

Type Conversion

Changing data type

float(5)

5.0

Implicit Conversion

Auto conversion by Python

5 + 3.5

8.5

Explicit Conversion

Manual conversion by user

int('10')

10

type() Function

Returns data type

type(10)

<class 'int'>

is Operator

Checks object identity

a is b

True / False

 

Dynamic Typing in Python

Definition:
Python is a dynamically typed language, which means you don’t need to declare the type of a variable when you create it.
The type is decided automatically at runtime (when the program runs).

Example:

x = 10        # x is an integer

print(type(x))

 

x = "Python"  # Now x is a string

print(type(x))

 

Output:

<class 'int'>

<class 'str'>

 

Explanation:

  • The variable x can hold different types of data at different times.
  • Python automatically detects the data type at runtime.

Key Points:

  • No need for explicit type declaration (like in C/C++).
  • Type is determined dynamically.
  • Easier and faster to code.

Disadvantage:

  • Type errors may occur during execution, not compilation.

Strong Typing in Python

Definition:
Python is a strongly typed language, meaning it does not automatically convert one data type to another when performing operations.
You must explicitly convert between incompatible types.

 

Example 1 – Type Error

x = "10"

y = 5

print(x + y)   # ❌ Error: cannot add string and integer

 

Output:

TypeError: can only concatenate str (not "int") to str

 

Correct Way (Explicit Conversion):

x = "10"

y = 5

print(int(x) + y)   # ✅ Converts string to int

Output:

15

 

Key Points:

  • Python does not perform implicit conversions between unrelated types (e.g., str ↔ int).
  • You must use type casting functions like int(), float(), str() when needed.

 

Comparison Table

Feature

Dynamic Typing

Strong Typing

Definition

Type of variable determined at runtime

Type safety enforced strictly

Example

x = 10; x = "Hello"

"10" + 5 → Error

Type Declaration

Not required

Not allowed to mix types implicitly

Type Conversion

Automatic detection

Must be explicit

Nature

Flexible

Safe and strict

Control Flow Statements in Python

Control flow statements determine the order in which statements are executed in a program.
They allow the program to make decisions, repeat tasks, and control execution flow.

The if Statement

Definition:
The if statement executes a block of code only if a given condition is true.

 

Syntax:

if condition:

    statement(s)

 

Example:

x = 10

if x > 5:

    print("x is greater than 5")

Output:

x is greater than 5

The if–else Statement

Definition:


Used when there are two possible paths — one when the condition is true, and another when it’s false.

 

 Syntax:

if condition:

    statement(s)

else:

    statement(s)

 

Example:

x = 3

if x % 2 == 0:

    print("Even number")

else:

    print("Odd number")

Output:

Odd number

The if…elif…else Statement

Definition:
Used for multiple conditional checks.

 

Syntax:

if condition1:

    statement(s)

elif condition2:

    statement(s)

else:

    statement(s)

 

Example:

marks = 85

if marks >= 90:

    print("Grade A")

elif marks >= 75:

    print("Grade B")

else:

    print("Grade C")

 

Output:

Grade B

Nested if Statement

Definition:
An if statement inside another if statement.

Example:

x = 15

if x > 10:

    if x < 20:

        print("x is between 10 and 20")

 

Output:

x is between 10 and 20

 

Note: Indentation is crucial to show hierarchy.

The while Loop

Definition:
Executes a block of code repeatedly while the condition is true.

Syntax:

while condition:

    statement(s)

 

Example:

i = 1

while i <= 5:

    print(i)

    i += 1

 

Output:

1

2

3

4

5

 

Be careful: Infinite loop occurs if the condition never becomes false.

The for Loop

Definition:
Used to iterate over a sequence (like list, tuple, string, or range).

Syntax:

for variable in sequence:

    statement(s)

 

Example:

for i in range(1, 6):

    print(i)

 

Output:

1

2

3

4

5

Note: range(start, stop) generates numbers from start to stop–1.

 

The continue Statement

 

Definition:
Skips the current iteration and continues with the next loop iteration.

 

Example:

for i in range(1, 6):

    if i == 3:

        continue

    print(i)

 

Output:

1

2

4

5

Here, when i == 3, the loop skips printing and continues.

 

The break Statement

 

Definition:
Used to terminate the loop immediately when a condition is met.

 

Example:

for i in range(1, 6):

    if i == 4:

        break

    print(i)

Output:

1

2

3

When i == 4, the loop stops executing further.

 

Statement

Description

Example

if

Executes block if condition is true

if x>0:

if–else

Executes one block if true, another if false

if x>0: else:

if–elif–else

Multiple conditions

if x>0 elif x==0 else:

Nested if

if inside if

if a>0: if b>0:

while loop

Repeats while condition true

while x<5:

for loop

Iterates over sequence

for i in range(5):

continue

Skips to next iteration

continue

break

Exits the loop

break

 

Catching Exceptions Using try and except Statement in Python

Introduction to Exceptions

Definition:
An exception is an error that occurs during program execution.
When an exception occurs, the normal flow of the program is interrupted.

Examples of exceptions:

  • ZeroDivisionError – dividing by zero
  • ValueError – invalid value type
  • IndexError – index out of range
  • TypeError – invalid operation between data types

 

Example (Without Handling)

a = 10

b = 0

print(a / b)

print("End of program")

 

Output:

ZeroDivisionError: division by zero

 

The program stops execution after the error.
To prevent this, we use exception handling with try and except.

 

The try and except Statement

Definition:
Used to catch and handle exceptions gracefully, so that the program doesn’t crash.

 Syntax:

try:

    # Code that may cause an exception

except:

    # Code to handle the exception

 

Example 1: Basic try–except

try:

    a = 10

    b = 0

    print(a / b)

except:

    print("Error! Division by zero is not allowed.")

 

print("Program continues...")

 

Output:

Error! Division by zero is not allowed.

Program continues...

✅ The program continues to run even after the error.

 

Catching Specific Exceptions

You can handle specific types of errors separately.

 

Syntax:

try:

    # risky code

except ZeroDivisionError:

    # handle divide by zero

except ValueError:

    # handle invalid value

 

Example 2:

try:

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

    print(10 / num)

except ZeroDivisionError:

    print("You cannot divide by zero.")

except ValueError:

    print("Please enter a valid integer.")

 

Output 1:

Enter a number: 0

You cannot divide by zero.

 

Output 2:

Enter a number: abc

Please enter a valid integer.

 

Using else with try–except

 

Definition:
The else block executes only when no exception occurs.

 

Example:

try:

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

    print("Reciprocal:", 1 / num)

except ZeroDivisionError:

    print("Cannot divide by zero.")

else:

    print("No exception occurred.")

 

Output:

Enter a number: 2

Reciprocal: 0.5

No exception occurred.

Using finally Block

Definition:
The finally block runs no matter what happens — whether there’s an error or not.
Useful for clean-up actions (like closing files or releasing resources).

 

 

Example:

try:

    f = open("sample.txt", "r")

    data = f.read()

except FileNotFoundError:

    print("File not found!")

finally:

    print("Closing file (if opened).")

 

 

Output:

File not found!

Closing file (if opened).

 

Block

Description

Execution Time

try

Code that may cause an error

Always executed

except

Handles the exception

Only when error occurs

else

Executes if no exception occurs

When try succeeds

finally

Always executes

Whether error or not

 



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



*Week - I Programs*

1) Write a program to find the largest element among three Numbers

CODE:

Method 1: Using if-else statements

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

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

c = int(input("Enter third number: "))

 

if a >= b and a >= c:

    largest = a

elif b >= a and b >= c:

    largest = b

else:

    largest = c

 

print("The largest number is:", largest) 

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 2: Using max() function

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

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

c = int(input("Enter third number: "))

 

largest = max(a, b, c)

print("The largest number is:", largest)


 OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 3: Using Ternary operator

 

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

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

c = int(input("Enter third number: "))

 

largest = a if (a > b and a > c) else (b if b > c else c)

print("The largest number is:", largest)

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 4: Using sorted() function

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

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

c = int(input("Enter third number: "))

 

numbers = [a, b, c]

largest = sorted(numbers)[-1]

print("The largest number is:", largest)

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 5: Defining a function

def find_largest(a, b, c):

    if a >= b and a >= c:

        return a

    elif b >= a and b >= c:

        return b

    else:

        return c

 

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

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

c = int(input("Enter third number: "))

 

print("The largest number is:", find_largest(a, b, c))

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

2) Write a Program to display all prime numbers within an interval

CODE:

Method 1: Basic Loop

 

start = int(input("Enter the start of interval: "))

end = int(input("Enter the end of interval: "))

 

print(f"Prime numbers between {start} and {end} are:")

 

for num in range(start, end + 1):

    if num > 1:

        for i in range(2, num):

            if num % i == 0:

                break

        else:

            print(num, end=" ")

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

 

Method 2: Optimized Prime Check

 

import math

 

start = int(input("Enter the start of interval: "))

end = int(input("Enter the end of interval: "))

 

print(f"Prime numbers between {start} and {end} are:")

 

for num in range(start, end + 1):

    if num > 1:

        is_prime = True

        for i in range(2, int(math.sqrt(num)) + 1):

            if num % i == 0:

                is_prime = False

                break

        if is_prime:

            print(num, end=" ")

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

 

Method 3: Using a function

def is_prime(n):

    if n <= 1:

        return False

    for i in range(2, int(n**0.5) + 1):

        if n % i == 0:

            return False

    return True

 

start = int(input("Enter the start of interval: "))

end = int(input("Enter the end of interval: "))

 

print(f"Prime numbers between {start} and {end} are:")

 

for num in range(start, end + 1):

    if is_prime(num):

        print(num, end=" ")


OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

3) Write a program to swap two numbers without using a temporary variable.

 

CODE:

 

Method 1: Addition and Subtraction

 

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

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

 

a = a + b

b = a - b

a = a - b

 

print("After swapping: a =", a, ", b =", b)

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 2: Multiplication and Division

 

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

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

 

a = a * b

b = a / b

a = a / b

 

print("After swapping: a =", int(a), ", b =", int(b))

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 3: Pythonic way (Tuple unpacking)

 

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

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

 

a, b = b, a

 

print("After swapping: a =", a, ", b =", b)

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

 4) Demonstrate the following Operators in Python with suitable examples.

i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators iv)

Logical Operators v) Bit wise Operators vi) Ternary Operator vii) Membership

Operators viii) Identity Operators

 

CODE:

Demonstration of Different Operators in Python

 

1. Arithmetic Operators

a = 15

b = 4

print("Arithmetic Operators:")

print("a + b =", a + b)   # Addition

print("a - b =", a - b)   # Subtraction

print("a * b =", a * b)   # Multiplication

print("a / b =", a / b)   # Division

print("a % b =", a % b)   # Modulus

print("a ** b =", a ** b) # Exponentiation

print("a // b =", a // b) # Floor Division

print()

 

2. Relational (Comparison) Operators

print("Relational Operators:")

print("a > b is", a > b)

print("a < b is", a < b)

print("a == b is", a == b)

print("a != b is", a != b)

print("a >= b is", a >= b)

print("a <= b is", a <= b)

print()

 

3. Assignment Operators

print("Assignment Operators:")

x = 10

print("x =", x)

x += 5   # x = x + 5

print("x += 5 ", x)

x -= 3   # x = x - 3

print("x -= 3 ", x)

x *= 2   # x = x * 2

print("x *= 2 ", x)

x /= 4   # x = x / 4

print("x /= 4 ", x)

x %= 5   # x = x % 5

print("x %= 5 ", x)

print()

 

4. Logical Operators

p = True

q = False

print("Logical Operators:")

print("p and q is", p and q)

print("p or q is", p or q)

print("not p is", not p)

print()

 

5. Bitwise Operators

m = 6   # (110 in binary)

n = 3   # (011 in binary)

print("Bitwise Operators:")

print("m & n =", m & n)   # AND

print("m | n =", m | n)   # OR

print("m ^ n =", m ^ n)   # XOR

print("~m =", ~m)         # NOT

print("m << 1 =", m << 1) # Left shift

print("m >> 1 =", m >> 1) # Right shift

print()

 

6. Ternary Operator

num = 10

result = "Even" if num % 2 == 0 else "Odd"

print("Ternary Operator:")

print("Number is", result)

print()

 

7. Membership Operators

list1 = [1, 2, 3, 4, 5]

print("Membership Operators:")

print("3 in list1 ", 3 in list1)

print("7 not in list1 ", 7 not in list1)

print()

 

8. Identity Operators

x = [1, 2, 3]

y = [1, 2, 3]

z = x

print("Identity Operators:")

print("x is y ", x is y)         # False (different objects with same content)

print("x is z ", x is z)         # True  (same object)

print("x is not y ", x is not y) # True

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 


5) Write a program to add and multiply complex numbers

 

CODE:

 Method 1: Using complex type

a = complex(2, 3)   # 2 + 3i

b = complex(4, 5)   # 4 + 5i

 

# Addition and Multiplication

print("Addition:", a + b)

print("Multiplication:", a * b)

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 2: Taking input as complex numbers

a = complex(input("Enter first complex number (e.g., 2+3j): "))

b = complex(input("Enter second complex number (e.g., 4+5j): "))

 

print("Addition:", a + b)

print("Multiplication:", a * b)

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

6) Write a program to print multiplication table of a given number.

 

CODE:

 Method 1: For loop

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

print(f"Multiplication Table of {num}")

 

for i in range(1, 11):

    print(f"{num} x {i} = {num * i}")

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 2: While loop

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

print(f"Multiplication Table of {num}")

 

i = 1

while i <= 10:

    print(f"{num} x {i} = {num * i}")

    i += 1

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

Method 3: Function

def multiplication_table(n):

    for i in range(1, 11):

        print(f"{n} x {i} = {n * i}")

 

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

print(f"Multiplication Table of {num}")

multiplication_table(num)


OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 

 

Method 4: List Comprehension

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

table = [f"{num} x {i} = {num * i}" for i in range(1, 11)]

print("\n".join(table))

 

OUTPUT: ----------------------------- Try on your own👏----------------------------- 

 


No comments:

Post a Comment

PP UNIT IV & WEEK IV PROGRAMS

  UNIT-IV Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write Data, Reading and Writing Binary Files, Pi...