Introduction to Python – Chapter 3 | O Level M3-R5 | Boosting Skills

Introduction to Python – NIELIT O Level (M3-R5)

इस chapter में हम Python language की मूल बातें सीखेंगे जैसे — Python Interpreter, Comments, Literals, Constants, Built-in Data Types, Numbers, Strings, Input/Output और कुछ Simple Programs

👉 Swipe to see more
1️⃣ Python Introduction

🐍 What is Python?

Python एक high-level, interpreted, object-oriented programming language है, जिसे Guido van Rossum ने 1989 में बनाया और 1991 में officially release किया गया। इसका नाम “Python” टीवी शो “Monty Python’s Flying Circus” से लिया गया है — इसलिए इसका सांप से कोई संबंध नहीं है 🐍🙂।

💡 Key Features of Python:

  • Simple and Easy to Learn
  • Open Source and Free
  • Interpreted Language (no need of compilation)
  • Platform Independent (runs on Windows, macOS, Linux)
  • Extensive Libraries (math, data, web, AI, ML)
  • Object-Oriented and Structured
  • Supports GUI, Web, Database, and Scripting

🧠 Why Learn Python?

Python आज के समय की सबसे popular programming language है क्योंकि यह:

  • Artificial Intelligence (AI) और Machine Learning में उपयोग होती है।
  • Data Science और Data Visualization में powerful tool है।
  • Automation, Web Development, Cyber Security और Game Development में widely used है।

📦 Applications of Python

  • 🌐 Web Development → Django, Flask
  • 🤖 Machine Learning / AI → TensorFlow, Scikit-learn
  • 📊 Data Science → Pandas, NumPy, Matplotlib
  • 🔧 Automation / Scripting → OS, Selenium
  • 🎮 Game Development → Pygame

⚙️ Simple Python Example

चलिए एक simple “Hello, World!” program से शुरू करते हैं:


# My first Python program
print("Hello, World!")
  

Output:
Hello, World!

🔹 Example 2: Basic Arithmetic


a = 10
b = 5
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
  

Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

📘 Python Execution Process

Python एक interpreted language है — इसका मतलब यह है कि कोड को line-by-line execute किया जाता है।

  1. Program written in .py file
  2. Python interpreter converts code → Bytecode
  3. Python Virtual Machine (PVM) executes the bytecode

🧾 Advantages of Python

  • Readable and simple syntax
  • Large community and vast libraries
  • Portable and embeddable
  • Integration with other languages (C, C++)

⚠️ Disadvantages of Python

  • Slower speed (interpreted nature)
  • Not ideal for mobile apps
  • High memory usage

💬 Interview FAQs

  • Q: Who developed Python?
    A: Guido van Rossum in 1989.
  • Q: What type of language is Python?
    A: High-level, interpreted, object-oriented.
  • Q: What are .py files?
    A: Python source code files with “.py” extension.
  • Q: Is Python case sensitive?
    A: Yes, Python differentiates between uppercase and lowercase.
  • Q: What are some popular IDEs for Python?
    A: PyCharm, VS Code, Jupyter, IDLE.

🧠 Summary

  • Python is simple, powerful, and versatile.
  • It supports multiple domains like AI, Data Science, and Web.
  • Easy syntax and huge library support make it beginner-friendly.
  • Created by Guido van Rossum, first released in 1991.
2️⃣ Technical Strength of Python

⚙️ Introduction

Python एक ऐसी programming language है जो अपनी technical power, flexibility और simplicity की वजह से आज दुनिया की सबसे पसंदीदा language बन चुकी है। यह हर क्षेत्र में काम आती है — चाहे वह AI, ML, Web Development, Data Science, Automation या Cybersecurity क्यों न हो।

💡 Major Technical Strengths of Python

1️⃣ Interpreted Language

Python एक interpreted language है, यानी कोड को line-by-line execute किया जाता है। इससे debugging आसान होती है और errors जल्दी पकड़ में आते हैं।


print("Step 1")
print("Step 2")
print("Step 3")
  

Output:
Step 1
Step 2
Step 3

2️⃣ Dynamically Typed

Python में variable का type declare नहीं करना पड़ता। Interpreter खुद detect कर लेता है कि कौन सा data type assign हुआ है।


x = 10       # integer
y = "Hello"  # string
z = 3.14     # float
print(type(x), type(y), type(z))
  

Output:
<class 'int'> <class 'str'> <class 'float'>

3️⃣ Platform Independent

Python को किसी भी operating system पर run किया जा सकता है — जैसे Windows, macOS, Linux, या Android. आप एक ही कोड को अलग-अलग machines पर execute कर सकते हैं।

4️⃣ Huge Standard Library

Python की library बहुत बड़ी है — जिसमें pre-written modules होते हैं। ये modules हमें बार-बार code लिखने से बचाते हैं।


import math
print(math.sqrt(25))
print(math.factorial(5))
  

Output:
5.0
120

5️⃣ Object-Oriented & Procedural

Python दोनों styles को support करती है — आप चाहें तो functions-based (procedural) या classes-based (OOP) तरीके से code लिख सकते हैं।


# Procedural
def greet():
    print("Hello Python!")
greet()

# Object-Oriented
class Hello:
    def msg(self):
        print("Welcome to OOP in Python")

obj = Hello()
obj.msg()
  

