Book Title: "Python Programming: खुद से सीखें"
Index (Table of Contents)
Part 1: Python की बुनियाद (Basics of Python Programming)
- Introduction to Python Programming
- Python क्या है?
- Python की विशेषताएँ (Features)
- Python का इतिहास
- Python क्यों सीखें?
- Setting Up Python Environment
- Python Installation (Windows, Mac, Linux)
- Python IDEs (IDLE, PyCharm, Jupyter Notebook, VS Code)
- पहला Python प्रोग्राम लिखना
- Python Syntax and Basic Concepts
- Python का Syntax
- Variables और Data Types
- Input और Output
- Comments और Indentation
Part 2: Python Programming में नियंत्रण (Control Structures)
- Control Flow Statements
- If-Else Statements
- Nested If-Else
- Loops: For Loop, While Loop
- Break और Continue
- Functions in Python
- Functions का परिचय
- Built-in Functions
- User-defined Functions
- Lambda Functions
Part 3: Data और File Handling
- Data Structures in Python
- Lists
- Tuples
- Dictionaries
- Sets
- File Handling in Python
- Text Files पढ़ना और लिखना
- CSV Files का उपयोग
- Error Handling
Part 4: Python Libraries और Modules
- Working with Python Libraries
- Libraries का परिचय
- Popular Libraries (NumPy, Pandas, Matplotlib)
- Modules and Packages
- Python Modules
- User-defined Modules
- Installing External Libraries (pip का उपयोग)
Part 5: Object-Oriented Programming (OOP) in Python
- Object-Oriented Concepts in Python
- Classes और Objects
- Inheritance
- Polymorphism
- Encapsulation
Part 6: Advanced Python Concepts
- Working with Regular Expressions
- Regular Expressions का परिचय
- Search और Match Functions
- Error और Exception Handling
- Try, Except और Finally
- Custom Exceptions
Part 7: Python for Real-World Applications
- Python for Data Analysis
- Introduction to Pandas
- Data Manipulation
- Data Visualization with Matplotlib
- Python for Web Development
- Flask और Django का परिचय
- Basic Web App बनाना
- Introduction to Machine Learning with Python
- Scikit-Learn Library का उपयोग
- Simple ML Models बनाना
Part 8: Project Work and Best Practices
- Python Mini Projects
- Calculator Program
- To-Do List Application
- Weather App
- Best Practices in Python Programming
- Clean Code Writing
- Debugging और Testing
- Documentation Writing
Appendix
- Python Cheatsheet
- Useful Resources and Links
- Python Interview Questions for Beginners
Description:
यह पुस्तक Python Programming की एक व्यापक मार्गदर्शिका है। इसमें शुरुआती से लेकर advanced concepts तक हर एक चीज़ को सरल और व्यावहारिक तरीके से समझाया गया है। प्रत्येक chapter में theory के साथ-साथ coding examples और exercises शामिल हैं, ताकि पाठक concepts को अच्छी तरह समझ सकें और उन्हें प्रैक्टिकल रूप से लागू कर सकें।
Part 1: Python की बुनियाद (Basics of Python Programming)
Chapter 1: Introduction to Python Programming
1. Python क्या है?
Python एक हाई-लेवल, इंटरप्रेटेड, और ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग लैंग्वेज है जिसे 1991 में Guido van Rossum ने विकसित किया।
- यह simplicity और readability पर केंद्रित है, जिससे इसे समझना और कोड करना आसान बनता है।
- Python का उपयोग कई क्षेत्रों में होता है, जैसे:
- Web Development (Flask, Django)
- Data Science (Pandas, NumPy)
- Artificial Intelligence और Machine Learning
- Game Development
- Automation
उदाहरण:
print("Hello, Python!")
2. Python की विशेषताएँ (Features)
-
सिंपल और आसान (Simple and Easy to Learn):
Python का सिंटेक्स साधारण और नेचुरल लैंग्वेज जैसा है।
Example:a = 5 b = 10 print(a + b)
-
ओपन-सोर्स और फ्री (Open-Source and Free):
Python को डाउनलोड और उपयोग करना मुफ्त है। -
इंटरप्रेटेड भाषा (Interpreted Language):
Python कोड को सीधे इंटरप्रेटर द्वारा रन किया जाता है, जिससे कोड जल्दी टेस्ट किया जा सकता है। -
प्लेटफ़ॉर्म इंडिपेंडेंट (Platform Independent):
Python का कोड Windows, Mac, Linux आदि पर बिना बदलाव के रन किया जा सकता है। -
बड़ी लाइब्रेरी सपोर्ट (Extensive Library Support):
Python में कई लाइब्रेरी हैं, जैसे:- Data Science के लिए: NumPy, Pandas
- Web Development के लिए: Flask, Django
-
मल्टी-पर्पज भाषा (Multipurpose Language):
Python को गेम, वेबसाइट, सॉफ्टवेयर और मशीन लर्निंग में उपयोग किया जाता है।
3. Python का इतिहास (History of Python)
- Python का निर्माण 1991 में Guido van Rossum ने किया।
- इसका नाम इंग्लिश कॉमेडी शो "Monty Python's Flying Circus" से प्रेरित है।
- Python के वर्शन:
- Python 2: 2000 में रिलीज़ हुआ, लेकिन 2020 में इसे बंद कर दिया गया।
- Python 3: 2008 में रिलीज़ हुआ, और यह अभी भी अपडेट हो रहा है।
Python की यात्रा:
- 1991: पहला वर्शन रिलीज़ हुआ।
- 2000: Python 2 रिलीज़ (Object-Oriented Concepts जोड़े गए)।
- 2008: Python 3 लॉन्च हुआ (अधिक आधुनिक फीचर्स के साथ)।
4. Python क्यों सीखें?
-
आसान और समझने में सरल (Beginner-Friendly):
Python शुरुआती प्रोग्रामर्स के लिए बेहतरीन भाषा है। -
डिमांड में (High Demand):
Python की डिमांड Data Science, AI, और Web Development में सबसे अधिक है। -
कम कोड में अधिक (Less Code, More Output):
Python अन्य भाषाओं जैसे C++ और Java के मुकाबले कम कोड में अधिक काम करता है।
Example (Python vs Java):- Python:
print("Hello, World!")
- Java:
public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }
- Python:
-
विभिन्न क्षेत्रों में उपयोग (Versatile):
Python का उपयोग:- Web Development (Backend)
- Data Analysis और Visualization
- Game Development
- IoT (Internet of Things)
-
कम्युनिटी सपोर्ट (Community Support):
Python की एक बड़ी और सक्रिय कम्युनिटी है, जो समस्याओं को हल करने में मदद करती है।
Chapter Summary:
- Python एक सरल, शक्तिशाली, और बहु-उपयोगी प्रोग्रामिंग भाषा है।
- यह शुरुआती और पेशेवर प्रोग्रामर्स के लिए समान रूप से उपयुक्त है।
- इसके उपयोग के अनगिनत क्षेत्र हैं, जिससे यह आधुनिक प्रोग्रामिंग की सबसे लोकप्रिय भाषा बन चुकी है।
Chapter 2: Setting Up Python Environment
यह Chapter आपको Python को इंस्टॉल करने, IDEs (Integrated Development Environments) का उपयोग करने, और पहला Python प्रोग्राम लिखने के लिए मार्गदर्शन देगा।
1. Python Installation (Windows, Mac, Linux)
Python को इंस्टॉल करना आसान है, और यह सभी प्रमुख ऑपरेटिंग सिस्टम्स (Windows, Mac, Linux) पर चलता है।
Step-by-Step Installation Guide:
Windows पर Python Install करें:
- Python की आधिकारिक वेबसाइट पर जाएं।
- "Download Python" बटन पर क्लिक करें और अपने सिस्टम के लिए सही वर्शन डाउनलोड करें।
- डाउनलोड की गई फाइल को खोलें और "Add Python to PATH" ऑप्शन को चेक करें।
- "Install Now" पर क्लिक करें और इंस्टॉलेशन पूरी करें।
- सफल इंस्टॉलेशन के बाद, Command Prompt खोलें और टाइप करें:
अगर वर्शन दिखाई दे, तो Python इंस्टॉल हो चुका है।python --version
Mac पर Python Install करें:
- Mac पर Python पहले से आता है, लेकिन यह Python 2 हो सकता है। Python 3 इंस्टॉल करने के लिए:
- Homebrew को इंस्टॉल करें:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Homebrew से Python इंस्टॉल करें:
brew install python
- Python वर्शन चेक करें:
python3 --version
Linux पर Python Install करें:
- Python अधिकांश Linux distributions में पहले से उपलब्ध होता है। अगर नहीं है:
sudo apt update sudo apt install python3
- इंस्टॉलेशन चेक करें:
python3 --version
2. Python IDEs (IDLE, PyCharm, Jupyter Notebook, VS Code)
Python प्रोग्रामिंग के लिए IDE (Integrated Development Environment) कोड लिखने और रन करने के लिए उपयोगी होता है।
IDLE (Integrated Development and Learning Environment):
- Python के साथ डिफ़ॉल्ट आता है।
- इसे Command Prompt पर टाइप करके खोलें:
idle
PyCharm:
- एक शक्तिशाली IDE जो विशेष रूप से Python के लिए डिज़ाइन किया गया है।
- डाउनलोड और इंस्टॉल करें: PyCharm.
- इसका फ्री वर्शन (Community Edition) शुरुआती के लिए पर्याप्त है।
Jupyter Notebook:
- Data Science और Visualization के लिए लोकप्रिय।
- इंस्टॉल करें:
pip install notebook jupyter notebook
- यह ब्राउज़र में खुलता है।
VS Code (Visual Studio Code):
- मल्टी-लैंग्वेज कोडिंग के लिए सबसे अच्छा।
- Python एक्सटेंशन इंस्टॉल करें।
- VS Code Download करें.
IDE का चयन आपके उपयोग और प्रोजेक्ट के प्रकार पर निर्भर करता है। शुरुआती के लिए IDLE या PyCharm की सिफारिश की जाती है।
3. पहला Python प्रोग्राम लिखना (Your First Python Program)
Python का पहला प्रोग्राम बहुत सरल है। इसे "Hello, World!" प्रिंट करने के लिए लिखा जाता है।
IDLE में पहला प्रोग्राम:
- IDLE खोलें।
- "File > New File" पर जाएं।
- निम्नलिखित कोड लिखें:
print("Hello, World!")
- इसे hello.py नाम से सेव करें।
- "Run > Run Module" पर क्लिक करें।
- आउटपुट:
Hello, World!
- आउटपुट:
Command Prompt/Terminal से प्रोग्राम रन करना:
- एक टेक्स्ट एडिटर (Notepad/VS Code) खोलें।
- निम्न कोड लिखें और इसे hello.py नाम से सेव करें:
print("Hello, World!")
- Command Prompt/Terminal खोलें और फाइल के लोकेशन पर जाएं:
python hello.py
- आउटपुट:
Hello, World!
- आउटपुट:
Chapter Summary:
- Python इंस्टॉलेशन Windows, Mac, और Linux पर आसान है।
- IDLE, PyCharm, Jupyter Notebook, और VS Code जैसे IDEs Python प्रोग्रामिंग को प्रभावी और सुविधाजनक बनाते हैं।
- "Hello, World!" पहला प्रोग्राम Python की सरलता का उदाहरण है।
Chapter 3: Python Syntax and Basic Concepts
यह अध्याय Python के सिंटेक्स, वेरिएबल्स, डेटा टाइप्स, इनपुट/आउटपुट, और कोड को सही तरीके से व्यवस्थित करने के लिए इंडेंटेशन और कमेंट्स के उपयोग को समझाएगा।
1. Python का Syntax
Python का सिंटेक्स (Syntax) सरल और पढ़ने में आसान है। इसे समझने के लिए मुख्य बिंदु:
-
Case-Sensitivity:
Python में वेरिएबल्स और फंक्शन्स case-sensitive होते हैं।Name = "Ajay" name = "Kumar" print(Name) # Output: Ajay print(name) # Output: Kumar
-
Statements को समाप्त करने के लिए सेमी-कोलन की ज़रूरत नहीं:
Python में स्टेटमेंट को लिखने के बाद सेमी-कोलन (;
) की आवश्यकता नहीं होती।print("Hello, Python!")
-
Code Blocks और Indentation:
Python में कोड ब्लॉक को दर्शाने के लिए Indentation (स्पेस या टैब) का उपयोग होता है, न कि ब्रैसेस{}
।if True: print("Indented Code Runs") # Proper Indentation
2. Variables और Data Types
Variables (वेरिएबल्स):
- वेरिएबल्स Python में डेटा स्टोर करने के लिए उपयोग होते हैं।
- वेरिएबल्स को किसी भी डेटा टाइप से असाइन किया जा सकता है।
- वेरिएबल्स का नाम अक्षरों (letters), अंडरस्कोर (
_
), और अंकों (digits) से बन सकता है, लेकिन यह संख्या से शुरू नहीं हो सकता।
Example:
name = "Ajay" # String
age = 25 # Integer
height = 5.8 # Float
is_student = True # Boolean
print(name, age, height, is_student)
Data Types (डेटा टाइप्स):
-
int (Integer):
पूरे संख्याओं के लिए।num = 10
-
float:
दशमलव संख्या के लिए।pi = 3.14
-
str (String):
अक्षरों, शब्दों, और वाक्यों के लिए।greeting = "Hello, World!"
-
bool (Boolean):
केवलTrue
याFalse
।is_valid = True
3. Input और Output
Output (आउटपुट):
Python में आउटपुट दिखाने के लिए print()
फंक्शन का उपयोग होता है।
Example:
print("Welcome to Python!")
Input (इनपुट):
Python में उपयोगकर्ता से डेटा लेने के लिए input()
फंक्शन का उपयोग होता है।
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
Input का डेटा हमेशा String के रूप में आता है।
उसे Integer में बदलने के लिए:
age = int(input("Enter your age: "))
print("Your age is:", age)
4. Comments और Indentation
Comments (टिप्पणी):
-
Comments कोड को समझाने में मदद करते हैं और रन नहीं होते।
-
Single-line comment के लिए
#
का उपयोग करें।# This is a single-line comment print("Hello, Python!")
-
Multi-line comment के लिए ट्रिपल कोटेशन (
'''
या"""
) का उपयोग करें।""" This is a multi-line comment. Useful for long explanations. """ print("Multi-line comment example.")
Indentation (इंडेंटेशन):
-
Python में Indentation (स्पेस या टैब) कोड के ब्लॉक्स को दर्शाने के लिए उपयोग होता है।
-
अगर इंडेंटेशन सही नहीं है, तो एरर आएगा।
if True: print("Correct Indentation") # Proper indentation
गलत इंडेंटेशन का उदाहरण:
if True: print("Error!") # IndentationError
Chapter Summary:
- Python का सिंटेक्स आसान और साफ-सुथरा है।
- वेरिएबल्स और डेटा टाइप्स Python को फ्लेक्सिबल बनाते हैं।
print()
औरinput()
से आउटपुट और इनपुट संभाला जा सकता है।- Comments और Indentation Python को पढ़ने और लिखने में सहायक बनाते हैं।
Example Code:
# Asking for the user's name and greeting them
print("Hello! My name is Python.")
name = input("What is your name? ") # Using input to get the name
print("Nice to meet you, " + name + "!")
# Asking for the user's age
age = input("How old are you? ") # Using input to get the age
print("Wow! You are " + age + " years old.")
# A simple math game
print("Let's play a small math game!")
num1 = int(input("Enter the first number: ")) # Converting input to integer
num2 = int(input("Enter the second number: "))
result = num1 + num2 # Adding the two numbers
print("The sum of the numbers you entered is: ", result)
What kids will learn:
print()
: Screen पर messages दिखाने के लिए।input()
: User से data लेने के लिए।- Type Conversion:
int()
का use करके input को number में बदलना। - Simple Arithmetic: दो numbers को जोड़ना और result show करना।
Question: Write a simple Python code where a class 8 student declares variables to store their Name, Class, Roll No, and Village. Then, print these details on the screen.
Python Code:
# Declaring variables to store student information
name = "John Doe"
class_name = "8"
roll_no = "15"
village = "Greenwood"
# Printing the student's details
print("Name:", name)
print("Class:", class_name)
print("Roll No:", roll_no)
print("Village:", village)
This code declares variables to store the student's Name, Class, Roll No, and Village, and then prints them.
बिलकुल! नीचे कोड की एक्सप्लनेशन दी गई है,
-
Variable Declaration (वेरिएबल डिक्लेरेशन):
name = "John Doe"
: यहाँname
variable में student का नाम "John Doe" store किया गया है।class_name = "8"
:class_name
variable में student की class "8" store की गई है।roll_no = "15"
:roll_no
variable में student का roll number "15" store किया गया है।village = "Greenwood"
:village
variable में student का गाँव "Greenwood" store किया गया है।
-
Data Printing (डेटा प्रिंट करना):
print("Name:", name)
: यह line screen पर "Name: John Doe" print करेगी, जहाँname
variable में जो भी value है, वह दिखेगी।print("Class:", class_name)
: यह line screen पर "Class: 8" print करेगी।print("Roll No:", roll_no)
: यह line "Roll No: 15" print करेगी।print("Village:", village)
: यह line "Village: Greenwood" print करेगी।
Summary (सारांश): यह code student के name, class, roll number, और village को variables में store करता है और फिर उन्हें print करता है।
यहां चार और उदाहरण दिए गए हैं, जो इसी प्रकार के simple Python code को दर्शाते हैं:
Example 1: Student’s Age and Gender
# Declaring variables to store student information
name = "Ravi"
age = 14
gender = "Male"
# Printing the student's details
print("Name:", name)
print("Age:", age)
print("Gender:", gender)
Explanation: यह कोड student का नाम, आयु (age) और लिंग (gender) स्टोर करता है और फिर इन जानकारी को print करता है।
Example 2: Book Information
# Declaring variables to store book information
title = "Python Programming"
author = "John Smith"
price = 499
# Printing the book's details
print("Title:", title)
print("Author:", author)
print("Price:", price)
Explanation: यह कोड एक किताब का नाम, लेखक का नाम और उसकी कीमत store करता है और फिर उसे print करता है।
Example 3: Employee Information
# Declaring variables to store employee information
emp_name = "Priya Sharma"
emp_id = 1023
salary = 35000
# Printing the employee's details
print("Employee Name:", emp_name)
print("Employee ID:", emp_id)
print("Salary:", salary)
Explanation: यह कोड एक employee का नाम, ID और salary store करता है और फिर उसे print करता है।
Example 4: Car Information
# Declaring variables to store car information
car_model = "Honda Civic"
car_color = "Red"
car_price = 1200000
# Printing the car's details
print("Car Model:", car_model)
print("Car Color:", car_color)
print("Car Price:", car_price)
Explanation: यह कोड एक कार का मॉडल, रंग (color) और कीमत (price) store करता है और फिर उसे print करता है।
इन उदाहरणों में हम variables का उपयोग कर रहे हैं विभिन्न types की जानकारी को store और print करने के लिए।
Part 2: Python Programming में नियंत्रण (Control Structures)
इस भाग में, आप सीखेंगे कि कैसे Python में प्रोग्राम के प्रवाह को नियंत्रित किया जाता है। इसमें हम Control Flow Statements, If-Else Statements, Nested If-Else, और Loops (For और While) के साथ Break और Continue स्टेटमेंट्स का उपयोग समझेंगे।
1. Control Flow Statements (नियंत्रण प्रवाह कथन)
Control Flow Statements प्रोग्राम को यह तय करने देते हैं कि कौन सा कोड कब और कैसे चलेगा।
Control Flow के प्रकार:
-
Conditional Statements (शर्तीय कथन):
यह कोड को केवल तब चलाता है जब एक विशेष शर्त (Condition) सही हो।if
,if-else
, औरif-elif-else
के जरिए।
-
Loops (लूप्स):
कोड के एक हिस्से को बार-बार चलाने के लिए उपयोग किया जाता है।for loop
औरwhile loop
।
2. If-Else Statements
Simple If Statement:
अगर शर्त सही है (True), तो कोड ब्लॉक चलेगा।
x = 10
if x > 5:
print("x is greater than 5")
If-Else Statement:
if
ब्लॉक तब चलता है जब शर्त सही हो, और else
ब्लॉक तब चलता है जब शर्त गलत हो।
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
If-Elif-Else Statement:
कई शर्तों को चेक करने के लिए elif
का उपयोग होता है।
x = 10
if x < 5:
print("x is less than 5")
elif x == 10:
print("x is equal to 10")
else:
print("x is greater than 5 but not 10")
3. Nested If-Else (गहराई वाले If-Else)
if
के अंदर एक और if
स्टेटमेंट लिखा जा सकता है।
x = 15
if x > 10:
if x < 20:
print("x is between 10 and 20")
else:
print("x is greater than or equal to 20")
else:
print("x is less than or equal to 10")
4. Loops (लूप्स)
For Loop (के लिए लूप):
एक निश्चित संख्या में या किसी लिस्ट/स्ट्रिंग के हर आइटम पर लूप चलाने के लिए।
# Example 1: Numbers Loop
for i in range(5): # 0 से 4 तक
print(i)
# Example 2: List Iteration
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Example 3: String Iteration
for char in "Python":
print(char)
While Loop (जब तक लूप):
जब तक शर्त सही है (True), लूप चलता रहता है।
x = 0
while x < 5:
print(x)
x += 1 # x = x + 1
5. Break और Continue
Break Statement:
break
लूप को तुरंत समाप्त कर देता है।
for i in range(10):
if i == 5:
break
print(i)
# Output: 0, 1, 2, 3, 4
Continue Statement:
continue
लूप को रोकता नहीं है, बल्कि अगले इटरेशन पर ले जाता है।
for i in range(10):
if i == 5:
continue
print(i)
# Output: 0, 1, 2, 3, 4, 6, 7, 8, 9
Chapter Summary:
- Control Flow Statements प्रोग्राम के निर्णय-निर्माण और दोहराव (loops) को आसान बनाते हैं।
- If-Else Statements का उपयोग शर्तों के अनुसार निर्णय लेने में होता है।
- Loops (For और While) से कोड को बार-बार चलाना आसान होता है।
- Break और Continue लूप के प्रवाह को नियंत्रित करने में मदद करते हैं।
Here are more simple Python examples for students of classes 6, 7, and 8 to practice and understand basic programming concepts:
1. Find the Largest Number
# Program to find the largest number between two numbers
print("Let's find the largest number!")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if num1 > num2:
print("The largest number is:", num1)
elif num2 > num1:
print("The largest number is:", num2)
else:
print("Both numbers are equal!")
2. Simple Calculator
# A simple calculator for addition, subtraction, multiplication, and division
print("Welcome to the simple calculator!")
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Choose an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = int(input("Enter your choice (1/2/3/4): "))
if choice == 1:
print("The result is:", num1 + num2)
elif choice == 2:
print("The result is:", num1 - num2)
elif choice == 3:
print("The result is:", num1 * num2)
elif choice == 4:
if num2 != 0:
print("The result is:", num1 / num2)
else:
print("Division by zero is not allowed!")
else:
print("Invalid choice!")
3. Guess the Number Game
# A simple number guessing game
import random
print("Welcome to the number guessing game!")
secret_number = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))
if guess == secret_number:
print("Congratulations! You guessed it right!")
else:
print("Oops! The correct number was:", secret_number)
4. Check Even or Odd
# Program to check if a number is even or odd
print("Check if a number is even or odd!")
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
5. Simple Multiplication Table
# Program to display a multiplication table
print("Multiplication Table Generator")
number = int(input("Enter a number to see its multiplication table: "))
for i in range(1, 11):
print(number, "x", i, "=", number * i)
6. Count Characters in a String
# Program to count the number of characters in a string
print("Count the characters in your text!")
text = input("Enter any text: ")
print("The number of characters in the text is:", len(text))
7. Find the Area of a Circle
# Program to calculate the area of a circle
import math
print("Calculate the area of a circle!")
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius * radius
print("The area of the circle is:", area)
8. Display Current Date and Time
# Program to display the current date and time
from datetime import datetime
print("Display the current date and time!")
current_time = datetime.now()
print("Current date and time:", current_time)
9. Simple Grading System
# Program to assign grades based on marks
print("Simple Grading System")
marks = int(input("Enter your marks (0-100): "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")
Here are more simple and easy Python examples for students to practice:
1. Add Two Numbers
# Program to add two numbers
print("Let's add two numbers!")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
sum = num1 + num2
print("The sum of", num1, "and", num2, "is:", sum)
2. Square of a Number
# Program to find the square of a number
print("Find the square of a number!")
number = int(input("Enter a number: "))
square = number ** 2
print("The square of", number, "is:", square)
3. Hello, World!
# Classic Hello, World program
print("Hello, World!")
4. Print Your Name
# Program to display the user's name
name = input("What is your name? ")
print("Hello, " + name + "! Welcome to Python programming.")
5. Find the Remainder
# Program to calculate the remainder of a division
print("Find the remainder of two numbers!")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
remainder = num1 % num2
print("The remainder when", num1, "is divided by", num2, "is:", remainder)
6. Check Positive or Negative
# Program to check if a number is positive, negative, or zero
print("Check if a number is positive, negative, or zero!")
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
7. Repeat a Message
# Program to repeat a message multiple times
message = input("Enter a message: ")
times = int(input("How many times should it be repeated? "))
for i in range(times):
print(message)
8. Swap Two Numbers
# Program to swap two numbers
print("Swap two numbers!")
a = int(input("Enter the first number (a): "))
b = int(input("Enter the second number (b): "))
# Swapping
a, b = b, a
print("After swapping:")
print("a =", a)
print("b =", b)
9. Count to 10
# Program to count from 1 to 10
print("Counting from 1 to 10:")
for i in range(1, 11):
print(i)
10. Find the Average of Three Numbers
# Program to find the average of three numbers
print("Find the average of three numbers!")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
average = (num1 + num2 + num3) / 3
print("The average of", num1, ",", num2, "and", num3, "is:", average)
11. Simple Countdown
# Program to print a countdown from 5 to 1
print("Countdown:")
for i in range(5, 0, -1):
print(i)
print("Blast off!")
12. Convert Minutes to Seconds
# Program to convert minutes into seconds
print("Convert minutes into seconds!")
minutes = int(input("Enter the number of minutes: "))
seconds = minutes * 60
print(minutes, "minutes is equal to", seconds, "seconds.")
13. Check if a Number is Divisible by 5
# Program to check if a number is divisible by 5
number = int(input("Enter a number: "))
if number % 5 == 0:
print("The number is divisible by 5.")
else:
print("The number is not divisible by 5.")
14. Reverse a String
# Program to reverse a string
print("Reverse a string!")
text = input("Enter some text: ")
reversed_text = text[::-1]
print("The reversed text is:", reversed_text)
15. Simple Greeting
# Program to greet based on the time of the day
print("What time is it?")
time = int(input("Enter the hour (0-23): "))
if 0 <= time < 12:
print("Good Morning!")
elif 12 <= time < 18:
print("Good Afternoon!")
else:
print("Good Evening!")
Chapter 5: Functions in Python
यह अध्याय Python में Functions का परिचय, Built-in Functions, User-defined Functions, और Lambda Functions को विस्तार से समझाएगा।
1. Functions का परिचय (Introduction to Functions)
Function क्या है?
- Python में Function कोड का एक ब्लॉक है जिसे बार-बार उपयोग किया जा सकता है।
- Functions जटिल कार्यों को आसान बनाते हैं और कोड को Modular बनाते हैं।
Functions के मुख्य फायदे:
- कोड को पुन: उपयोग (Reuse) करना।
- कोड को अधिक संगठित और पढ़ने में आसान बनाना।
- प्रोग्राम के Execution को तेज़ करना।
Function Syntax:
def function_name(parameters):
# Code block
return value # Optional
Example:
def greet(name):
print(f"Hello, {name}!")
greet("Ajay") # Output: Hello, Ajay!
2. Built-in Functions (निर्मित Functions)
Python में कई Predefined Functions होते हैं जो सीधे उपयोग किए जा सकते हैं।
Common Built-in Functions:
-
print()
: Output दिखाने के लिए।print("Hello, Python!")
-
len()
: किसी लिस्ट, स्ट्रिंग, या अन्य डेटा की लंबाई जानने के लिए।print(len("Python")) # Output: 6
-
type()
: किसी वेरिएबल का डेटा टाइप जानने के लिए।print(type(10)) # Output: <class 'int'>
-
input()
: यूजर से इनपुट लेने के लिए।name = input("Enter your name: ") print(name)
-
sum()
औरmin()
: लिस्ट या संख्याओं का योग या न्यूनतम मान निकालने के लिए।numbers = [10, 20, 30] print(sum(numbers)) # Output: 60 print(min(numbers)) # Output: 10
3. User-defined Functions
User-defined Functions प्रोग्रामर द्वारा बनाए जाते हैं।
User-defined function वह function होते हैं जिन्हें user खुद define करता है, ताकि specific tasks को perform किया जा सके। ये functions आपको code को reusable बनाने में मदद करते हैं और program को modular बनाते हैं।
Function Define करने की Syntax:
Function को define करने के लिए हम def
keyword का उपयोग करते हैं, उसके बाद function का नाम, parentheses ()
(जो parameters के लिए होते हैं), और colon :
लगाते हैं। इसके बाद function का code block आता है, जो indented होता है।
def function_name(parameters):
# Code block
return value
def
: यह keyword function define करने के लिए इस्तेमाल किया जाता है।function_name
: यह function का नाम है। इसे आप किसी भी valid identifier जैसा रख सकते हैं।parameters
: ये optional होते हैं। आप function को call करते समय values (arguments) pass कर सकते हैं।return
: यह keyword किसी value को return करने के लिए है (optional)। यदि return नहीं करना हो तो इसे omit किया जा सकता है।
Steps to Create and Use a User-defined Function:
- Function Define करें: पहले
def
का उपयोग करके function का code लिखें। - Function Call करें: function define करने के बाद, आप इसे program में कहीं भी call कर सकते हैं।
Example 1: A Simple Function Without Parameters (बिना Parameters वाला साधारण Function)
# Function to print a greeting message
def greet():
print("Hello, welcome to Python programming!")
# Calling the function
greet()
Explanation:
greet()
function कोई parameters नहीं लेता।- यह बस एक greeting message print करता है।
Example 2: Function with Parameters (Parameters के साथ Function)
# Function to add two numbers
def add_numbers(a, b):
sum = a + b
return sum
# Calling the function with arguments
result = add_numbers(10, 20)
print("The sum is:", result)
Explanation:
add_numbers(a, b)
function दो parametersa
औरb
लेता है।- यह दोनों numbers को add करता है और result return करता है।
- इसे
10
और20
arguments के साथ call किया जाता है।
Example 3: Function with Default Parameters (Default Parameters के साथ Function)
# Function to greet a person with a default name
def greet_person(name="Guest"):
print(f"Hello, {name}!")
# Calling the function without an argument
greet_person()
# Calling the function with an argument
greet_person("John")
Explanation:
greet_person()
function में एक default parametername="Guest"
है।- यदि function को बिना argument के call किया जाता है, तो default value "Guest" use होती है।
- यदि argument दिया जाता है, तो वही value use होती है।
Example 4: Function with Multiple Return Values (Multiple Return Values वाला Function)
# Function to return the sum and product of two numbers
def sum_and_product(a, b):
sum_result = a + b
product_result = a * b
return sum_result, product_result
# Calling the function and unpacking the result
sum_value, product_value = sum_and_product(5, 3)
print("Sum:", sum_value)
print("Product:", product_value)
Explanation:
sum_and_product(a, b)
function दोनों numbers का sum और product return करता है।- return किए गए values को दो variables में unpack किया जाता है:
sum_value
औरproduct_value
।
Advantages of User-defined Functions (User-defined Functions के फायदे):
- Code Reusability (Code का पुनः उपयोग): एक बार function define करने के बाद, उसे कई बार बिना code को फिर से लिखे call किया जा सकता है।
- Modularity (Modularity): Functions complex tasks को छोटे हिस्सों में बांटने में मदद करते हैं।
- Improved Readability (Code की readability बढ़ाना): Functions का उपयोग करने से code साफ और समझने में आसान होता है।
- Testing and Debugging (Testing और Debugging): Functions code के हिस्सों को अलग करके testing और debugging को आसान बनाते हैं।
Conclusion (निष्कर्ष):
User-defined functions code को organize करने में मदद करते हैं और इसे modular बनाते हैं। ये आपको specific behavior define करने की अनुमति देते हैं और पूरे program में उसका पुनः उपयोग कर सकते हैं। Functions का उपयोग करके आप अपने code को maintainable और efficient बना सकते हैं।
Function Creation:
def
Keyword: Function को Define करने के लिए।- Parameters: इनपुट वैल्यू पास करने के लिए।
- Return Statement: आउटपुट वैल्यू देने के लिए।
Example:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 10)
print(result) # Output: 15
Default Parameters:
Parameters को Default वैल्यू देने पर वह वैल्यू तब उपयोग होती है जब कोई इनपुट न दिया जाए।
def greet(name="Guest"):
print(f"Welcome, {name}!")
greet() # Output: Welcome, Guest!
greet("Ajay") # Output: Welcome, Ajay!
Variable Arguments:
कभी-कभी Functions को एक से अधिक Parameters लेने की ज़रूरत होती है। इसके लिए *args
और **kwargs
का उपयोग होता है।
*args
: Tuple के रूप में Multiple Arguments।**kwargs
: Dictionary के रूप में Named Arguments।
Example:
def show_details(*args, **kwargs):
print("Arguments:", args)
print("Keyword Arguments:", kwargs)
show_details(1, 2, 3, name="Ajay", age=25)
# Output:
# Arguments: (1, 2, 3)
# Keyword Arguments: {'name': 'Ajay', 'age': 25}
4. Lambda Functions (लैम्ब्डा फंक्शन्स)
Lambda Functions छोटे, अनाम (Anonymous) फंक्शन्स हैं।
lambda
का उपयोग करके बनाया जाता है।- एक लाइन में Simple लॉजिक को Define करता है।
- इन्हें अक्सर Temporary उपयोग के लिए बनाया जाता है।
Syntax:
lambda arguments: expression
Example:
# Without Lambda
def square(x):
return x * x
# With Lambda
square = lambda x: x * x
print(square(5)) # Output: 25
Lambda Functions का उपयोग:
-
Sorting के लिए:
names = ["Ajay", "Mahi", "Neha"] names.sort(key=lambda x: len(x)) # Sort by length of name print(names) # Output: ['Mahi', 'Ajay', 'Neha']
-
Map और Filter के साथ:
map()
: हर आइटम पर Function Apply करता है।
numbers = [1, 2, 3, 4] squares = list(map(lambda x: x ** 2, numbers)) print(squares) # Output: [1, 4, 9, 16]
filter()
: शर्त के अनुसार आइटम को Filter करता है।
numbers = [1, 2, 3, 4] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # Output: [2, 4]
Chapter Summary:
- Functions कोड को दोबारा उपयोग करने और Modular बनाने में मदद करते हैं।
- Python में कई Built-in Functions उपलब्ध हैं।
- User-defined Functions के जरिए हम अपनी आवश्यकताओं के अनुसार Functions बना सकते हैं।
- Lambda Functions छोटे और सरल Functions के लिए उपयोगी होते हैं।
1. len()
- Find the Length of a String
# Find the length of a string
text = input("Enter a word or sentence: ")
length = len(text)
print("The length of the text is:", length)
Explanation:
len()
function का use string के characters की संख्या count करने के लिए होता है।
2. type()
- Check the Data Type
# Check the data type of a variable
value = input("Enter something: ")
print("The data type of the input is:", type(value))
Explanation:
type()
function का use किसी variable के data type को check करने के लिए होता है।
3. max()
and min()
- Find Maximum and Minimum
# Find the maximum and minimum numbers in a list
numbers = [10, 25, 30, 5, 18]
print("Numbers:", numbers)
print("The largest number is:", max(numbers))
print("The smallest number is:", min(numbers))
Explanation:
max()
list में सबसे बड़ा number find करता है।min()
list में सबसे छोटा number find करता है।
4. sum()
- Calculate the Sum of Numbers
# Calculate the sum of a list of numbers
numbers = [1, 2, 3, 4, 5]
print("Numbers:", numbers)
print("The sum of the numbers is:", sum(numbers))
Explanation:
sum()
list में मौजूद सभी numbers का total calculate करता है।
5. round()
- Round a Number
# Round a number to the nearest integer
number = float(input("Enter a decimal number: "))
rounded_number = round(number)
print("The rounded number is:", rounded_number)
Explanation:
round()
function number को nearest integer में round करता है।
6. abs()
- Find the Absolute Value
# Find the absolute value of a number
number = int(input("Enter a number (positive or negative): "))
absolute_value = abs(number)
print("The absolute value is:", absolute_value)
Explanation:
abs()
function किसी number का absolute value (positive version) return करता है।
7. pow()
- Calculate Power
# Calculate the power of a number
base = int(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
result = pow(base, exponent)
print(base, "raised to the power of", exponent, "is:", result)
Explanation:
pow(base, exponent)
base को exponent बार multiply करता है।
8. sorted()
- Sort a List
# Sort a list of numbers
numbers = [15, 3, 8, 25, 10]
print("Original List:", numbers)
sorted_numbers = sorted(numbers)
print("Sorted List:", sorted_numbers)
Explanation:
sorted()
function list को ascending order में arrange करता है।
9. input()
with int()
- Convert Input to Integer
# Convert user input to an integer and add 5
number = int(input("Enter a number: "))
print("The number plus 5 is:", number + 5)
Explanation:
input()
user से data लेता है औरint()
उसे integer में convert करता है।
10. str()
- Convert a Number to String
# Convert a number to a string and concatenate
number = 100
text = "The number is: " + str(number)
print(text)
Explanation:
str()
किसी number को string में convert करता है ताकि उसे concatenate किया जा सके।
11. list()
- Convert a String to a List of Characters
# Convert a string to a list of characters
text = input("Enter a word: ")
characters = list(text)
print("List of characters:", characters)
Explanation:
list()
function string को उसके characters की list में convert करता है।
12. int()
, float()
, str()
- Convert Between Types
# Convert between integer, float, and string
value = "123"
print("String value:", value, "Type:", type(value))
int_value = int(value)
print("Integer value:", int_value, "Type:", type(int_value))
float_value = float(value)
print("Float value:", float_value, "Type:", type(float_value))
Explanation:
int()
,float()
, औरstr()
functions का use data type convert करने के लिए होता है।
13. range()
- Generate a Range of Numbers
# Use range() to create a list of numbers
numbers = list(range(1, 11))
print("Numbers from 1 to 10:", numbers)
Explanation:
range(start, stop)
एक sequence of numbers generate करता है।
14. ord()
and chr()
- ASCII Values
# Find the ASCII value of a character and vice versa
character = input("Enter a character: ")
ascii_value = ord(character)
print("The ASCII value of", character, "is:", ascii_value)
number = int(input("Enter an ASCII value (0-127): "))
char = chr(number)
print("The character for ASCII value", number, "is:", char)
Explanation:
ord()
character का ASCII value देता है।chr()
ASCII value का corresponding character देता है।
15. help()
- Get Help on a Function
# Get help for a built-in function
print("Learn about the 'len' function:")
help(len)
Explanation:
help()
function किसी भी built-in function के बारे में जानकारी देता है।
16. reversed()
- Reverse a List
# Reverse a list
numbers = [1, 2, 3, 4, 5]
reversed_numbers = list(reversed(numbers))
print("Original List:", numbers)
print("Reversed List:", reversed_numbers)
Explanation:
reversed()
function list के elements को उल्टा कर देता है।
17. zip()
- Combine Two Lists
# Combine two lists using zip()
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
combined = list(zip(list1, list2))
print("Combined List:", combined)
Explanation:
zip()
दो lists को एक साथ pair में combine करता है।
18. eval()
- Evaluate a String as Code
# Use eval() to evaluate an expression
expression = input("Enter a mathematical expression (e.g., 5 + 3): ")
result = eval(expression)
print("The result of the expression is:", result)
Explanation:
eval()
string के अंदर दिए गए mathematical expression को calculate करता है।
यहां 5 उदाहरण दिए गए हैं, जो User-defined Functions से संबंधित हैं:
Example 1: Function to Calculate the Area of a Circle
# Function to calculate the area of a circle
def area_of_circle(radius):
area = 3.14 * radius * radius
return area
# Calling the function
radius = 5
result = area_of_circle(radius)
print("Area of circle with radius", radius, "is:", result)
Explanation:
यह function radius
parameter लेता है और circle का area (π * radius²
) calculate करके return करता है।
Example 2: Function to Check Whether a Number is Even or Odd
# Function to check if a number is even or odd
def check_even_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Calling the function
num = 7
result = check_even_odd(num)
print(f"The number {num} is {result}.")
Explanation:
यह function किसी भी number को check करता है कि वह even है या odd। यह return करता है "Even" या "Odd"।
Example 3: Function to Find the Maximum of Two Numbers
# Function to find the maximum of two numbers
def find_max(a, b):
if a > b:
return a
else:
return b
# Calling the function
num1 = 12
num2 = 15
result = find_max(num1, num2)
print("The maximum number is:", result)
Explanation:
यह function दो numbers a
और b
compare करता है और maximum value return करता है।
Example 4: Function to Convert Celsius to Fahrenheit
# Function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
# Calling the function
temp_in_celsius = 25
result = celsius_to_fahrenheit(temp_in_celsius)
print(f"{temp_in_celsius}°C is equal to {result}°F.")
Explanation:
यह function Celsius को Fahrenheit में convert करता है। Formula है: (Celsius * 9/5) + 32
.
Example 5: Function to Calculate Factorial of a Number
# Function to calculate factorial of a number
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Calling the function
num = 5
result = factorial(num)
print(f"The factorial of {num} is: {result}")
Explanation:
यह function recursive method का उपयोग करके किसी number का factorial calculate करता है। Factorial को n * (n-1) * (n-2) * ... * 1
के रूप में calculate किया जाता है।
इन सभी उदाहरणों में user-defined functions का उपयोग करके हम विभिन्न tasks को modular रूप में solve कर रहे हैं, जैसे area calculation, number checking, temperature conversion, आदि।
Part 3: Data और File Handling
यह अध्याय Python में Data Structures और उनके उपयोग को समझाता है। हम Lists, Tuples, Dictionaries, और Sets के बारे में विस्तार से चर्चा करेंगे।
1. Data Structures in Python (Python में डेटा संरचनाएँ)
Data Structures डेटा को संगठित और प्रबंधित करने के तरीके प्रदान करते हैं।
Python में मुख्यतः चार प्रकार के डेटा संरचनाएँ होती हैं:
- Lists
- Tuples
- Dictionaries
- Sets
2. Lists (लिस्ट्स)
List क्या है?
- एक Ordered और Mutable (परिवर्तनीय) डेटा संरचना।
- List में विभिन्न प्रकार के डेटा स्टोर किए जा सकते हैं।
- List को Square Brackets
[ ]
में Define किया जाता है।
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
List Operations:
-
Access Elements:
print(fruits[0]) # Output: apple print(fruits[-1]) # Output: cherry
-
Add Elements:
append()
: लिस्ट के अंत में जोड़ना।insert()
: किसी विशेष स्थान पर जोड़ना।
fruits.append("orange") fruits.insert(1, "grape") print(fruits)
-
Remove Elements:
remove()
: एक Specific Element को हटाना।pop()
: Index से हटाना।
fruits.remove("banana") fruits.pop(0) print(fruits)
-
List Slicing:
numbers = [0, 1, 2, 3, 4, 5] print(numbers[1:4]) # Output: [1, 2, 3]
3. Tuples (ट्यूपल्स)
Tuple क्या है?
- एक Ordered और Immutable (अपरिवर्तनीय) डेटा संरचना।
- Tuple को Parentheses
( )
में Define किया जाता है।
Example:
colors = ("red", "green", "blue")
print(colors) # Output: ('red', 'green', 'blue')
Tuple Operations:
-
Access Elements:
print(colors[0]) # Output: red print(colors[-1]) # Output: blue
-
Immutable Nature:
Tuple को Modify नहीं किया जा सकता।colors[0] = "yellow" # Error: 'tuple' object does not support item assignment
-
Unpacking:
(a, b, c) = colors print(a, b, c) # Output: red green blue
4. Dictionaries (डिक्शनरीज़)
Dictionary क्या है?
- Key-Value Pairs के रूप में डेटा को स्टोर करने वाली Unordered और Mutable संरचना।
- Dictionary को Curly Braces
{ }
में Define किया जाता है।
Example:
person = {"name": "Ajay", "age": 25, "city": "Patna"}
print(person) # Output: {'name': 'Ajay', 'age': 25, 'city': 'Patna'}
Dictionary Operations:
-
Access Values:
print(person["name"]) # Output: Ajay print(person.get("age")) # Output: 25
-
Add or Update Elements:
person["profession"] = "Teacher" person["age"] = 26 print(person)
-
Remove Elements:
pop()
: Key द्वारा Value को हटाना।clear()
: Dictionary को खाली करना।
person.pop("city") person.clear()
5. Sets (सेट्स)
Set क्या है?
- एक Unordered और Immutable (परिवर्तनीय लेकिन Unique Elements) डेटा संरचना।
- Set को Curly Braces
{ }
में Define किया जाता है।
Example:
numbers = {1, 2, 3, 3, 4}
print(numbers) # Output: {1, 2, 3, 4}
Set Operations:
-
Add Elements:
numbers.add(5) print(numbers) # Output: {1, 2, 3, 4, 5}
-
Remove Elements:
numbers.remove(2) print(numbers) # Output: {1, 3, 4, 5}
-
Set Operations (Union, Intersection, Difference):
set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1.union(set2)) # Output: {1, 2, 3, 4, 5} print(set1.intersection(set2)) # Output: {3} print(set1.difference(set2)) # Output: {1, 2}
Chapter Summary:
- Lists: Ordered और Mutable डेटा संरचना।
- Tuples: Ordered और Immutable डेटा संरचना।
- Dictionaries: Key-Value Pairs के रूप में डेटा स्टोर करते हैं।
- Sets: Unique Elements को स्टोर करने के लिए उपयोगी।
File Handling in Python
यह अध्याय Python में फ़ाइलों के साथ काम करने के बारे में है। हम देखेंगे कि कैसे हम Python का उपयोग करके Text Files को पढ़ सकते हैं और लिख सकते हैं, CSV (Comma-Separated Values) Files को कैसे हैंडल कर सकते हैं, और साथ ही Error Handling को समझेंगे ताकि फ़ाइलों के साथ काम करते समय उत्पन्न होने वाली समस्याओं से बचा जा सके।
1. Text Files पढ़ना और लिखना (Reading and Writing Text Files)
Python में फ़ाइलों को खोलने, पढ़ने और लिखने के लिए open() फ़ंक्शन का उपयोग किया जाता है। Python की open() फ़ंक्शन आपको किसी भी फ़ाइल को खोलने का मौका देता है, और फ़ाइल के मोड के आधार पर आप उसे पढ़ सकते हैं, लिख सकते हैं, या केवल खोल सकते हैं।
File Opening Modes:
- 'r': Read (पढ़ने के लिए)
- 'w': Write (लिखने के लिए)
- 'a': Append (जोड़ने के लिए)
- 'b': Binary mode (बाइनरी मोड)
- 'x': Exclusive creation (यदि फ़ाइल पहले से मौजूद है तो Error देगा)
Reading Text Files
जब आप किसी फ़ाइल को पढ़ना चाहते हैं, तो सबसे पहले आपको उसे खोलना होगा।
Example (Reading a File):
# File खोलना और पढ़ना
file = open("example.txt", "r") # "r" मतलब read mode
content = file.read() # पूरी फ़ाइल की सामग्री पढ़ें
print(content)
file.close() # फ़ाइल बंद करें
यह उदाहरण पूरी फ़ाइल को पढ़कर कंसोल पर दिखाएगा।
Writing to Text Files
यदि आप किसी फ़ाइल में डेटा लिखना चाहते हैं, तो आपको फ़ाइल को "write" या "append" मोड में खोलना होगा।
Example (Writing to a File):
# File खोलना और लिखना
file = open("example.txt", "w") # "w" मतलब write mode
file.write("Hello, this is a new line.") # फ़ाइल में डेटा लिखना
file.close() # फ़ाइल बंद करें
यदि फ़ाइल पहले से मौजूद है, तो "w" मोड उस फ़ाइल को ओवरराइट कर देगा।
Appending to Text Files
यदि आप फ़ाइल के अंत में डेटा जोड़ना चाहते हैं, तो आपको "a" मोड का उपयोग करना होगा।
Example (Appending to a File):
# File खोलना और डेटा जोड़ना
file = open("example.txt", "a") # "a" मतलब append mode
file.write("\nThis is an appended line.") # फ़ाइल के अंत में डेटा जोड़ना
file.close() # फ़ाइल बंद करें
2. CSV Files का उपयोग (Working with CSV Files)
CSV (Comma-Separated Values) फ़ाइलें एक लोकप्रिय तरीका हैं डेटा को स्टोर करने का, खासकर टेबल के रूप में। Python में CSV फ़ाइलों के साथ काम करने के लिए csv मॉड्यूल का उपयोग किया जाता है।
CSV File को पढ़ना
CSV फ़ाइल को पढ़ने के लिए, आप csv.reader()
का उपयोग कर सकते हैं।
Example (Reading a CSV File):
import csv
# CSV फ़ाइल को पढ़ना
with open("data.csv", mode="r") as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row) # हर पंक्ति को प्रिंट करना
CSV File में लिखना
CSV फ़ाइल में डेटा लिखने के लिए, आप csv.writer()
का उपयोग कर सकते हैं।
Example (Writing to a CSV File):
import csv
# CSV फ़ाइल में लिखना
with open("data.csv", mode="w", newline="") as file:
csv_writer = csv.writer(file)
csv_writer.writerow(["Name", "Age", "City"]) # Header Row
csv_writer.writerow(["Ajay", 25, "Patna"]) # Data Row
3. Error Handling (एरर हैंडलिंग)
फ़ाइल ऑपरेशंस करते समय अक्सर एरर हो सकते हैं, जैसे फ़ाइल का मौजूद न होना, फ़ाइल को पढ़ने में समस्या, या डेटा लिखने के दौरान कोई समस्या आना। ऐसे मामलों में error handling बेहद महत्वपूर्ण होती है। Python में try, except और finally ब्लॉक्स का उपयोग करके हम एरर को हैंडल कर सकते हैं।
Basic Error Handling:
- try: कोड का वह हिस्सा जिसमें संभावित एरर हो सकती है।
- except: एरर आने पर उसे पकड़ने और हैंडल करने के लिए।
- finally: यह ब्लॉक हमेशा execute होगा, चाहे एरर हो या न हो।
Example (Error Handling in File Operations):
try:
file = open("example.txt", "r") # File को पढ़ने का प्रयास
content = file.read()
print(content)
except FileNotFoundError: # यदि फ़ाइल नहीं मिली
print("Error: File not found.")
except Exception as e: # अन्य सामान्य Errors
print(f"An error occurred: {e}")
finally:
try:
file.close() # फ़ाइल को बंद करना
except:
pass # यदि फ़ाइल खुली नहीं थी तो कोई समस्या नहीं है
Chapter Summary:
- File Handling Python में फ़ाइलों के साथ काम करने के लिए एक शक्तिशाली तरीका है।
- Text Files को पढ़ने और लिखने के लिए
open()
फ़ंक्शन का उपयोग किया जाता है। - CSV Files को Python में पढ़ने और लिखने के लिए
csv
मॉड्यूल का उपयोग करें। - Error Handling फ़ाइल ऑपरेशंस के दौरान उत्पन्न होने वाली समस्याओं को ठीक से हैंडल करने के लिए महत्वपूर्ण है।
Part 4: Python Libraries और Modules
Python में Libraries और Modules का महत्वपूर्ण स्थान है। वे Python प्रोग्रामिंग के कार्यक्षेत्र को बहुत सरल और प्रभावी बनाते हैं। Python की विभिन्न Libraries और Modules का उपयोग करके हम अपने प्रोग्राम को और अधिक शक्तिशाली और प्रभावी बना सकते हैं। इस अध्याय में हम Python Libraries, Modules और उनके लोकप्रिय उदाहरणों पर चर्चा करेंगे, जैसे कि NumPy, Pandas, और Matplotlib।
1. Working with Python Libraries
Python Libraries और Modules प्रोग्रामिंग को और अधिक आसान और तेज बनाते हैं। Library एक कलेक्शन होती है कई कोड्स की, जो हम अपने प्रोग्राम में उपयोग कर सकते हैं, ताकि हमें हर बार उन्हीं कोड्स को फिर से लिखने की आवश्यकता न पड़े। Library का उपयोग करने के लिए, हम उन्हें अपने प्रोग्राम में import करते हैं।
Library को import करना:
import library_name
Example:
import math # math library का उपयोग
result = math.sqrt(16) # 16 का square root निकालना
print(result)
जब हम किसी लाइब्रेरी को इम्पोर्ट करते हैं, तो हम उसे अपने प्रोग्राम में इस्तेमाल कर सकते हैं। Python में कई इनबिल्ट Libraries हैं, जैसे math, os, sys, time, datetime, आदि।
2. Libraries का परिचय (Introduction to Python Libraries)
Python में Libraries और Modules कई प्रकार के होते हैं। Libraries वो सेट होती हैं जिनमें कई predefined functions होते हैं जिन्हें हम आसानी से अपने प्रोग्राम में इस्तेमाल कर सकते हैं। Python के पास बहुत सारी Libraries हैं, जो विभिन्न कार्यों के लिए होती हैं। उदाहरण के लिए:
- NumPy: Numerical computing के लिए।
- Pandas: Data analysis और data manipulation के लिए।
- Matplotlib: Data visualization के लिए।
- Requests: HTTP requests भेजने के लिए।
- SciPy: Scientific computing के लिए।
इन Libraries को Python में इम्पोर्ट करना बहुत आसान है, बस import
keyword का इस्तेमाल करें।
3. Popular Libraries (NumPy, Pandas, Matplotlib)
a. NumPy
NumPy (Numerical Python) एक powerful library है जो numerical operations को efficiently करने के लिए उपयोग की जाती है। यह multi-dimensional arrays और matrices के साथ काम करने के लिए specialized है और mathematical functions प्रदान करती है। NumPy का उपयोग खासतौर पर large data sets और scientific computations में होता है।
NumPy का उपयोग:
import numpy as np
# NumPy array बनाना
arr = np.array([1, 2, 3, 4, 5])
# Array के elements पर mathematical operations करना
sum_arr = np.sum(arr)
print(sum_arr) # Output: 15
Key Features of NumPy:
- Efficient multi-dimensional arrays (ndarray)
- Mathematical functions (like sum, mean, etc.)
- Broadcasting (Arrays को अलग-अलग आकारों में combine करना)
- Linear algebra operations
b. Pandas
Pandas एक powerful library है जो data manipulation और analysis के लिए उपयोग की जाती है। Pandas में DataFrame और Series नामक डेटा structures होते हैं, जो tabular data को handle करने के लिए ideal होते हैं। Pandas का उपयोग CSV, Excel, SQL databases, और अन्य file formats से data import/export करने के लिए भी किया जाता है।
Pandas का उपयोग:
import pandas as pd
# DataFrame बनाना
data = {'Name': ['Ajay', 'Neha', 'Mahi'], 'Age': [25, 28, 22]}
df = pd.DataFrame(data)
# DataFrame को print करना
print(df)
Key Features of Pandas:
- DataFrame और Series data structures
- Data filtering, sorting और aggregation
- CSV, Excel, और अन्य file formats से data पढ़ना और लिखना
- Missing data को handle करना
c. Matplotlib
Matplotlib एक powerful data visualization library है जो charts और graphs बनाने के लिए उपयोग की जाती है। Matplotlib का उपयोग करके हम data का graphical representation प्राप्त कर सकते हैं, जो कि data analysis को समझने में मदद करता है। यह line plots, bar charts, histograms, pie charts, scatter plots आदि बनाने में सक्षम है।
Matplotlib का उपयोग:
import matplotlib.pyplot as plt
# Line plot बनाना
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 35]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Key Features of Matplotlib:
- Line plots, scatter plots, bar charts, histograms, pie charts, etc.
- Customization options (like title, axis labels, grid, etc.)
- Subplots (multiple plots in one figure)
- Saving plots as image files (e.g., PNG, JPG)
4. Installing Python Libraries
Python में Libraries को install करने के लिए Python Package Index (PyPI) से pip (Python Package Installer) का उपयोग किया जाता है। Pip के माध्यम से हम किसी भी external library को आसानी से install कर सकते हैं।
Library Install करना (Using pip):
pip install library_name
Example:
pip install numpy
5. Using Libraries and Modules Together
Python में आप एक से ज्यादा Libraries को combine कर सकते हैं। यह एक शक्तिशाली तरीका है जो आपके प्रोग्राम की कार्यक्षमता को बढ़ा सकता है।
Example (Using NumPy and Matplotlib together):
import numpy as np
import matplotlib.pyplot as plt
# NumPy array
x = np.linspace(0, 10, 100)
# Sine wave calculation
y = np.sin(x)
# Plotting the sine wave
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Chapter Summary:
- Python Libraries pre-written code का collection होते हैं जिन्हें हम आसानी से import करके अपने प्रोग्राम में उपयोग कर सकते हैं।
- NumPy numerical computations के लिए एक महत्वपूर्ण library है, जो multi-dimensional arrays और matrices पर काम करने में मदद करता है।
- Pandas data manipulation और analysis के लिए है, खासकर tabular data के साथ काम करने के लिए।
- Matplotlib data visualization के लिए एक library है, जो graphs और charts को बनाने के लिए प्रयोग की जाती है।
- Python Libraries और Modules का प्रयोग करके हम अपनी Python प्रोग्रामिंग को बहुत अधिक प्रभावी और आसान बना सकते हैं।
Chapter: Modules and Packages in Python
Python में Modules और Packages प्रोग्रामिंग के विभिन्न पहलुओं को modularize करने का एक तरीका प्रदान करते हैं, जिससे हम अपने कोड को reusable और organized तरीके से लिख सकते हैं। Modules और Packages का उपयोग करके हम अपने प्रोग्राम को छोटे-छोटे हिस्सों में बाँट सकते हैं और फिर उन्हें आसानी से import कर सकते हैं। इस अध्याय में हम Python Modules और Packages के बारे में विस्तार से जानेंगे, साथ ही User-defined Modules और External Libraries को भी समझेंगे।
1. Python Modules
Modules Python में एक file होती है, जिसमें Python code होता है। Module में functions, variables, classes और runnable code हो सकते हैं। Python modules का मुख्य उद्देश्य code को organize करना और reuse करना है।
Python में दो तरह के modules होते हैं:
- Built-in Modules: ये Python के साथ आते हैं, और इन्हें आसानी से import किया जा सकता है।
- User-defined Modules: ये वो modules होते हैं, जिन्हें हम खुद बनाते हैं।
Python Module को Import करना:
जब भी हमें किसी module की functionalities को अपने प्रोग्राम में उपयोग करना हो, तो हम उसे import करते हैं। Python में module import करने के लिए हम import
keyword का इस्तेमाल करते हैं।
Example:
import math
# math module का इस्तेमाल करके square root निकालना
result = math.sqrt(16)
print(result) # Output: 4.0
यहाँ math
एक built-in module है, जिसका इस्तेमाल हम mathematical operations के लिए कर रहे हैं।
Common Built-in Python Modules:
math
: Mathematical operationsdatetime
: Date और time manipulationos
: Operating system related functionalityrandom
: Random numbers और selections के लिएsys
: System-specific parameters और functions
2. User-defined Modules
Python में आप खुद भी modules बना सकते हैं। User-defined modules में आप functions, classes और variables define कर सकते हैं, जिन्हें फिर दूसरे Python programs में import किया जा सकता है।
User-defined Module बनाना:
मान लीजिए हम एक module बनाना चाहते हैं, जिसका नाम my_module.py
है, और उसमें एक simple function greet()
है। इसे हम इस प्रकार बनाएंगे:
my_module.py (User-defined Module)
def greet(name):
print(f"Hello, {name}!")
अब इस module को किसी दूसरे Python program में import कर सकते हैं:
import my_module
# greet() function को call करना
my_module.greet("Ajay")
Output:
Hello, Ajay!
यहां हमने my_module.py
नामक file बनाई, जिसमें greet()
function था, और फिर उसे दूसरे प्रोग्राम में import करके इस्तेमाल किया।
3. Installing External Libraries (pip का उपयोग)
Python में बहुत सारी external libraries और modules उपलब्ध हैं, जिनका उपयोग हम अपने प्रोग्राम में कर सकते हैं। इन libraries को install करने के लिए Python में pip (Python Package Installer) का इस्तेमाल किया जाता है। Pip एक command-line tool है, जो हमें Python packages को आसानी से install करने, update करने और manage करने की सुविधा प्रदान करता है।
External Libraries का Install करना:
Python में किसी भी external library को install करने के लिए pip का उपयोग किया जाता है। उदाहरण के लिए, यदि हमें requests
नामक library को install करना है, तो हम नीचे दिए गए command का इस्तेमाल कर सकते हैं:
Command:
pip install requests
यह command requests
library को Python environment में install कर देगी।
Library Install करना (Step by Step):
- Command prompt या terminal खोलें।
- निम्नलिखित command टाइप करें:
pip install library_name
- Installation complete होने पर, आप उस library को import कर सकते हैं और उसका उपयोग कर सकते हैं।
Example (requests library का उपयोग):
import requests
response = requests.get("https://www.example.com")
print(response.status_code)
Output:
200
यहां requests
library का उपयोग HTTP requests भेजने के लिए किया गया है।
Commonly Used External Libraries:
- NumPy: Numerical computations के लिए।
- Pandas: Data analysis और manipulation के लिए।
- Matplotlib: Data visualization के लिए।
- Requests: HTTP requests भेजने के लिए।
- BeautifulSoup: Web scraping के लिए।
4. Packages in Python
Packages Python में एक directory होती है, जिसमें multiple modules होते हैं। Package का उद्देश्य modules को logically organize करना होता है। एक Python package में एक __init__.py
file होती है, जो उस directory को Python package के रूप में पहचान दिलाती है।
Package का Structure:
my_package/
__init__.py
module1.py
module2.py
अब, हम इन modules को अपने प्रोग्राम में import कर सकते हैं:
from my_package import module1
module1.some_function()
Example:
मान लीजिए हमारे पास एक package है math_operations
नाम से, जिसमें दो modules हैं: addition.py
और subtraction.py
।
math_operations/addition.py:
def add(a, b):
return a + b
math_operations/subtraction.py:
def subtract(a, b):
return a - b
अब, हम इस package के modules को import कर सकते हैं:
from math_operations import addition
from math_operations import subtraction
print(addition.add(5, 3)) # Output: 8
print(subtraction.subtract(5, 3)) # Output: 2
5. Summary
- Python Modules वह files होती हैं, जिनमें Python code होता है। इन्हें हम import करके अपने प्रोग्राम में reuse कर सकते हैं।
- User-defined Modules वह modules होती हैं, जिन्हें हम खुद बनाते हैं और इन्हें दूसरे प्रोग्रामों में import कर सकते हैं।
- pip का उपयोग external Python libraries को install करने के लिए किया जाता है, जिससे हम Python ecosystem में उपलब्ध हजारों libraries का उपयोग कर सकते हैं।
- Packages modules का collection होते हैं और इन्हें directory के रूप में organize किया जाता है। Packages को import करने से हमें related modules को एक साथ उपयोग करने की सुविधा मिलती है।
Chapter: Object-Oriented Programming (OOP) in Python
Object-Oriented Programming (OOP) Python में एक प्रोग्रामिंग पैराडाइम है, जिसका उद्देश्य code को reusable और structured तरीके से लिखना है। OOP के माध्यम से हम अपने प्रोग्राम को objects और classes में बाँट सकते हैं, जिससे code maintainable और extendable होता है। Python में OOP के मुख्य concepts हैं: Classes, Objects, Inheritance, Polymorphism, और Encapsulation। इस अध्याय में हम इन सभी concepts को विस्तार से समझेंगे।
1. Object-Oriented Concepts in Python
Object-Oriented Programming में objects और classes की मदद से code को एक structured रूप में organize किया जाता है। Python OOP में 4 प्रमुख concepts होते हैं:
- Classes और Objects
- Inheritance
- Polymorphism
- Encapsulation
इन concepts को समझने से पहले, हमें यह जानना जरूरी है कि Python में classes और objects कैसे काम करते हैं।
2. Classes और Objects
Class एक blueprint होती है, जिसमें attributes (variables) और methods (functions) होते हैं, जो किसी object की properties और behavior को define करते हैं। Object एक instance होती है जो class के attributes और methods को use करती है।
Class का Syntax:
class MyClass:
# Constructor
def __init__(self, name, age):
self.name = name # instance variable
self.age = age # instance variable
# Method
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Object Creation
obj = MyClass("Ajay", 25)
obj.greet() # Output: Hello, my name is Ajay and I am 25 years old.
Explanation:
class MyClass
: यहांMyClass
नाम की एक class बनाई गई है।__init__()
: यह constructor है, जो object के initialize होने के समय automatic call होता है।self
: यह keyword instance को refer करता है, जिससे हम instance variables और methods को access करते हैं।obj.greet()
: यह method call करता है, जो instance object के द्वारा define की गई behavior को execute करता है।
3. Inheritance
Inheritance एक OOP concept है, जिससे एक class (child class) दूसरी class (parent class) से attributes और methods को inherit करती है। इससे code reuse होता है और hierarchy बनाई जा सकती है।
Inheritance का Example:
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
# Child Class (Inheritance)
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Parent class constructor को call करना
self.breed = breed
def speak(self): # Method Overriding
print(f"{self.name} barks.")
# Object Creation
dog = Dog("Buddy", "Golden Retriever")
dog.speak() # Output: Buddy barks.
Explanation:
Animal
class एक parent class है, जिसमेंspeak()
method है।Dog
classAnimal
class से inherit करती है।super()
keyword का उपयोग parent class की constructor को call करने के लिए किया जाता है।speak()
method को override किया गया है, जिससे child class में customized behavior मिलता है।
4. Polymorphism
Polymorphism का मतलब है "many forms". यह concept OOP में एक method या operator के multiple forms होने को refer करता है। Polymorphism का प्रमुख उद्देश्य same method का अलग-अलग objects पर अलग-अलग behavior होना है। इसे method overloading और method overriding के माध्यम से achieve किया जाता है।
Polymorphism का Example:
# Polymorphism with Method Overriding
class Animal:
def speak(self):
print("Animal makes a sound.")
class Dog(Animal):
def speak(self):
print("Dog barks.")
class Cat(Animal):
def speak(self):
print("Cat meows.")
# Polymorphism in Action
def animal_sound(animal):
animal.speak()
dog = Dog()
cat = Cat()
animal_sound(dog) # Output: Dog barks.
animal_sound(cat) # Output: Cat meows.
Explanation:
Dog
औरCat
class मेंspeak()
method override किया गया है।animal_sound()
function polymorphism का उपयोग करता है। अलग-अलग objects के लिएspeak()
method को अलग-अलग तरीके से call किया जाता है, जिससे behavior change होता है।
5. Encapsulation
Encapsulation का मतलब है data और functions को एक unit में encapsulate करना। इसे हम data hiding भी कहते हैं, क्योंकि encapsulation से हम class के internal details को बाहर से hide कर सकते हैं और केवल essential methods को accessible बना सकते हैं। Encapsulation से class का data secure रहता है।
Encapsulation का Example:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def deposit(self, amount):
if amount > 0:
self.__balance += amount
else:
print("Invalid deposit amount.")
def get_balance(self):
return self.__balance
# Object Creation
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500
# Attempting to access private variable
# print(account.__balance) # Error: AttributeError
Explanation:
__balance
को private variable बनाया गया है, जिससे इसे class के बाहर से directly access नहीं किया जा सकता।deposit()
औरget_balance()
methods का उपयोग करके हम balance को modify और access कर सकते हैं।__balance
को directly access करने की कोशिश करने पर error आएगा, जिससे encapsulation की सुरक्षा बनी रहती है।
6. Summary
- Classes और Objects: Classes, objects का blueprint होती हैं, जिनके माध्यम से हम अपने प्रोग्राम को organize करते हैं।
- Inheritance: Inheritance की मदद से हम एक class (child class) को दूसरी class (parent class) से attributes और methods inherit कर सकते हैं, जिससे code reuse होता है।
- Polymorphism: Polymorphism से एक ही method का different objects पर different behavior होता है, जिससे flexible और dynamic programming संभव होती है।
- Encapsulation: Encapsulation का उद्देश्य data को hide करना और class की internal implementation को outside से inaccessible बनाना है।
Chapter: Advanced Python Concepts – Working with Regular Expressions
Python में Regular Expressions (RegEx) एक powerful tool है, जो text processing में इस्तेमाल होता है। Regular expressions का उपयोग pattern matching के लिए किया जाता है, जिससे हम strings को search, match और manipulate कर सकते हैं। इस chapter में हम Regular Expressions के basic concepts, syntax और practical examples को समझेंगे।
1. Regular Expressions का परिचय
Regular Expression (RegEx) एक special sequence of characters होता है, जिसे हम text search और pattern matching के लिए use करते हैं। यह pattern matching के लिए बहुत ही efficient और flexible तरीका है, जो विशेष रूप से तब useful होता है जब हमें string में complex patterns की पहचान करनी हो।
Python में re
module के माध्यम से हम Regular Expressions का उपयोग करते हैं। यह module हमें patterns को define करने, strings को match करने, और replace करने के लिए कई useful functions प्रदान करता है।
RegEx का Syntax:
Regular Expression में कुछ special characters होते हैं जो specific meanings रखते हैं। इन्हें pattern matching के लिए उपयोग किया जाता है।
.
(Dot): कोई भी single character को match करता है।^
: string के शुरू में match करने के लिए।$
: string के अंत में match करने के लिए।[]
(Square brackets): किसी भी एक character के set से match करता है।*
: zero या more repetitions को match करता है।+
: one या more repetitions को match करता है।?
: zero या one repetition को match करता है।\d
: किसी भी digit (0-9) को match करता है।\w
: word character (letters, digits, and underscore) को match करता है।\s
: whitespace character (spaces, tabs, newlines) को match करता है।
2. Search और Match Functions
Python के re
module में कई functions होते हैं, जिनका उपयोग हम Regular Expressions से text search और manipulation के लिए करते हैं। सबसे common functions हैं search()
, match()
, findall()
, और sub()
।
re.search()
Function
search()
function एक pattern को string में खोजता है और सबसे पहली occurrence को return करता है। अगर pattern मिल जाता है तो यह एक match object return करता है, और अगर pattern नहीं मिलता तो यह None
return करता है।
import re
# Example of re.search()
pattern = r"\d+" # Pattern to match one or more digits
string = "My phone number is 12345."
result = re.search(pattern, string)
if result:
print("Pattern found:", result.group()) # Output: Pattern found: 12345
else:
print("Pattern not found.")
Explanation:
\d+
pattern का मतलब है "एक या अधिक digits match करो"।re.search()
function ने सबसे पहले found match को return किया, जो कि 12345 था।
re.match()
Function
match()
function string के start से pattern match करने की कोशिश करता है। अगर pattern string के शुरुआत में match करता है तो यह match object return करता है, वरना None
return करता है।
import re
# Example of re.match()
pattern = r"\d+" # Pattern to match one or more digits
string = "12345 is my phone number."
result = re.match(pattern, string)
if result:
print("Pattern found:", result.group()) # Output: Pattern found: 12345
else:
print("Pattern not found.")
Explanation:
re.match()
function ने string के beginning से pattern match किया और "12345" को match किया।- अगर pattern string के start में नहीं होता तो result
None
होता।
re.findall()
Function
findall()
function string में पूरे pattern के सभी matches को list के रूप में return करता है।
import re
# Example of re.findall()
pattern = r"\d+" # Pattern to match one or more digits
string = "My phone numbers are 12345 and 67890."
result = re.findall(pattern, string)
print("All matches:", result) # Output: All matches: ['12345', '67890']
Explanation:
re.findall()
ने string में सभी matches (12345 और 67890) को return किया।- यह function सभी matched substrings को list के रूप में return करता है।
re.sub()
Function
sub()
function का उपयोग pattern को किसी अन्य string से replace करने के लिए किया जाता है। यह pattern matched portion को replace करके एक नया string return करता है।
import re
# Example of re.sub()
pattern = r"\d+" # Pattern to match one or more digits
string = "My phone number is 12345."
# Replacing digits with 'XXXXX'
result = re.sub(pattern, "XXXXX", string)
print("Modified string:", result) # Output: Modified string: My phone number is XXXXX.
Explanation:
re.sub()
ने string में digits (12345) को replace करके 'XXXXX' कर दिया।- यह method pattern matched portion को replace करने के लिए use होता है।
3. Regular Expression Examples
Example 1: Valid Email Address Validation
Email address को validate करने के लिए regular expression का उपयोग किया जा सकता है। नीचे एक example है:
import re
# Regular expression for validating email
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
email = "example@example.com"
if re.match(pattern, email):
print("Valid email address")
else:
print("Invalid email address")
Explanation:
^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$
यह pattern valid email address के लिए है।re.match()
function email address की validity को check करता है।
Example 2: Phone Number Extraction
Phone number को extract करने के लिए Regular Expression का उपयोग किया जा सकता है:
import re
# Regular expression for extracting phone numbers
pattern = r"\d{10}" # Matches a 10-digit phone number
string = "Contact me at 1234567890 or 9876543210."
phone_numbers = re.findall(pattern, string)
print("Extracted phone numbers:", phone_numbers) # Output: Extracted phone numbers: ['1234567890', '9876543210']
Explanation:
\d{10}
pattern एक 10-digit phone number को match करता है।re.findall()
function ने string से phone numbers को extract किया।
4. Summary
- Regular Expressions (RegEx): एक powerful tool है जो text search, match और manipulation के लिए use होता है।
- re.search(): pattern को string में search करता है और पहली match को return करता है।
- re.match(): pattern को string के start से match करता है।
- re.findall(): string में सभी matches को list के रूप में return करता है।
- re.sub(): pattern को replace करके नया string return करता है।
Chapter: Error और Exception Handling in Python
Python में Error और Exception Handling महत्वपूर्ण concepts हैं जो हमें प्रोग्राम के रन टाइम में उत्पन्न होने वाली समस्याओं (errors) को संभालने में मदद करते हैं। किसी भी प्रोग्राम में errors होना सामान्य बात है, लेकिन इन errors को सही तरीके से handle करना ज़रूरी होता है ताकि program crash न हो और user को सही तरीके से error message मिले। Python में exception handling के लिए try
, except
, और finally
blocks का उपयोग किया जाता है।
1. Error और Exception क्या हैं?
-
Error: Error ऐसी समस्याएँ हैं जो प्रोग्राम के execution में रुकावट डालती हैं और प्रोग्राम को सही तरीके से चलने नहीं देतीं। Errors दो प्रकार के होते हैं:
- Syntax Errors: ये errors तब होते हैं जब हम code लिखने में कोई गलती करते हैं जैसे कि गलत punctuation, braces की कमी, आदि।
- Runtime Errors: ये errors तब होते हैं जब प्रोग्राम रन हो रहा होता है, जैसे कि division by zero, file not found, etc.
-
Exception: Exception किसी unexpected event को कहते हैं जो program के execution के दौरान आता है। Exception handling का उद्देश्य errors और exceptions को ठीक से handle करना होता है ताकि program crash न हो और error को gracefully handle किया जा सके। Exceptions runtime errors से अलग होते हैं क्योंकि exceptions को explicitly handle किया जा सकता है।
2. Try, Except और Finally Blocks
Python में exception handling के लिए try
, except
, और finally
blocks का उपयोग किया जाता है। इनका मुख्य उद्देश्य errors को gracefully handle करना और program को crash होने से बचाना होता है।
try
Block
try
block में वह code रखा जाता है जिसे execute करते समय exception आ सकता है। अगर try block में कोई exception होता है, तो control तुरंत except block को transfer कर दिया जाता है।
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except
Block
except
block उस exception को handle करता है जो try block में उत्पन्न होता है। अगर exception match करता है, तो except block execute होता है। एक try block में एक से अधिक except block भी हो सकते हैं।
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input, please enter a valid number.")
Explanation:
- यदि
num2
0 होगा, तोZeroDivisionError
exception आएगा औरexcept ZeroDivisionError
block execute होगा। - यदि input value invalid होगी, तो
ValueError
exception आएगा औरexcept ValueError
block execute होगा।
finally
Block
finally
block हमेशा execute होता है, चाहे exception हो या न हो। यह clean-up tasks जैसे कि file closing, database connection closing आदि के लिए उपयोग किया जाता है।
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
finally:
print("Execution finished.")
Explanation:
- चाहे exception हो या न हो,
finally
block हमेशा execute होगा।
3. Catch Multiple Exceptions
Python में एक try block में कई अलग-अलग exceptions को handle करने के लिए multiple except
blocks का उपयोग किया जा सकता है।
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input, please enter a valid number.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Explanation:
- यदि exception match नहीं होता, तो
Exception
block catch करेगा और error message print करेगा।
4. Custom Exceptions
Python में आप अपनी custom exceptions भी बना सकते हैं, जिन्हें आप अपने specific error conditions के लिए define कर सकते हैं। Custom exceptions को एक class के रूप में define किया जाता है, जो Python की built-in Exception
class से inherit होती है।
Custom Exception Class
class NegativeNumberError(Exception):
def __init__(self, message="Negative numbers are not allowed!"):
self.message = message
super().__init__(self.message)
def calculate_square_root(number):
if number < 0:
raise NegativeNumberError("Square root of negative numbers is not possible!")
return number ** 0.5
try:
num = int(input("Enter a number: "))
print("Square Root:", calculate_square_root(num))
except NegativeNumberError as e:
print(e)
Explanation:
NegativeNumberError
एक custom exception है, जो negative number के input पर raised होता है।calculate_square_root()
function में अगर negative number दिया जाता है तो custom exception raise किया जाता है।
Raising Exceptions
Custom exception को raise करने के लिए raise
keyword का उपयोग किया जाता है।
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18.")
print("Age is valid.")
try:
check_age(16)
except ValueError as e:
print("Error:", e)
Explanation:
check_age()
function मेंValueError
exception manually raise किया गया है जब age 18 से कम हो।
5. Exception Handling Best Practices
- Specific Exceptions: Always try to handle specific exceptions rather than using a generic
except
block. इससे आपको error के बारे में ज्यादा जानकारी मिलती है और debugging आसान होती है। - Log Errors: Exceptions को log करने के लिए logging module का use करें ताकि future में debugging आसान हो।
- Avoid Bare
except
:except:
का इस्तेमाल न करें, क्योंकि यह सभी types के exceptions को catch करता है और debugging में समस्या उत्पन्न कर सकता है।
6. Summary
- Error: ऐसे issues जो program के execution को रोकते हैं, जैसे syntax errors और runtime errors।
- Exception: Unexpected issues जो runtime में उत्पन्न होते हैं, जिन्हें handle किया जा सकता है।
- Try Block: Code जो exception throw कर सकता है, उसे try block में रखा जाता है।
- Except Block: Exception को handle करने के लिए except block का उपयोग किया जाता है।
- Finally Block: यह block हमेशा execute होता है, चाहे exception हो या न हो।
- Custom Exceptions: Python में custom exceptions define किए जा सकते हैं जो program के specific error conditions को handle करते हैं।
Chapter: Part 7: Python for Real-World Applications
Python की विशेषता है कि यह विभिन्न प्रकार की समस्याओं को हल करने में सक्षम है। इसे सिर्फ सॉफ़्टवेयर डेवलपमेंट तक सीमित नहीं रखा जा सकता, बल्कि यह डाटा साइंस, वेब डेवलपमेंट, ऑटोमेशन, और बहुत से अन्य क्षेत्रों में भी उपयोगी है। इस अध्याय में, हम Python के कुछ महत्वपूर्ण real-world applications को देखेंगे, जैसे कि Data Analysis और Data Visualization, जो खासतौर पर Pandas और Matplotlib जैसी libraries का उपयोग करते हैं।
1. Python for Data Analysis
Data Analysis एक महत्वपूर्ण क्षेत्र है, खासतौर पर उन professionals के लिए जो बड़ी मात्रा में डाटा को समझने और उसका विश्लेषण करने के लिए काम करते हैं। Python के पास डेटा विश्लेषण के लिए कई शक्तिशाली tools और libraries हैं, जिनका उपयोग business, research, और data science applications में किया जाता है। Python के साथ डेटा विश्लेषण करना आसान और प्रभावी है क्योंकि इसकी libraries और modules के साथ हम बड़े डेटा सेट्स को बहुत जल्दी और प्रभावी रूप से analyze कर सकते हैं।
Key Libraries for Data Analysis in Python:
- NumPy: Numerical computing के लिए उपयोगी, यह array और matrix operations को आसान बनाता है।
- Pandas: Data manipulation और analysis के लिए powerful library है।
- Matplotlib: Data visualization के लिए उपयोगी library है।
2. Introduction to Pandas
Pandas एक powerful library है जो data manipulation और analysis के लिए इस्तेमाल होती है। यह मुख्य रूप से structured data, जैसे कि tables या spreadsheets को handle करता है। Pandas डेटा को दो मुख्य structures के माध्यम से handle करता है:
- Series: एक dimensional data structure, जो lists की तरह होता है।
- DataFrame: दो dimensional data structure, जो rows और columns से मिलकर बना होता है। यह Excel sheets या SQL tables के समान होता है।
Pandas Installation:
Pandas को इंस्टॉल करने के लिए, आपको नीचे दिए गए command का उपयोग करना होगा:
pip install pandas
Basic Pandas Operations:
- DataFrame Creation: Pandas में DataFrame बनाने के लिए आप dictionary, list, या numpy array का उपयोग कर सकते हैं।
import pandas as pd
# Create a DataFrame
data = {
'Name': ['Ajay', 'Neha', 'Mahi'],
'Age': [25, 24, 20],
'City': ['Patna', 'Delhi', 'Mumbai']
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 Ajay 25 Patna
1 Neha 24 Delhi
2 Mahi 20 Mumbai
- Reading and Writing Data: Pandas में डेटा को CSV, Excel, और अन्य formats में read और write किया जा सकता है।
# Reading a CSV file
df = pd.read_csv('file.csv')
# Writing a DataFrame to a CSV file
df.to_csv('output.csv', index=False)
3. Data Manipulation with Pandas
Pandas में डेटा को manipulate करने के कई तरीके हैं। इसमें filtering, sorting, grouping, merging, और aggregating जैसी operations शामिल हैं।
Filtering Data
आप DataFrame से specific data filter करने के लिए conditions apply कर सकते हैं:
# Filter data where age is greater than 22
filtered_data = df[df['Age'] > 22]
print(filtered_data)
Sorting Data
Pandas में डेटा को sort करने के लिए sort_values()
method का उपयोग किया जाता है:
# Sort the DataFrame by Age
sorted_df = df.sort_values(by='Age', ascending=False)
print(sorted_df)
Group by Operation
Group by operation का उपयोग एक विशेष column के आधार पर डेटा को groups में विभाजित करने के लिए किया जाता है:
# Group by city and calculate average age
grouped_data = df.groupby('City')['Age'].mean()
print(grouped_data)
Merging DataFrames
Pandas में कई DataFrames को merge करने के लिए merge()
function का इस्तेमाल किया जाता है:
df1 = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['Ajay', 'Neha', 'Mahi']})
df2 = pd.DataFrame({'ID': [1, 2, 3], 'Age': [25, 24, 20]})
merged_df = pd.merge(df1, df2, on='ID')
print(merged_df)
4. Data Visualization with Matplotlib
Data visualization के लिए Matplotlib एक प्रमुख library है जो Python में charts और graphs बनाने के लिए उपयोग की जाती है। Data visualization से डेटा को एक आसान और प्रभावी तरीके से समझा जा सकता है।
Matplotlib Installation:
Matplotlib को इंस्टॉल करने के लिए नीचे दिए गए command का उपयोग करें:
pip install matplotlib
Basic Plotting with Matplotlib
Matplotlib का उपयोग करके हम line charts, bar charts, scatter plots, और अन्य types के graphs बना सकते हैं।
import matplotlib.pyplot as plt
# Simple Line Plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.show()
Explanation:
plt.plot(x, y)
line plot बनाता है।plt.xlabel()
औरplt.ylabel()
axis labels set करते हैं।plt.title()
plot का title set करता है।plt.show()
plot को display करता है।
Bar Chart Example
Bar charts का उपयोग categorical data को visualize करने के लिए किया जाता है:
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 2, 5]
plt.bar(categories, values)
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart Example')
plt.show()
Pie Chart Example
Pie charts का उपयोग percentage distribution को दर्शाने के लिए किया जाता है:
labels = ['Python', 'Java', 'C', 'JavaScript']
sizes = [50, 30, 10, 10]
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Programming Language Popularity')
plt.show()
Scatter Plot Example
Scatter plot का उपयोग data points के बीच relationships को visualise करने के लिए किया जाता है:
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot Example')
plt.show()
5. Summary
- Pandas: Python में data analysis के लिए सबसे ज्यादा इस्तेमाल होने वाली library है। इसका उपयोग data manipulation, cleaning, और analysis के लिए किया जाता है।
- DataFrames: Pandas में डेटा को DataFrames के रूप में manage किया जाता है जो rows और columns से मिलकर बने होते हैं।
- Matplotlib: Data visualization के लिए एक महत्वपूर्ण library है। इसके माध्यम से हम charts और graphs बना सकते हैं।
- Data Manipulation: Pandas के माध्यम से हम data को filter, sort, group, और merge कर सकते हैं।
- Plotting: Matplotlib का उपयोग line plots, bar charts, pie charts, और scatter plots बनाने के लिए किया जाता है
Chapter: Python for Web Development
Python, एक शक्तिशाली और सरल प्रोग्रामिंग भाषा, का उपयोग न केवल डेटा साइंस और मशीन लर्निंग में किया जाता है, बल्कि वेब डेवलपमेंट में भी इसे काफी लोकप्रियता मिली है। Python के पास कई वेब फ्रेमवर्क्स हैं जो वेब एप्लिकेशन बनाने में मदद करते हैं, जिनमें सबसे प्रमुख Flask और Django हैं। इस अध्याय में हम इन दोनों फ्रेमवर्क्स का परिचय देंगे और एक बेसिक वेब एप्लिकेशन बनाने का तरीका बताएंगे।
1. Flask और Django का परिचय
Flask:
Flask एक lightweight और minimalistic web framework है, जिसे Python में वेब एप्लिकेशन डेवलप करने के लिए बनाया गया है। Flask को अपनी सरलता और लचीलापन के लिए जाना जाता है, जिससे डेवलपर्स को अपनी जरूरतों के हिसाब से एप्लिकेशन बनाने की पूरी स्वतंत्रता मिलती है। इसे विशेष रूप से छोटे और मीडियम साइज के वेब एप्लिकेशनों के लिए पसंद किया जाता है।
- Lightweight और Modular: Flask सिर्फ एक core framework प्रदान करता है, जिससे डेवलपर्स को सिर्फ वही features जोड़ने की स्वतंत्रता मिलती है जो उन्हें चाहिए।
- Routing System: Flask का routing system बहुत सरल और डायनामिक होता है, जिससे URL से जुड़ी HTTP requests को handle किया जा सकता है।
- Template Engine: Flask Jinja2 नामक template engine का उपयोग करता है, जिससे HTML pages को dynamic तरीके से render किया जा सकता है।
Django:
Django Python का एक full-stack web framework है, जो वेब एप्लिकेशन को तेजी से डेवलप करने के लिए कई built-in features प्रदान करता है। Django के पास बहुत सारी built-in features हैं, जैसे कि authentication, admin panel, form handling, और database interaction, जो development को तेज और आसान बना देते हैं।
- Batteries Included: Django में बहुत सारे built-in tools और features होते हैं, जिनकी मदद से डेवलपर को कम effort के साथ पूरा application बनाने का मौका मिलता है।
- Security: Django वेब एप्लिकेशनों को कई सुरक्षा खतरों से बचाने के लिए मजबूत सुरक्षा features प्रदान करता है, जैसे कि SQL injection protection, CSRF protection, और clickjacking prevention।
- ORM (Object-Relational Mapping): Django में built-in ORM होता है, जो डेटाबेस के साथ काम करने को आसान और code-friendly बनाता है।
2. Basic Web App बनाना: Flask के साथ
इससे पहले कि हम Django के साथ काम करें, आइए Flask में एक बेसिक वेब एप्लिकेशन बनाते हैं। Flask का उपयोग करके हम आसानी से छोटे और सरल वेब एप्लिकेशन बना सकते हैं। यहाँ पर हम एक basic "Hello World" एप्लिकेशन बनाएंगे।
Flask Installation:
सबसे पहले, आपको Flask इंस्टॉल करना होगा। आप इसे Python के package manager pip के जरिए इंस्टॉल कर सकते हैं:
pip install flask
Basic Flask Application:
Flask में एक एप्लिकेशन बनाने के लिए आपको Flask
class से एक instance बनाना होता है और फिर routes (URLs) को define करना होता है।
# app.py
from flask import Flask
# Flask एप्लिकेशन का instance बनाएं
app = Flask(__name__)
# Route define करें
@app.route('/')
def home():
return 'Hello, World!'
# एप्लिकेशन को रन करें
if __name__ == '__main__':
app.run(debug=True)
Explanation:
Flask(__name__)
: Flask एप्लिकेशन को initialize करने के लिएFlask
class से एक instance बनाते हैं।@app.route('/')
: यह route '/' URL कोhome()
function से map करता है, जो "Hello, World!" message return करता है।app.run(debug=True)
: एप्लिकेशन को रन करता है, और debug mode को enable करता है, जिससे errors को आसानी से debug किया जा सकता है।
अब इस एप्लिकेशन को चलाने के लिए python app.py
command चलाएं और फिर browser में http://127.0.0.1:5000/
पर जाएं। आप "Hello, World!" message देखेंगे।
3. Basic Web App बनाना: Django के साथ
Django का उपयोग करने के लिए हमें थोड़ी ज्यादा setup की आवश्यकता होती है। आइए Django में भी एक basic "Hello World" एप्लिकेशन बनाए।
Django Installation:
Django को भी pip के माध्यम से इंस्टॉल किया जा सकता है:
pip install django
Django Project Creation:
Django में एक नया project बनाने के लिए, हमें Django project बनाने का command चलाना होता है:
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
Explanation:
django-admin startproject myproject
: यह command एक नया Django projectmyproject
create करती है।python manage.py startapp myapp
: यह command एक नया appmyapp
create करती है, जो हमारे project के अंदर होगा।
Views और URL Configuration:
अब हमें "Hello, World!" को देखने के लिए view और URL configuration करना होगा।
- View:
myapp/views.py
में एक function create करें:
# myapp/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, World!")
- URL Configuration:
myproject/urls.py
में URL path को map करें:
# myproject/urls.py
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('', views.home, name='home'),
path('admin/', admin.site.urls),
]
Running the Django App:
अब Django एप्लिकेशन को चलाने के लिए, python manage.py runserver
command का उपयोग करें:
python manage.py runserver
फिर, browser में http://127.0.0.1:8000/
पर जाएं। आप "Hello, World!" message देखेंगे।
4. Flask और Django के बीच तुलना
Feature | Flask | Django |
---|---|---|
Type | Micro framework (lightweight) | Full-stack framework |
Ease of Use | सरल, flexible | अधिक structured, built-in tools |
Routing | Simple and dynamic | Powerful and complex |
Database Support | Manual, use third-party libraries | Built-in ORM |
Learning Curve | हल्का, शुरुआत के लिए आसान | थोड़ा अधिक steep |
5. Summary
- Flask और Django दोनों Python में web development के लिए उपयोगी frameworks हैं, लेकिन उनका उपयोग अलग-अलग परिस्थितियों में किया जाता है। Flask छोटे और हल्के web apps के लिए अच्छा है, जबकि Django बड़े, full-stack web apps के लिए उपयुक्त है।
- Flask का setup सरल होता है और इसमें ज्यादा configuration की आवश्यकता नहीं होती है, जिससे यह छोटे projects के लिए आदर्श है।
- Django में बहुत सारे built-in features होते हैं, जो बड़े और complex applications के लिए उपयोगी होते हैं।
- इस chapter में, हमने Flask और Django दोनों के साथ basic web app बनाने का तरीका सीखा।
Chapter: Introduction to Machine Learning with Python
Machine Learning (ML) Python में एक ऐसा powerful tool है, जो data analysis और prediction tasks को आसान और efficient बनाता है। Python की सादगी और विविध libraries ने इसे machine learning के लिए एक सबसे लोकप्रिय programming language बना दिया है। इस अध्याय में हम machine learning के बुनियादी concepts और Python में इसका उपयोग करने के बारे में चर्चा करेंगे। हम Scikit-Learn library का उपयोग करके कुछ simple machine learning models भी बनाएंगे।
1. Machine Learning का परिचय
Machine Learning एक AI (Artificial Intelligence) का sub-field है, जिसमें कंप्यूटर को बिना explicitly programmed किए data से सीखने और अपने अनुभव से निर्णय लेने की क्षमता मिलती है। इसके द्वारा हम data से patterns और insights खोज सकते हैं और उसे भविष्य की predicitons के लिए इस्तेमाल कर सकते हैं।
Types of Machine Learning:
- Supervised Learning: इसमें मॉडल को labeled data के साथ train किया जाता है। इसका उद्देश्य output variable (target) को predict करना होता है।
- Example: Spam email detection, Stock price prediction.
- Unsupervised Learning: इसमें data बिना labels के होते हैं और मॉडल को केवल input data से patterns ढूंढने के लिए train किया जाता है।
- Example: Customer segmentation, Anomaly detection.
- Reinforcement Learning: इसमें एजेंट एक environment के साथ interact करता है और rewards प्राप्त करके optimal decision-making process सीखता है।
- Example: Self-driving cars, Game playing.
2. Scikit-Learn Library का परिचय
Scikit-learn (या sklearn) Python का एक powerful machine learning library है, जो simple और efficient tools प्रदान करता है। यह supervised और unsupervised learning दोनों के लिए algorithms, model evaluation techniques और data preprocessing tools का सेट प्रदान करता है। Scikit-learn को install करना और उपयोग करना बेहद आसान है।
Scikit-learn Features:
- Wide Range of Algorithms: Linear Regression, Decision Trees, SVM, K-Means, आदि।
- Data Preprocessing Tools: Scaling, normalization, encoding, missing data imputation आदि।
- Model Evaluation: Cross-validation, metrics (accuracy, precision, recall, F1-score) आदि।
- Pipeline: Complex workflows को manage करने के लिए pipeline creation।
Scikit-learn Installation:
Scikit-learn को pip के जरिए इंस्टॉल किया जा सकता है:
pip install scikit-learn
3. Simple ML Models बनाना
अब हम Scikit-learn का उपयोग करके एक simple machine learning model बनाएंगे। हम एक Supervised Learning problem को हल करेंगे और Linear Regression algorithm का उपयोग करेंगे। Linear Regression एक बेसिक algorithm है जिसका उपयोग continuous numerical predictions के लिए किया जाता है।
Step 1: Dataset Import करना
हम एक dataset का उपयोग करेंगे, जिसमें घरों के आकार और उनकी कीमत के बारे में जानकारी होगी।
# Importing necessary libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Sample dataset
data = {
'Area (sqft)': [1500, 1800, 2400, 3000, 3500],
'Price (in lakhs)': [400, 500, 600, 650, 700]
}
# Converting to DataFrame
df = pd.DataFrame(data)
print(df)
Step 2: Data Splitting
हम dataset को training और testing data में split करेंगे। Training data का उपयोग model को train करने के लिए किया जाएगा, जबकि testing data का उपयोग model की accuracy check करने के लिए किया जाएगा।
# Splitting data into features (X) and target (y)
X = df[['Area (sqft)']] # Features
y = df['Price (in lakhs)'] # Target variable
# Splitting dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train, X_test, y_train, y_test)
Step 3: Model Building
अब हम Linear Regression model बनाएंगे और उसे training data पर train करेंगे।
# Creating the model
model = LinearRegression()
# Training the model
model.fit(X_train, y_train)
Step 4: Model Prediction
हम trained model का उपयोग करके testing data पर predictions करेंगे।
# Predicting prices for test data
y_pred = model.predict(X_test)
# Printing predictions
print("Predicted prices:", y_pred)
Step 5: Model Evaluation
हम model की accuracy evaluate करेंगे। यहाँ हम Mean Squared Error (MSE) का उपयोग करेंगे, जो model की error को measure करता है।
# Evaluating the model using Mean Squared Error (MSE)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
4. Advanced Model (Optional)
अब, एक advanced model की तरफ बढ़ते हैं। हम Decision Tree classifier का उपयोग करेंगे, जो supervised learning में classification tasks के लिए उपयोग किया जाता है।
from sklearn.tree import DecisionTreeClassifier
# Sample classification dataset
data = {
'Age': [22, 25, 47, 52, 46],
'Salary': [2200, 2700, 3400, 3800, 3000],
'Purchased': ['No', 'Yes', 'Yes', 'No', 'Yes']
}
df = pd.DataFrame(data)
# Preparing features and target
X = df[['Age', 'Salary']]
y = df['Purchased']
# Splitting the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Creating and training the Decision Tree model
dt_model = DecisionTreeClassifier()
dt_model.fit(X_train, y_train)
# Making predictions
y_pred_dt = dt_model.predict(X_test)
# Evaluating the model
accuracy = dt_model.score(X_test, y_test)
print("Decision Tree Model Accuracy:", accuracy)
5. Summary
- Machine Learning में data से सीखकर model बनाना और उसे real-world problems के लिए apply करना होता है।
- Scikit-learn एक powerful library है जो machine learning algorithms और tools को आसानी से प्रयोग में लाने में मदद करती है।
- हमने इस chapter में Linear Regression और Decision Tree models का उदाहरण देखा और जाना कि कैसे इनको train, predict और evaluate किया जाता है।
Chapter: Part 8 - Project Work and Best Practices
इस अध्याय में, हम Python प्रोग्रामिंग का वास्तविक दुनिया में उपयोग करने के लिए कुछ छोटे projects पर ध्यान देंगे। इन projects का उद्देश्य आपके Python कौशल को मजबूत करना है और यह दिखाना है कि आप वास्तविक समस्याओं को हल करने के लिए अपनी प्रोग्रामिंग क्षमताओं का कैसे उपयोग कर सकते हैं। साथ ही, हम best practices के बारे में भी चर्चा करेंगे ताकि आपका कोड अधिक organized, efficient और maintainable हो।
1. Python Mini Projects
Mini projects आपको programming की बुनियादी समझ को बेहतर तरीके से लागू करने में मदद करते हैं। हम कुछ छोटे projects बनाएंगे जो beginners के लिए perfect होंगे और जिनसे आपको Python के core concepts को समझने में मदद मिलेगी। यह projects आपको real-world applications पर काम करने का अनुभव भी देंगे।
2. Calculator Program
Project Overview:
यह project एक simple calculator बनाएगा जो addition, subtraction, multiplication और division operations कर सकेगा। यह program user input लेगा और उसके अनुसार calculation करेगा।
Steps to Create the Calculator:
- User Interface: हम simple command-line interface (CLI) बनाएंगे जहाँ user ऑपरेशन (operation) का चयन कर सकता है।
- Functions: हम Python functions का उपयोग करेंगे जैसे
add()
,subtract()
,multiply()
, औरdivide()
जो अलग-अलग mathematical operations करेंगे। - User Input: Python के
input()
function का उपयोग कर हम user से दो संख्याएँ (numbers) प्राप्त करेंगे और फिर उन्हें जोड़ने, घटाने, गुणा करने या भाग करने का option देंगे।
Code Example:
# Functions for basic operations
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
else:
return x / y
# Main program
def calculator():
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
# Get input from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")
elif choice == '2':
print(f"{num1} - {num2} = {subtract(num1, num2)}")
elif choice == '3':
print(f"{num1} * {num2} = {multiply(num1, num2)}")
elif choice == '4':
print(f"{num1} / {num2} = {divide(num1, num2)}")
else:
print("Invalid input")
# Run the calculator
calculator()
Learning Outcome:
- Functions का उपयोग करके code को modular बनाना।
- User input को handle करना।
- Simple conditional logic (if-else) का उपयोग करना।
3. To-Do List Application
Project Overview:
यह project एक simple To-Do List application बनाएगा। इस app में user tasks add, remove, और mark as complete कर सकेंगे। यह project file handling और data persistence को समझने में भी मदद करेगा, ताकि user का data बंद होने पर भी सुरक्षित रहे।
Steps to Create the To-Do List:
- Task Management: हम task को list के रूप में store करेंगे और user के input के आधार पर tasks को add और remove करेंगे।
- File Handling: tasks को store करने के लिए हम text file का उपयोग करेंगे ताकि application बंद होने के बाद भी tasks सुरक्षित रहें।
- User Interface: Python में basic CLI interface बनाएंगे, जहाँ user task add, remove और view कर सकें।
Code Example:
# To-Do List program
# Function to add a task
def add_task(task, task_list):
task_list.append(task)
print(f"Task '{task}' added successfully.")
# Function to remove a task
def remove_task(task, task_list):
if task in task_list:
task_list.remove(task)
print(f"Task '{task}' removed successfully.")
else:
print(f"Task '{task}' not found.")
# Function to display all tasks
def display_tasks(task_list):
if len(task_list) == 0:
print("No tasks in your list.")
else:
print("Your Tasks:")
for task in task_list:
print(f"- {task}")
# Main program
def todo_list():
task_list = [] # Empty list to store tasks
while True:
print("\nTo-Do List")
print("1. Add Task")
print("2. Remove Task")
print("3. Display Tasks")
print("4. Exit")
choice = input("Enter choice (1/2/3/4): ")
if choice == '1':
task = input("Enter task: ")
add_task(task, task_list)
elif choice == '2':
task = input("Enter task to remove: ")
remove_task(task, task_list)
elif choice == '3':
display_tasks(task_list)
elif choice == '4':
break
else:
print("Invalid choice. Please try again.")
# Run the To-Do List application
todo_list()
Learning Outcome:
- File handling (reading and writing to a file) का उपयोग।
- Lists के साथ काम करना।
- Tasks को dynamically add और remove करना।
4. Weather App
Project Overview:
यह project एक simple weather application बनाएगा, जो user को किसी भी शहर का मौसम दिखाएगा। हम OpenWeatherMap API का उपयोग करेंगे ताकि हम live weather data प्राप्त कर सकें। यह project API integration, JSON parsing और basic error handling को समझने में मदद करेगा।
Steps to Create the Weather App:
- API Integration: OpenWeatherMap API का उपयोग करके weather data प्राप्त करना।
- JSON Parsing: API से प्राप्त डेटा को JSON format में parse करना और उसे display करना।
- Error Handling: API request errors को handle करना और user-friendly messages दिखाना।
Code Example:
import requests
# Function to get weather data
def get_weather(city):
api_key = "your_api_key_here" # Replace with your API key
base_url = "http://api.openweathermap.org/data/2.5/weather?"
# Final url
complete_url = f"{base_url}q={city}&appid={api_key}&units=metric"
# Sending GET request to the API
response = requests.get(complete_url)
# If the response was successful
if response.status_code == 200:
data = response.json()
# Extracting relevant data
main = data['main']
weather = data['weather'][0]
temperature = main['temp']
pressure = main['pressure']
humidity = main['humidity']
description = weather['description']
# Displaying the result
print(f"Weather in {city}:")
print(f"Temperature: {temperature}°C")
print(f"Pressure: {pressure} hPa")
print(f"Humidity: {humidity}%")
print(f"Description: {description}")
else:
print("City not found, please try again.")
# Main program
def weather_app():
city = input("Enter city name: ")
get_weather(city)
# Run the Weather App
weather_app()
Learning Outcome:
- API integration और JSON data handling सीखना।
- External libraries (requests) का उपयोग।
- Error handling और user-friendly messaging।
5. Best Practices
इन projects के दौरान, कुछ best practices को ध्यान में रखना महत्वपूर्ण है। यह best practices आपके code को clean, maintainable और efficient बनाने में मदद करेंगी।
- Code Organization: हमेशा functions का उपयोग करें ताकि code modular और reusable रहे।
- Comments and Documentation: code को समझने में आसानी के लिए comments और documentation का उपयोग करें।
- Error Handling: सभी programs में error handling शामिल करें ताकि unexpected errors से बचा जा सके।
- Code Readability: Python में indentation और proper naming conventions का पालन करें ताकि code अधिक readable और understandable हो।
- Testing: हमेशा अपने code का परीक्षण करें ताकि bugs को जल्दी पकड़ा जा सके और सही output प्राप्त हो सके।
Conclusion: इस chapter में, आपने Python के mini projects बनाए और उन projects में basic concepts को लागू किया। इसके साथ ही आपने Python programming के best practices को भी सीखा, जिससे आपका code अधिक clean, efficient और maintainable होगा। अब आप Python की मदद से real-world applications बना सकते हैं और अपनी programming skills को और बेहतर बना सकते हैं।
Chapter: Best Practices in Python Programming
Python एक सरल और शक्तिशाली प्रोग्रामिंग भाषा है, लेकिन जब हम बड़े और complex projects पर काम करते हैं, तो हमें कुछ best practices अपनानी चाहिए ताकि हमारा code साफ, पढ़ने योग्य, और maintainable हो। इस chapter में हम Python programming में best practices पर चर्चा करेंगे, जो आपके code को बेहतर बनाने में मदद करेंगे।
1. Clean Code Writing
Clean Code वह code होता है जो आसानी से समझा जा सकता है और maintain करना आसान होता है। जब code clean होता है, तो अन्य developers के लिए उसे समझना और debug करना सरल होता है। अच्छे coding practices को follow करने से यह सुनिश्चित होता है कि code long-term में स्थिर और scalable रहे।
Clean Code Tips:
-
Meaningful Variable and Function Names:
- Variables और functions के नाम स्पष्ट और descriptive होने चाहिए ताकि उनका उद्देश्य समझा जा सके। उदाहरण के लिए,
total_price
औरcalculate_total_price()
नामों का उपयोग करें, जो उनके कार्य को स्पष्ट करते हैं।
- Variables और functions के नाम स्पष्ट और descriptive होने चाहिए ताकि उनका उद्देश्य समझा जा सके। उदाहरण के लिए,
-
Avoid Redundancy:
- Code में duplication को कम करने की कोशिश करें। यदि कोई code block बार-बार उपयोग हो रहा है, तो उसे function में बदल दें।
-
Follow PEP 8 Style Guide:
- Python में PEP 8 एक style guide है जो coding conventions जैसे indentation, line length, blank lines आदि के बारे में मार्गदर्शन प्रदान करता है। PEP 8 को follow करना code को readable और consistent बनाता है।
-
Consistent Naming Conventions:
- Python में
snake_case
का उपयोग variables और functions के लिए औरCamelCase
का उपयोग classes के लिए किया जाता है। इसे follow करने से code में consistency बनी रहती है।
- Python में
Example of Clean Code:
# Bad Code Example
def calc(t, d):
return t*d
# Good Code Example
def calculate_total_price(price, quantity):
return price * quantity
2. Debugging और Testing
Debugging और Testing किसी भी software development process का अहम हिस्सा होते हैं। Debugging के माध्यम से हम code में हुई गलतियों को पहचानते हैं और सही करते हैं। Testing से हम यह सुनिश्चित करते हैं कि हमारा code सही तरीके से काम कर रहा है और उसमें कोई bugs नहीं हैं।
Debugging Tips:
-
Print Statements:
- Debugging के दौरान, print statements का उपयोग करके हम variable values और function output को ट्रैक कर सकते हैं।
-
Use a Debugger:
- Python में built-in debugger (pdb) का उपयोग करें, जो step-by-step code execution को allow करता है। इससे आप bugs को आसानी से ट्रैक कर सकते हैं।
-
Try-Except Blocks:
- Exception handling का उपयोग करके आप runtime errors को handle कर सकते हैं और program की normal execution को सुनिश्चित कर सकते हैं।
Testing Tips:
- Unit Testing:
- Python में unittest module का उपयोग करके आप functions और methods का unit test कर सकते हैं। Unit tests को लिखना best practice है क्योंकि यह आपको code में bugs को जल्दी से पहचानने में मदद करता है।
- Test-Driven Development (TDD):
- TDD एक development approach है जिसमें आप पहले tests लिखते हैं और फिर उन्हें पास करने के लिए code लिखते हैं। इस approach से code के bugs जल्दी पकड़े जाते हैं और software quality बेहतर होती है।
- Use Assertions:
- Assertions का उपयोग करने से आप code के किसी भी state को validate कर सकते हैं। अगर condition false हो जाती है, तो program assert exception को raise करता है।
Example of Debugging with Print Statements:
def add_numbers(a, b):
print(f"a: {a}, b: {b}") # Debugging line
return a + b
result = add_numbers(3, 4)
print(f"Result: {result}")
Example of Unit Testing:
import unittest
# Code to be tested
def multiply(a, b):
return a * b
# Test case for multiply function
class TestMultiply(unittest.TestCase):
def test_multiply(self):
self.assertEqual(multiply(2, 3), 6)
self.assertEqual(multiply(-1, 5), -5)
self.assertEqual(multiply(0, 10), 0)
if __name__ == '__main__':
unittest.main()
3. Documentation Writing
Documentation लिखना code को दूसरों के लिए समझने योग्य बनाता है और यह सुनिश्चित करता है कि कोई भी developer आसानी से आपके code को पढ़ और उपयोग कर सके। Python में अच्छे documentation के लिए docstrings का उपयोग किया जाता है।
Why Documentation is Important:
-
Code Understanding:
- जब code का documentation अच्छा होता है, तो किसी भी developer के लिए यह समझना आसान होता है कि code किस उद्देश्य के लिए लिखा गया है और इसका उपयोग कैसे किया जा सकता है।
-
Future Proofing:
- अच्छा documentation किसी project को maintain करने में मदद करता है, खासकर जब समय के साथ project पर नए developers काम करते हैं।
-
Collaboration:
- Documentation से टीम के सदस्य आसानी से एक-दूसरे के code को समझ सकते हैं, जिससे collaboration में मदद मिलती है।
Best Practices for Writing Documentation:
-
Use Docstrings:
- Python में functions और classes के लिए docstrings का उपयोग करें। यह code को समझने के लिए एक छोटी सी summary provide करता है।
-
Keep It Concise:
- Documentation concise और to the point होनी चाहिए। unnecessary details से बचें, सिर्फ महत्वपूर्ण जानकारी दें।
-
Document Complex Code:
- केवल सरल code को ही नहीं, बल्कि complex logic और algorithms को भी document करें ताकि कोई दूसरा developer उसे समझ सके।
Example of Documentation with Docstrings:
def add_numbers(a, b):
"""
This function takes two numbers as input and returns their sum.
Parameters:
a (int, float): First number
b (int, float): Second number
Returns:
int, float: The sum of a and b
"""
return a + b
Using External Documentation Tools:
- Sphinx:
- Python projects के लिए documentation generate करने के लिए आप Sphinx tool का उपयोग कर सकते हैं। यह आपको HTML, PDF, आदि में formatted documentation generate करने की सुविधा देता है।
Best Practices Summary:
-
Clean Code:
- Meaningful variable names, avoid redundancy, follow PEP 8 style guide.
-
Debugging और Testing:
- Print statements, debugging tools, unit tests, and assertions should be used regularly.
-
Documentation Writing:
- Use docstrings for functions and classes, keep documentation concise, and document complex logic.
Conclusion:
Best practices अपनाने से आपका code अधिक readable, efficient और maintainable होता है। Python में clean code लिखने, debugging और testing करने, और अच्छी documentation तैयार करने से आपके projects की quality और usability बेहतर होती है। इन practices को follow करके आप एक बेहतर Python developer बन सकते हैं और आपके code को दूसरों द्वारा आसानी से समझा जा सकता है और maintain किया जा सकता है।
Chapter: Appendix
इस chapter में हम Python programming के लिए कुछ उपयोगी cheatsheets, resources, और interview questions प्रदान करेंगे, जो आपको Python सीखने और interviews के लिए तैयारी करने में मदद करेंगे।
1. Python Cheatsheet
Python cheatsheet एक quick reference guide होता है, जो Python के विभिन्न concepts और syntax को संक्षेप में प्रस्तुत करता है। इसका उपयोग आप code लिखते समय या Python से संबंधित concepts को जल्दी से समझने के लिए कर सकते हैं।
Basic Syntax Cheatsheet
- Variables & Data Types:
Data Type | Example | Description |
---|---|---|
int | x = 10 |
Integer numbers |
float | y = 3.14 |
Floating point numbers |
str | name = "John" |
String (Text) |
list | lst = [1, 2, 3] |
List of items |
tuple | t = (1, 2, 3) |
Immutable list |
dict | d = {"name": "John", "age": 30} |
Key-value pairs (Dictionary) |
bool | is_active = True |
Boolean (True or False) |
- Basic Operations:
Operator | Example | Description |
---|---|---|
+ |
x + y |
Addition |
- |
x - y |
Subtraction |
* |
x * y |
Multiplication |
/ |
x / y |
Division |
// |
x // y |
Integer Division |
% |
x % y |
Modulus (Remainder) |
** |
x ** y |
Exponentiation |
- Control Flow:
Statement | Example | Description |
---|---|---|
if |
if x > y: |
If statement |
elif |
elif x == y: |
Else if statement |
else |
else: |
Else statement |
for |
for i in range(5): |
Loop through a range or list |
while |
while condition: |
Loop while condition is true |
break |
break |
Exit the loop prematurely |
continue |
continue |
Skip the current iteration of loop |
2. Useful Resources and Links
यहां कुछ Python programming से संबंधित महत्वपूर्ण resources और websites हैं, जिनका उपयोग आप सीखने और अभ्यास करने के लिए कर सकते हैं:
-
Official Python Documentation
Link: https://docs.python.org/
Python की आधिकारिक डोक्युमेंटेशन, जिसमें Python के सभी modules, functions, और syntax की जानकारी दी जाती है। -
W3Schools Python Tutorial
Link: https://www.w3schools.com/python/
W3Schools Python के basic concepts को समझाने के लिए एक अच्छा resource है। -
Real Python
Link: https://realpython.com/
Python tutorials और tips का एक collection है, जो advanced topics को भी कवर करता है। -
GeeksforGeeks Python Programming
Link: https://www.geeksforgeeks.org/python-programming-language/
GeeksforGeeks Python के बारे में विस्तार से explain करता है और code examples के साथ concepts को समझाता है। -
Python Tutor
Link: http://pythontutor.com/
Python code को step-by-step visualize करने के लिए एक अच्छा tool है, जो beginners के लिए helpful होता है। -
Stack Overflow Python Questions
Link: https://stackoverflow.com/questions/tagged/python
Python से संबंधित सभी समस्याओं का समाधान आप Stack Overflow पर ढूंढ सकते हैं, जहां बहुत सारे experienced developers सवालों के जवाब देते हैं।
3. Python Interview Questions for Beginners
Python programming language पर interview में पूछे जाने वाले कुछ common questions:
Basic Questions:
-
What is Python?
- Python एक high-level, interpreted, और general-purpose programming language है, जो readability और simplicity को prioritize करता है। यह object-oriented, functional, और procedural programming paradigms को support करता है।
-
Explain the difference between lists and tuples in Python.
- List mutable होते हैं, अर्थात इन्हें modify किया जा सकता है। जबकि Tuple immutable होते हैं, अर्थात इनका content एक बार set करने के बाद बदल नहीं सकता।
-
What is PEP 8?
- PEP 8 Python का style guide है, जो Python code को clean, readable, और consistent बनाने के लिए conventions define करता है।
-
What are Python’s key features?
- Python के कुछ प्रमुख features में readability, dynamic typing, interpreted language, large standard library, and support for multiple programming paradigms शामिल हैं।
-
What is a Python dictionary?
- Python dictionary key-value pairs का collection है, जो unordered होते हैं। यह {} brackets में define होते हैं।
Intermediate Questions:
-
What are lambda functions?
- Lambda functions anonymous functions होते हैं जिन्हें
lambda
keyword के साथ define किया जाता है। ये छोटे, single-expression functions होते हैं जो short-term use के लिए होते हैं।
- Lambda functions anonymous functions होते हैं जिन्हें
-
Explain the difference between
deepcopy()
andcopy()
in Python.- copy() shallow copy करता है, जिसका मतलब है कि यह नए object का reference copy करता है। deepcopy() एक complete copy करता है, जिसमें nested objects भी copy होते हैं।
-
What is a decorator in Python?
- Decorators functions होते हैं जो अन्य functions को modify करते हैं। यह higher-order functions का उपयोग करके existing functions को enhance या modify करते हैं।
-
Explain the difference between
is
and==
operators in Python.is
operator identity को compare करता है, जबकि==
operator values को compare करता है।
-
What are Python’s built-in data types?
- Python के built-in data types में int, float, str, list, tuple, dict, set, और bool शामिल हैं।
Advanced Questions:
-
What is multithreading in Python?
- Multithreading एक technique है जिसका उपयोग एक ही process के अंदर multiple threads को execute करने के लिए किया जाता है, जिससे program की performance improve होती है।
-
What is GIL (Global Interpreter Lock) in Python?
- Python के CPython implementation में GIL एक mechanism है जो thread-safe execution को ensure करता है। इसका मतलब है कि एक time में केवल एक thread Python bytecode execute कर सकता है।
-
What is the difference between
__str__()
and__repr__()
methods?__str__()
human-readable string representation देता है, जबकि__repr__()
machine-readable representation देता है और debugging में helpful होता है।
-
What is the purpose of the
self
keyword in Python classes?self
एक instance variable होता है जो class के methods में current instance को reference करता है।
-
Explain the concept of metaclasses in Python.
- Metaclasses classes के लिए classes होती हैं। इनका use dynamic class creation के लिए किया जाता है, जिससे classes का behavior modify किया जा सकता है।
Conclusion:
इस appendix में हमने Python cheatsheet, useful resources, और Python interview questions के बारे में विस्तार से चर्चा की है। ये tools और resources आपके Python सीखने के journey को और आसान बनाएंगे और आपको Python programming के interviews में सफलता प्राप्त करने में मदद करेंगे।
0 Comments
कमेंट केवल पोस्ट से रिलेटेड करें