Output:
Hello Python!
Welcome to OOP in Python

6️⃣ Extensible & Embeddable

Python को C/C++ जैसी languages के साथ integrate किया जा सकता है। इससे performance बढ़ जाती है और system-level programming आसान हो जाती है।

7️⃣ Memory Management

Python में automatic garbage collection system है जो unused memory को खुद free करता है। इससे programmer को memory manage करने की जरूरत नहीं होती।

8️⃣ Large Community Support

Python का सबसे बड़ा strength इसका active global community है। हर problem का solution StackOverflow, GitHub या official documentation पर आसानी से मिल जाता है।

🧩 Practical Demonstration

चलो कुछ practical examples से Python की ताकत समझते हैं:

💻 Example 1: Simple Loop (Readable Syntax)


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

Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

💻 Example 2: File Handling (in one line!)


with open("demo.txt", "w") as f:
    f.write("Python is powerful!")
  

Output:
A file named demo.txt is created containing → “Python is powerful!”

💻 Example 3: Web Request in 2 lines


import requests
r = requests.get("https://www.python.org")
print(r.status_code)
  

Output:
200 (Success)

📘 Comparison with Other Languages

FeaturePythonC/C++Java
TypingDynamicStaticStatic
CompilationInterpretedCompiledCompiled
SyntaxSimple, ReadableComplexVerbose
Memory MgmtAutomatic (GC)ManualAutomatic (GC)
SpeedModerateFastModerate

💬 Interview FAQs

  • Q: Why is Python slow compared to C++?
    A: Because Python is interpreted, not compiled directly to machine code.
  • Q: What makes Python portable?
    A: Python code runs on any OS without modification.
  • Q: How does Python manage memory?
    A: Through built-in garbage collector and reference counting.
  • Q: Can Python integrate with other languages?
    A: Yes, via libraries like Cython, Jython, and ctypes.

🧠 Summary

  • Python is interpreted, dynamic, and object-oriented.
  • It has powerful libraries and cross-platform support.
  • Automatic memory management makes it efficient.
  • Readable syntax and community support make it ideal for beginners.
3️⃣ Python Interpreter and Program Execution

⚙️ What is a Python Interpreter?

जब हम Python program लिखते हैं, तो उसे run करने के लिए एक Interpreter की आवश्यकता होती है। Python Interpreter हमारे कोड को line-by-line पढ़कर उसे machine-understandable instructions में बदलता है और execute करता है।

💡 Simple Meaning:

  • 👉 Compiler पूरे program को एक साथ translate करता है।
  • 👉 Interpreter program को line by line execute करता है।

🧠 How Python Executes a Program (Step-by-Step)

  1. Step 1: Write code in a .py file.
  2. Step 2: Interpreter reads the source code.
  3. Step 3: Code is converted into Byte Code.
  4. Step 4: Byte code is sent to the Python Virtual Machine (PVM).
  5. Step 5: PVM executes bytecode line-by-line and produces output.

🔸 Python uses this process to maintain portability — यानी वही bytecode किसी भी OS पर चल सकता है (Windows, Linux, macOS)।

🧩 Diagram (Textual Representation)

  Source Code (.py)
         ↓
  Python Compiler → Byte Code (.pyc)
         ↓
  Python Virtual Machine (PVM)
         ↓
        Output
  

💻 Example 1: Simple Program Execution


# hello.py
print("Welcome to Python Execution Flow!")
a = 5
b = 3
print("Sum =", a + b)
  

Output:
Welcome to Python Execution Flow!
Sum = 8

⚡ Internal Steps (behind this simple code):

  1. Python reads the hello.py file.
  2. Converts it to bytecode (machine-independent form).
  3. Bytecode executed by the Python Virtual Machine (PVM).
  4. Output printed on screen.

💻 Example 2: Viewing Bytecode

Python internally converts code into bytecode before running. You can view this using the dis (disassembler) module.


import dis

def add(x, y):
    return x + y

print(dis.dis(add))
  

Output:
It displays low-level bytecode instructions that Python executes internally.

📦 Components of Python Execution System

  • 1️⃣ Parser: Checks syntax errors.
  • 2️⃣ Compiler: Converts code → bytecode.
  • 3️⃣ Interpreter (PVM): Executes bytecode line-by-line.

📘 Types of Python Interpreters

InterpreterDescription
CPythonDefault and most used (written in C language).
JythonRuns Python code on Java Virtual Machine (JVM).
IronPythonUsed for .NET framework integration.
PyPyFaster Python implementation using JIT compiler.

🧮 Example 3: Python Interactive Mode

Python shell में आप direct code लिखकर result तुरंत देख सकते हैं।


>>> 5 + 3
8
>>> print("Hello Python")
Hello Python
  

यह mode beginners के लिए perfect है क्योंकि इसमें immediate feedback मिलता है।

🧾 Example 4: Script Mode

आप Python को .py file में save करके command line से run कर सकते हैं।

  C:\> python myprogram.py
  

इस तरीके से बड़े programs बनाए और execute किए जाते हैं।

🔍 Example 5: Error Handling During Execution

Interpreter syntax error या runtime error को तुरंत दिखा देता है।


a = 10
b = 0
print(a / b)  # division by zero
  

Output:
ZeroDivisionError: division by zero

💬 Interview FAQs

  • Q: What is Python Interpreter?
    A: It executes Python code line by line after converting it to bytecode.
  • Q: What is Bytecode in Python?
    A: It is an intermediate code generated by Python compiler before execution by PVM.
  • Q: What is the role of PVM?
    A: Python Virtual Machine executes bytecode and manages runtime environment.
  • Q: Difference between Interactive and Script mode?
    A: Interactive → executes line-by-line in shell; Script mode → executes saved file (.py).
  • Q: Can Python run without compilation?
    A: No. It compiles internally to bytecode automatically before execution.

🧠 Summary

  • Python Interpreter executes code line-by-line.
  • Source code → Bytecode → Executed by PVM.
  • Errors handled at runtime or compile-time automatically.
  • Interactive & Script modes make Python flexible.
  • Default implementation is CPython, written in C language.
4️⃣ Using Comments in Python

🗒️ Introduction

जब हम Python program लिखते हैं, तो अक्सर हमें code में कुछ extra जानकारी या notes लिखने की जरूरत होती है ताकि बाद में खुद या कोई और व्यक्ति उसे आसानी से समझ सके। ऐसे notes को comments कहा जाता है। ये program के execution को affect नहीं करते — केवल पढ़ने के लिए होते हैं।

💡 Why Comments are Important?

  • 👉 Code को readable बनाते हैं।
  • 👉 किसी logic या formula को explain करने में मदद करते हैं।
  • 👉 Debugging और maintenance आसान बनाते हैं।
  • 👉 Documentation में useful होते हैं।

📘 Types of Comments in Python

  • 1️⃣ Single-line Comment
  • 2️⃣ Multi-line Comment
  • 3️⃣ Docstring (Documentation String)

🟢 1️⃣ Single-line Comment

Single-line comment # symbol से शुरू होता है। Interpreter इसे ignore कर देता है।


# This is a single-line comment
print("Python is fun!")  # Printing a message
  

Output:
Python is fun!

🟡 2️⃣ Multi-line Comments

Multi-line comments लिखने के लिए आप कई lines में # लगा सकते हैं, या फिर triple quotes ''' ''' या """ """ का उपयोग कर सकते हैं।


# This program demonstrates
# the use of multi-line comments
# and prints a greeting message

print("Hello, Python Learner!")
  

Output:
Hello, Python Learner!

Alternative using triple quotes:


'''
This is a multi-line comment
written using triple single quotes
'''
print("Triple-quoted comment example")

"""
Another style using triple double quotes
This can also be used for documentation
"""
print("Docstring-style multi-line comment")
  

Output:
Triple-quoted comment example
Docstring-style multi-line comment

🧾 3️⃣ Docstrings (Documentation Strings)

Docstring एक special type का multi-line comment होता है जिसका उपयोग किसी function, class या module के बारे में documentation लिखने के लिए किया जाता है। इसे triple quotes में लिखा जाता है और यह help() function से access किया जा सकता है।


def add(a, b):
    """This function returns the sum of two numbers."""
    return a + b

print(add(10, 5))
print(add.__doc__)  # accessing docstring
  

Output:
15
This function returns the sum of two numbers.

🧩 Practical Examples

💻 Example 1: Commenting Steps in Program


# Step 1: Take input from user
a = int(input("Enter first number: "))

# Step 2: Take another input
b = int(input("Enter second number: "))

# Step 3: Add both numbers
sum = a + b

# Step 4: Display result
print("Sum =", sum)
  

Output:
Enter first number: 5
Enter second number: 7
Sum = 12

💻 Example 2: Multi-line Documentation of Function


def factorial(n):
    """
    Function to calculate factorial of a number.
    Uses recursion.
    Example: factorial(5) = 120
    """
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))
  

Output:
120

💻 Example 3: Using Comments to Disable Code


print("This will run")
# print("This line is commented out and won't execute")
  

Output:
This will run

💬 Interview FAQs

  • Q: What is the use of comments in Python?
    A: Comments help make code more readable and explain its logic.
  • Q: How can you write multi-line comments?
    A: By using multiple # symbols or triple quotes ''' ... '''.
  • Q: What is a docstring?
    A: A special string written in triple quotes used to document a function or class.
  • Q: How to access a function’s docstring?
    A: Using function_name.__doc__ or help(function_name).
  • Q: Do comments increase program execution time?
    A: No, the interpreter ignores comments completely.
5️⃣ Literals and Constants in Python

📘 Introduction

Python में literals और constants ऐसे values होते हैं जिन्हें हम directly program में लिखते हैं और जो change नहीं होते। ये program की fixed data values को represent करते हैं। उदाहरण के लिए: 10, "Hello", 3.14, True आदि।

💡 What is a Literal?

Literal का मतलब होता है — “एक fixed value जिसे directly code में लिखा गया है।” ये किसी variable में assign की जा सकती है या expression में use हो सकती है।


x = 10        # integer literal
y = 3.14      # float literal
name = "Amit" # string literal
is_ok = True  # boolean literal
  

Output:
These literals are directly stored in memory and used during execution.

🔹 Types of Literals in Python

  • 1️⃣ Numeric Literals
  • 2️⃣ String Literals
  • 3️⃣ Boolean Literals
  • 4️⃣ Special Literal (None)
  • 5️⃣ Collection Literals (List, Tuple, Dict, Set)

🧮 1️⃣ Numeric Literals

Numeric literals represent numbers — जैसे integers, floats, या complex numbers।


a = 10          # Integer literal
b = 3.14        # Float literal
c = 2 + 5j      # Complex literal

print("Integer:", a)
print("Float:", b)
print("Complex:", c)
print("Real part:", c.real)
print("Imaginary part:", c.imag)
  

Output:
Integer: 10
Float: 3.14
Complex: (2+5j)
Real part: 2.0
Imaginary part: 5.0

📝 2️⃣ String Literals

Strings वो literals हैं जो characters का collection होते हैं और single (‘ ’) या double (“ ”) quotes में लिखे जाते हैं।


name = 'Amit'
greet = "Hello, World!"
multiline = """This is
a multi-line
string literal."""

print(name)
print(greet)
print(multiline)
  

Output:
Amit
Hello, World!
This is
a multi-line
string literal.

🔘 3️⃣ Boolean Literals

Boolean literals सिर्फ दो values ले सकते हैं: True या False। ये logical expressions में इस्तेमाल होते हैं।


x = True
y = False
print(x and y)
print(x or y)
print(not x)
  

Output:
False
True
False

🧩 4️⃣ Special Literal: None

None एक special literal है जो represent करता है कि variable में कोई value नहीं है। यह “null” या “empty” concept जैसा है।


data = None
print("Value:", data)
print("Type:", type(data))
  

Output:
Value: None
Type: <class 'NoneType'>

📦 5️⃣ Collection Literals

Python में list, tuple, dictionary, और set को भी literals के रूप में define किया जा सकता है।


# List literal
fruits = ["apple", "banana", "cherry"]

# Tuple literal
colors = ("red", "green", "blue")

# Dictionary literal
student = {"name": "Amit", "age": 20}

# Set literal
numbers = {1, 2, 3, 4}

print(fruits)
print(colors)
print(student)
print(numbers)
  

Output:
['apple', 'banana', 'cherry']
('red', 'green', 'blue')
{'name': 'Amit', 'age': 20}
{1, 2, 3, 4}

🔒 Constants in Python

Python में constants का मतलब है ऐसी values जिन्हें program के दौरान बदला नहीं जाता। Python में कोई “constant keyword” नहीं है — लेकिन by convention, हम constant variable को uppercase letters में लिखते हैं।


PI = 3.14159
GRAVITY = 9.8
APP_NAME = "MyPythonApp"

print("PI =", PI)
print("GRAVITY =", GRAVITY)
print("APP_NAME =", APP_NAME)
  

Output:
PI = 3.14159
GRAVITY = 9.8
APP_NAME = MyPythonApp

💡 Note:

  • Python constants change नहीं होने चाहिए, लेकिन technically बदले जा सकते हैं।
  • Developers convention के हिसाब से उन्हें modify नहीं करते।

🧮 Practical Examples

💻 Example 1: Using literals in an expression


result = 5 * 10 + 3.5
print("Result =", result)
  

Output:
Result = 53.5

💻 Example 2: Checking data types of literals


x = 100
y = 12.5
z = True
s = "Python"
print(type(x), type(y), type(z), type(s))
  

Output:
<class 'int'> <class 'float'> <class 'bool'> <class 'str'>

💻 Example 3: Using constants for clarity


PI = 3.14159
radius = 5
area = PI * (radius ** 2)
print("Area of Circle =", area)
  

Output:
Area of Circle = 78.53975

💬 Interview FAQs

  • Q: What are literals in Python?
    A: Fixed data values written directly in the program, e.g., 10, "Hello", True.
  • Q: How are constants defined in Python?
    A: By convention, using uppercase names like PI = 3.14.
  • Q: What is the difference between literal and variable?
    A: Literal is the actual value; variable is a name that stores it.
  • Q: What is a special literal?
    A: None — it represents the absence of value.
  • Q: Can constants be changed in Python?
    A: Technically yes, but by coding standards, they should not be modified.
6️⃣ Python’s Built-in Data Types

📘 Introduction

Python में हर data को किसी न किसी Data Type से represent किया जाता है। Data type यह बताता है कि किसी variable में किस प्रकार का data store हुआ है — जैसे number, text, list, tuple, set या dictionary आदि।

Python में data type automatically assign होता है (Dynamic Typing)। यानी आपको explicitly type declare नहीं करना पड़ता।


x = 10          # int
y = 3.14        # float
name = "Amit"   # string
is_ok = True    # bool
print(type(x), type(y), type(name), type(is_ok))
  

Output:
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>

🔹 Major Built-in Data Types in Python

CategoryData TypeDescription
Numericint, float, complexNumeric values
Sequencestr, list, tuple, rangeOrdered collection of items
MappingdictKey-value pairs
Setset, frozensetUnordered collection of unique items
BooleanboolTrue or False values
Binarybytes, bytearray, memoryviewBinary data

🔢 1️⃣ Numeric Data Types

Numeric data types में तीन प्रकार आते हैं — integer, float, और complex।


a = 10        # int
b = 3.14      # float
c = 2 + 5j    # complex number

print("a =", a, "| Type:", type(a))
print("b =", b, "| Type:", type(b))
print("c =", c, "| Type:", type(c))
  

Output:
a = 10 | Type: <class 'int'>
b = 3.14 | Type: <class 'float'>
c = (2+5j) | Type: <class 'complex'>

🔤 2️⃣ String Data Type

Strings characters का collection होते हैं जिन्हें single (' ') या double (" ") quotes में लिखा जाता है। Strings immutable होते हैं (यानि change नहीं किए जा सकते)।


s = "Python"
print(s)
print("First Character:", s[0])
print("Slice:", s[1:4])
print("Reversed:", s[::-1])
  

Output:
Python
First Character: P
Slice: yth
Reversed: nohtyP

📋 3️⃣ List Data Type

List एक ordered collection होती है जो mutable होती है (यानि modify की जा सकती है)। इसमें अलग-अलग data types के elements store किए जा सकते हैं।


fruits = ["apple", "banana", "cherry"]
print(fruits)
fruits.append("mango")
print("Updated list:", fruits)
print("First fruit:", fruits[0])
  

Output:
['apple', 'banana', 'cherry']
Updated list: ['apple', 'banana', 'cherry', 'mango']
First fruit: apple

🔗 4️⃣ Tuple Data Type

Tuple भी list की तरह ordered collection होती है, लेकिन यह immutable होती है। यानी tuple के elements बदले नहीं जा सकते।


colors = ("red", "green", "blue")
print(colors)
print("Second color:", colors[1])
  

Output:
('red', 'green', 'blue')
Second color: green

📦 5️⃣ Dictionary (Mapping Type)

Dictionary key-value pairs के रूप में data store करती है। Keys unique होते हैं और values किसी भी data type की हो सकती हैं।


student = {"name": "Amit", "age": 20, "course": "Python"}
print(student)
print("Name:", student["name"])
student["age"] = 21
print("Updated dict:", student)
  

Output:
{'name': 'Amit', 'age': 20, 'course': 'Python'}
Name: Amit
Updated dict: {'name': 'Amit', 'age': 21, 'course': 'Python'}

🔘 6️⃣ Set Data Type

Set एक unordered collection होता है जिसमें duplicate values नहीं होतीं। यह mathematical set operations जैसे union, intersection, difference को support करता है।


numbers = {1, 2, 3, 4, 4, 2}
print(numbers)
numbers.add(5)
print("After adding:", numbers)
  

Output:
{1, 2, 3, 4}
After adding: {1, 2, 3, 4, 5}

🔹 7️⃣ Boolean Type

Boolean type logical values True और False को represent करता है। ये comparison और logical operations में उपयोग होते हैं।


a = 10
b = 5
print(a > b)
print(a == b)
print(bool(0), bool(1))
  

Output:
True
False
False True

💾 8️⃣ Binary Data Types

Binary types raw binary data handle करते हैं — जैसे files, images आदि में। इनमे bytes, bytearray, और memoryview आते हैं।


b = bytes([65, 66, 67])
print(b)
print(b.decode())  # converting to string

ba = bytearray([68, 69, 70])
ba[0] = 71
print(ba)
  

Output:
b'ABC'
ABC
bytearray(b'GEF')

🧩 Example: Using Multiple Data Types Together


data = {
    "id": 101,
    "name": "Amit",
    "marks": [85, 90, 92],
    "is_pass": True,
    "grades": ("A", "B+"),
    "subjects": {"math", "science"}
}

print(data)
  

Output:
{'id': 101, 'name': 'Amit', 'marks': [85, 90, 92], 'is_pass': True, 'grades': ('A', 'B+'), 'subjects': {'science', 'math'}}

💬 Interview FAQs

  • Q: What are the main categories of Python data types?
    A: Numeric, Sequence, Mapping, Set, Boolean, and Binary types.
  • Q: What is the difference between list and tuple?
    A: List is mutable; tuple is immutable.
  • Q: Can dictionary keys be mutable?
    A: No, dictionary keys must be immutable (e.g., strings, numbers, tuples).
  • Q: What is the difference between bytes and bytearray?
    A: Bytes are immutable, bytearray is mutable.
  • Q: How to check a variable’s data type?
    A: Use the built-in type() function.
7️⃣ Numbers in Python

📘 Introduction

Python में Numbers एक fundamental data type हैं। ये mathematical operations (addition, subtraction, multiplication, division, etc.) करने के लिए इस्तेमाल होते हैं। Python numbers को internally अलग-अलग categories में classify करता है।

🔹 Types of Numbers in Python

  • 1️⃣ Integer (int) – Whole numbers, बिना decimal के (जैसे 10, -5, 1000)
  • 2️⃣ Float (float) – Decimal numbers (जैसे 3.14, -7.5)
  • 3️⃣ Complex (complex) – Numbers with real and imaginary parts (जैसे 2 + 3j)

💡 Example 1: Different Numeric Types


# Integer
x = 10
print("Integer:", x, "| Type:", type(x))

# Float
y = 3.14
print("Float:", y, "| Type:", type(y))

# Complex
z = 2 + 5j
print("Complex:", z, "| Type:", type(z))
  

Output:
Integer: 10 | Type: <class 'int'>
Float: 3.14 | Type: <class 'float'>
Complex: (2+5j) | Type: <class 'complex'>

🧮 Example 2: Arithmetic Operations

Python numbers पर arithmetic operations को support करता है।


a = 15
b = 4

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
  

Output:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625

🧩 Example 3: Type Conversion (Type Casting)

Python में numbers के बीच conversion आसानी से किया जा सकता है।


a = 10       # int
b = 3.5      # float
c = 2 + 4j   # complex

# Type conversions
print(float(a))   # int → float
print(int(b))     # float → int
print(complex(a)) # int → complex
  

Output:
10.0
3
(10+0j)

🧠 Example 4: Checking Numeric Type

आप isinstance() function से check कर सकते हैं कि variable कौन से type का है।


a = 7
b = 4.2
c = 3 + 2j

print(isinstance(a, int))
print(isinstance(b, float))
print(isinstance(c, complex))
  

Output:
True
True
True

💻 Example 5: Using math Module

Python का math module कई built-in mathematical functions देता है। इन्हें import करके आप trigonometric, logarithmic, और power functions use कर सकते हैं।


import math

print("Square root:", math.sqrt(16))
print("Power:", math.pow(2, 3))
print("Floor:", math.floor(3.8))
print("Ceil:", math.ceil(3.8))
print("Value of pi:", math.pi)
print("Value of e:", math.e)
  

Output:
Square root: 4.0
Power: 8.0
Floor: 3
Ceil: 4
Value of pi: 3.141592653589793
Value of e: 2.718281828459045

🧾 Example 6: Random Number Generation

Python का random module random numbers generate करने में उपयोग होता है।


import random

print("Random number (1 to 10):", random.randint(1, 10))
print("Random float:", random.random())
print("Random choice from list:", random.choice([10, 20, 30, 40]))
  

Output:
Random number (1 to 10): 7
Random float: 0.5638292
Random choice from list: 30

🧩 Example 7: Complex Number Operations

Complex numbers में real और imaginary parts को access किया जा सकता है।


c1 = 2 + 3j
c2 = 1 + 2j

result = c1 + c2
print("Addition:", result)
print("Real Part:", result.real)
print("Imaginary Part:", result.imag)
  

Output:
Addition: (3+5j)
Real Part: 3.0
Imaginary Part: 5.0

📦 Example 8: Decimal and Fraction Module

Floating point errors से बचने के लिए Python में decimal और fractions modules होते हैं।


from decimal import Decimal
from fractions import Fraction

x = Decimal('0.1') + Decimal('0.2')
print("Using Decimal:", x)

y = Fraction(1, 3) + Fraction(2, 3)
print("Using Fraction:", y)
  

Output:
Using Decimal: 0.3
Using Fraction: 1

💬 Interview FAQs

  • Q: What are the numeric types in Python?
    A: int, float, and complex.
  • Q: How is Python dynamically typed?
    A: Python automatically detects the data type of a variable at runtime.
  • Q: What is the difference between / and // in Python?
    A: / performs true division (float result), // performs floor division (integer result).
  • Q: What is the purpose of the math and random modules?
    A: math → mathematical functions; random → random number generation.
  • Q: How to represent complex numbers in Python?
    A: Using a + bj where ‘a’ is real part and ‘b’ is imaginary part.
8️⃣ Strings and Operations in Python

📘 Introduction

Python में Strings characters का collection होते हैं जिन्हें single quotes (‘ ’), double quotes (“ ”), या triple quotes (‘’’ ’’’ / “”” “””) में लिखा जाता है। ये text data को represent करने के लिए इस्तेमाल किए जाते हैं। उदाहरण के लिए – नाम, पता, संदेश आदि।


s1 = 'Hello'
s2 = "Python"
s3 = '''This is
a multi-line
string example'''
print(s1)
print(s2)
print(s3)
  

Output:
Hello
Python
This is
a multi-line
string example

💡 Characteristics of Strings

  • ✅ Strings are immutable (change नहीं किए जा सकते)।
  • ✅ Indexing और Slicing को support करते हैं।
  • ✅ Concatenation (जोड़ना) और Repetition (दोहराना) possible है।
  • ✅ Unicode-based — यानी सभी भाषाओं के अक्षर store कर सकते हैं।

🧩 Creating Strings


str1 = 'Welcome'
str2 = "to Python"
str3 = str1 + " " + str2  # Concatenation
print(str3)
  

Output:
Welcome to Python

🔢 Indexing and Slicing

Strings में हर character की एक index position होती है। Indexing [ ] brackets का उपयोग करके की जाती है।


text = "PYTHON"
print(text[0])    # First character
print(text[-1])   # Last character
print(text[1:4])  # Slice from index 1 to 3
print(text[::-1]) # Reverse string
  

Output:
P
N
YTH
NOHTYP

🧮 String Operations

OperationExampleResult
Concatenation'Hello' + 'World'HelloWorld
Repetition'Hi' * 3HiHiHi
Membership'H' in 'Hello'True
Lengthlen('Python')6
Iterationfor ch in 'Hi': print(ch)H
i

💻 Example: All String Operations


a = "Hello"
b = "World"

print(a + " " + b)   # Concatenation
print(a * 2)         # Repetition
print('H' in a)      # Membership
print(len(a))        # Length
for ch in a:
    print(ch, end=" ")
  

Output:
Hello World
HelloHello
True
5
H e l l o

🧰 String Methods

Python में कई built-in string methods होते हैं:

MethodUsageExample & Output
upper()Convert to uppercase'python'.upper() → PYTHON
lower()Convert to lowercase'HELLO'.lower() → hello
title()Capitalize each word'welcome to python'.title() → Welcome To Python
strip()Remove spaces' hi '.strip() → hi
replace()Replace text'I like Java'.replace('Java', 'Python') → I like Python
find()Find substring index'python'.find('t') → 2
count()Count occurrences'banana'.count('a') → 3
split()Split string'a,b,c'.split(',') → ['a', 'b', 'c']
join()Join sequence"-".join(['A', 'B']) → A-B
startswith()Check prefix'Python'.startswith('Py') → True
endswith()Check suffix'Python'.endswith('on') → True

🧮 Example: Using Methods


text = "  python programming  "

print(text.upper())
print(text.lower())
print(text.title())
print(text.strip())
print(text.replace("python", "java"))
print(text.count("m"))
print(text.find("pro"))
  

Output:
PYTHON PROGRAMMING
python programming
Python Programming
python programming
java programming
2
2

🔤 Example: Formatting Strings

Python में strings को format करने के लिए तीन तरीके हैं:


name = "Amit"
age = 21
score = 95.5

# 1️⃣ Using %
print("Name: %s, Age: %d, Score: %.1f" % (name, age, score))

# 2️⃣ Using str.format()
print("Name: {}, Age: {}, Score: {}".format(name, age, score))

# 3️⃣ Using f-string
print(f"Name: {name}, Age: {age}, Score: {score}")
  

Output:
Name: Amit, Age: 21, Score: 95.5
Name: Amit, Age: 21, Score: 95.5
Name: Amit, Age: 21, Score: 95.5

🧩 Example: Checking Palindrome


text = "madam"
if text == text[::-1]:
    print("Palindrome")
else:
    print("Not Palindrome")
  

Output:
Palindrome

🧠 Example: Counting Vowels


text = "Hello Python"
count = 0
for ch in text.lower():
    if ch in "aeiou":
        count += 1
print("Total vowels:", count)
  

Output:
Total vowels: 3

💬 Interview FAQs

  • Q: What is a string in Python?
    A: A sequence of characters enclosed in quotes.
  • Q: Are strings mutable?
    A: No, strings are immutable in Python.
  • Q: How to reverse a string?
    A: Using slicing → string[::-1].
  • Q: How to find string length?
    A: Using len(string).
  • Q: What is the difference between strip() and replace()?
    A: strip() removes spaces, replace() replaces characters or substrings.
9️⃣ Accepting Input & Printing Output in Python

📘 Introduction

किसी भी प्रोग्राम का सबसे महत्वपूर्ण हिस्सा होता है — Input लेना (user से data प्राप्त करना) और Output दिखाना (screen पर result दिखाना)। Python में इसके लिए दो प्रमुख functions होते हैं:

  • 🟢 input() — यूज़र से data लेने के लिए
  • 🔵 print() — स्क्रीन पर output दिखाने के लिए

🧩 1️⃣ Taking Input using input()

input() function user से input लेता है और हमेशा data को string के रूप में return करता है। अगर numeric data चाहिए तो type conversion करना पड़ता है (जैसे int(), float() आदि)।


name = input("Enter your name: ")
print("Hello,", name)
  

Output:
Enter your name: Amit
Hello, Amit

🔢 Example: Numeric Input with Type Conversion


a = int(input("Enter first number: "))
b = float(input("Enter second number: "))
sum = a + b
print("Sum =", sum)
  

Output:
Enter first number: 5
Enter second number: 2.5
Sum = 7.5

🧠 Example: Multiple Inputs in One Line

आप एक ही line में कई inputs ले सकते हैं split() method के साथ।


x, y = input("Enter two numbers separated by space: ").split()
print("First number:", x)
print("Second number:", y)
  

Output:
Enter two numbers separated by space: 10 20
First number: 10
Second number: 20

🧮 Example: Taking Multiple Numbers as List


numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print("List of numbers:", numbers)
print("Sum of numbers:", sum(numbers))
  

Output:
Enter numbers separated by space: 5 10 15 20
List of numbers: [5, 10, 15, 20]
Sum of numbers: 50

🖨️ 2️⃣ Displaying Output using print()

print() function का उपयोग screen पर data दिखाने के लिए किया जाता है। इसमें आप strings, numbers, variables, और expressions print कर सकते हैं।


x = 10
y = 20
print("Sum of", x, "and", y, "is", x + y)
  

Output:
Sum of 10 and 20 is 30

🧾 Example: Using sep and end Parameters

sep (separator) और end parameters output format को control करते हैं।


print("Amit", "Kumar", sep="-")
print("Python", end=" ")
print("Programming")
  

Output:
Amit-Kumar
Python Programming

💡 Example: Printing with f-Strings

f-strings Python 3.6+ में introduce हुए थे — जो variables को string में directly embed करने की सुविधा देते हैं।


name = "Amit"
age = 21
print(f"My name is {name} and I am {age} years old.")
  

Output:
My name is Amit and I am 21 years old.

🧮 Example: Printing Expressions Directly


a = 5
b = 3
print("Sum =", a + b)
print("Product =", a * b)
print("Average =", (a + b) / 2)
  

Output:
Sum = 8
Product = 15
Average = 4.0

🧩 Example: Printing Formatted Output (Old Style)

आप placeholders (%) का इस्तेमाल करके formatted output भी दिखा सकते हैं।


name = "Amit"
marks = 91.25
print("Name: %s | Marks: %.2f" % (name, marks))
  

Output:
Name: Amit | Marks: 91.25

📊 Example: String Formatting using format()


subject = "Python"
score = 95
print("Subject: {} | Score: {}".format(subject, score))
  

Output:
Subject: Python | Score: 95

🧠 Example: Printing Tables (Formatted Output)


num = int(input("Enter a number: "))
for i in range(1, 6):
    print(f"{num} x {i} = {num * i}")
  

Output:
Enter a number: 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15

💬 Interview FAQs

  • Q: What is the return type of input()?
    A: Always returns a string.
  • Q: How to take integer input from user?
    A: Use int(input()).
  • Q: What is the use of sep and end in print()?
    A: sep defines separator between items, and end defines how the line ends (default is newline).
  • Q: Difference between f-string and format()?
    A: f-string is faster and easier to write; format() is older but widely supported.
  • Q: Can we take multiple inputs in one line?
    A: Yes, using input().split().
🔟 Simple Python Programs

📘 Introduction

Python एक high-level और easy-to-learn programming language है। Beginners के लिए सबसे पहला step होता है छोटे programs बनाना जो basic logic सिखाते हैं — जैसे addition, loops, conditions, input-output, strings और numbers पर काम करना। नीचे दिए गए उदाहरण आपको Python की बुनियादी समझ को मजबूत करने में मदद करेंगे।

💻 Example 1: Print “Hello, World!”


print("Hello, World!")
  

Output:
Hello, World!

🧮 Example 2: Addition of Two Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum =", sum)
  

Output:
Enter first number: 8
Enter second number: 12
Sum = 20

⚙️ Example 3: Find Square and Cube of a Number


num = int(input("Enter a number: "))
print("Square =", num ** 2)
print("Cube =", num ** 3)
  

Output:
Enter a number: 4
Square = 16
Cube = 64

📏 Example 4: Area of a Rectangle


length = float(input("Enter length: "))
breadth = float(input("Enter breadth: "))
area = length * breadth
print("Area of Rectangle =", area)
  

Output:
Enter length: 5
Enter breadth: 3
Area of Rectangle = 15.0

🔁 Example 5: Print Table of a Number


n = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")
  

Output:
Enter a number: 6
6 x 1 = 6
6 x 2 = 12
...
6 x 10 = 60

🧠 Example 6: Check Even or Odd


num = int(input("Enter a number: "))
if num % 2 == 0:
    print("Even Number")
else:
    print("Odd Number")
  

Output:
Enter a number: 7
Odd Number

📅 Example 7: Check Leap Year


year = int(input("Enter a year: "))
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
    print("Leap Year")
else:
    print("Not a Leap Year")
  

Output:
Enter a year: 2024
Leap Year

🔢 Example 8: Sum of Natural Numbers


n = int(input("Enter N: "))
sum = 0
for i in range(1, n+1):
    sum += i
print("Sum of first", n, "natural numbers =", sum)
  

Output:
Enter N: 5
Sum of first 5 natural numbers = 15

💠 Example 9: Factorial of a Number


num = int(input("Enter a number: "))
fact = 1
for i in range(1, num+1):
    fact *= i
print("Factorial =", fact)
  

Output:
Enter a number: 5
Factorial = 120

🔢 Example 10: Fibonacci Series


n = int(input("Enter number of terms: "))
a, b = 0, 1
print("Fibonacci Series:")
for i in range(n):
    print(a, end=" ")
    a, b = b, a + b
  

Output:
Enter number of terms: 6
Fibonacci Series:
0 1 1 2 3 5

🔄 Example 11: Reverse a Number


num = int(input("Enter a number: "))
rev = 0
while num > 0:
    rev = rev * 10 + num % 10
    num //= 10
print("Reversed number =", rev)
  

Output:
Enter a number: 1234
Reversed number = 4321

🔤 Example 12: Check Palindrome String


text = input("Enter a string: ")
if text == text[::-1]:
    print("Palindrome String")
else:
    print("Not a Palindrome")
  

Output:
Enter a string: madam
Palindrome String

🔠 Example 13: Count Vowels in a String


text = input("Enter text: ").lower()
count = 0
for ch in text:
    if ch in "aeiou":
        count += 1
print("Total vowels =", count)
  

Output:
Enter text: Hello World
Total vowels = 3

📈 Example 14: Find Largest Element in List


numbers = [10, 25, 8, 36, 72, 15]
print("Largest number =", max(numbers))
  

Output:
Largest number = 72

🧩 Example 15: Check Prime Number


num = int(input("Enter a number: "))
if num > 1:
    for i in range(2, num):
        if num % i == 0:
            print("Not Prime")
            break
    else:
        print("Prime Number")
else:
    print("Not Prime")
  

Output:
Enter a number: 7
Prime Number

💬 Interview FAQs

  • Q: What is the first program usually written in Python?
    A: The “Hello, World!” program — used to verify installation and syntax understanding.
  • Q: How to take multiple inputs from a user in one line?
    A: Using input().split() or map() for type casting.
  • Q: What is the purpose of indentation in Python?
    A: It defines the block of code (like curly braces in other languages).
  • Q: What is the difference between print() and return?
    A: print() displays result, while return gives value back from a function.
  • Q: How to reverse a string in Python?
    A: Using slicing → string[::-1].