Chapter 1
14 November 2024 12:47 AM
Chapter 1: Python Basics (Foundation for Everything)
Goal:
Is chapter ka main goal hai Python ke fundamentals ko achhe se samajhna taki tum aage complex
coding easily samajh sako.
What is Python?
Python ek high-level, interpreted, object-oriented programming language hai jo simple syntax aur
powerful libraries ke liye famous hai.
Iska use AI, ML, Web Development, Automation, Scripting har jagah hota hai.
Why Learn Python?
✅ Easy to Learn – Simple aur readable syntax
✅ Versatile – Web dev, ML, AI, Data Science, sabme use hoti hai
✅ Huge Community – Har problem ka solution online available hai
Installing Python
1. Download Python from [Link]
2. Install IDE: Use VS Code ya PyCharm for coding
3. Check Python Version: Run python --version in terminal
Python ka syntax simple aur readable hota hai. Example dekho:
python
CopyEdit
print("Hello, Anu!") # Output: Hello, Anu!
Key Points:
✔ No need for semicolons (;)
✔ No need for curly braces ({}), indentation is important
✔ Comments likhne ke liye # ka use hota hai
python
CopyEdit
# This is a comment
print("Python is easy!") # This prints a message
Variables:
Variable ek memory location hoti hai jisme data store hota hai.
Python me variables define karne ke liye = ka use hota hai.
python
CopyEdit
x = 10 # Integer
y = 3.14 # Float
name = "Anu" # String
is_python_easy = True # Boolean
python chapter 1 Page 1
is_python_easy = True # Boolean
Agar user se input lena ho toh input() ka use karte hain.
python
CopyEdit
name = input("Enter your name: ")
print("Hello, " + name + "!")
✔ Note: input() hamesha string return karta hai.
✔ Agar number lena hai toh int() ya float() use karo:
python
CopyEdit
age = int(input("Enter your age: "))
print("You are", age, "years old.")
Python me different types ke operators hote hain:
Type Operator Example
Arithmetic +, -, *, /, %, **, // 5 + 3 = 8
Comparison ==, !=, >, <, >=, <= 5 > 3 → True
Logical and, or, not True and False → False
Assignment =, +=, -=, *=, /= x += 1
Membership in, not in "a" in "apple" → True
Example:
python
CopyEdit
x = 10
y= 5
print(x + y) # Addition
print(x > y) # Comparison
print(x > 0 and y > 0) # Logical AND
Conditional statements se program me decision-making hoti hai.
python
CopyEdit
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not eligible to vote.")
✔ Nested if-else
python
CopyEdit
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade: A")
elif marks >= 75:
python chapter 1 Page 2
elif marks >= 75:
print("Grade: B")
else:
print("Grade: C")
Loops ka use repeated tasks perform karne ke liye hota hai.
✔ For loop example:
python
CopyEdit
for i in range(1, 6): # Loop from 1 to 5
print("Number:", i)
✔ While loop example:
python
CopyEdit
count = 1
while count <= 5:
print("Count:", count)
count += 1
✔ Loop Control Statements:
• break: Loop ko tod deta hai
• continue: Current iteration skip kar deta hai
python
CopyEdit
for i in range(1, 6):
if i == 3:
break # Loop will stop at 3
print(i)
python
CopyEdit
for i in range(1, 6):
if i == 3:
continue # 3 ko skip karega
print(i)
Functions code reuse karne ke liye use hote hain.
✔ Function Definition & Calling:
python
CopyEdit
def greet(
name):
print("Hello,", name)
greet("Anu") # Function Call
✔ Return Statement:
python
CopyEdit
def add(a, b):
python chapter 1 Page 3
def add(a, b):
return a + b
result = add(5, 3)
print("Sum:", result)
✔ Lambda Function:
python
CopyEdit
square = lambda x: x ** 2
print(square(4)) # Output: 16
✔ List: Mutable (change ho sakti hai)
python
CopyEdit
fruits = ["Apple", "Banana", "Cherry"]
[Link]("Mango") # Add item
print(fruits[0]) # Apple
✔ Tuple: Immutable (change nahi ho sakti)
python
CopyEdit
colors = ("Red", "Green", "Blue")
print(colors[1]) # Green
✔ Dictionary: Key-Value pairs
python
CopyEdit
student = {"name": "Anu", "age": 20, "marks": 85}
print(student["name"]) # Anu
# Most Useful and Important Methods of Tuple, List, Dictionary, and String
# ===== Tuple Methods =====
tup = (1, 2, 3, 2, 4)
print([Link](2)) # Count how many times 2 appears
print([Link](3)) # Get index of value 3 (first occurrence)
# ===== List Methods =====
my_list = [3, 1, 4, 1, 5, 9]
my_list.append(10) # Add element at end
my_list.insert(2, 99) # Insert 99 at index 2
my_list.remove(1) # Remove first occurrence of 1
my_list.pop() # Remove last item (or pop(index))
my_list.sort() # Sort the list
my_list.reverse() # Reverse the list
my_list.clear() # Remove all elements
copy_list = my_list.copy() # Copy the list
print(my_list.count(5)) # Count how many times 5 occurs
print(my_list.index(4)) # Get index of first occurrence of 4
# ===== Dictionary Methods =====
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.get('a')) # Get value of 'a'
print(my_dict.keys()) # Get all keys
print(my_dict.values()) # Get all values
python chapter 1 Page 4
print(my_dict.values()) # Get all values
print(my_dict.items()) # Get all key-value pairs
my_dict.update({'d': 4}) # Add/update key 'd'
my_dict.pop('b') # Remove key 'b'
my_dict.popitem() # Remove last inserted item
print(my_dict.setdefault('e', 5)) # Get key 'e' or set it to 5 if missing
my_dict.clear() # Clear dictionary
copy_dict = my_dict.copy() # Shallow copy of dictionary
# ===== String Methods =====
my_str = " Hello, Python World! "
print(my_str.lower()) # Convert to lowercase
print(my_str.upper()) # Convert to uppercase
print(my_str.title()) # Title case
print(my_str.strip()) # Remove leading/trailing spaces
print(my_str.lstrip()) # Remove leading spaces
print(my_str.rstrip()) # Remove trailing spaces
print(my_str.replace("Python", "Java")) # Replace substring
print(my_str.split()) # Split into words
print(my_str.join(["One", "Two"])) # Join with original string as separator
print(my_str.find("Python")) # Find index of substring
print(my_str.index("Hello")) # Index of substring (raises error if not found)
print(my_str.startswith(" H")) # Check if string starts with
print(my_str.endswith("! ")) # Check if string ends with
print(my_str.count("o")) # Count of a character
print(my_str.isalpha()) # Checks if all characters are alphabetic return true or false
print(my_str.isdigit()) # Checks if all characters are digits return true or false
print(my_str.isalnum()) # Checks if all characters are alphanumeric return true or false
print(my_str.isspace()) # Checks if all characters are whitespace return true or false
print(my_str.islower()) # Checks if all characters are lowercase return true or false
print(my_str.isupper()) # Checks if all characters are uppercase return true or false
print(my_str.istitle()) # Checks if string is titlecased return true or false
✅ Bonus: Slicing and Length
python
CopyEdit
s = "Python"
s[0] # 'P'
s[-1] # 'n'
s[1:4] # 'yth'
len(s) # 6
File Handling in Python
Python me file open, read, write kar sakte hain.
✔ File Read:
python
CopyEdit
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
✔ File Write:
python chapter 1 Page 5
python
CopyEdit
file = open("[Link]", "w")
[Link]("Hello, Anu!")
[Link]()
Chapter Summary
✅ Python ka introduction aur installation
✅ Variables, data types, user input
✅ Operators aur conditional statements
✅ Loops aur functions
✅ Lists, tuples, dictionaries
✅ File handling
-------------------------------------------------------------------
Python Basics Mastery Questions (One-Time Solve, Lifetime
Retain!)
Yeh questions tumhari Python fundamentals itni strong bana denge ki tumhe dubara revise karne ki
zaroorat nahi padegi!
python chapter 1 Page 6
✅ Q1: Write a Python program to print "Hello, Python!".
✅ Q2: Take user input for name and age, then print "Hello [name], you are [age] years old!".
✅ Q3: Swap two variables without using a third variable.
✅ Q4: Convert temperature from Celsius to Fahrenheit using the formula:
F=(C×95)+32F = (C \times \frac{9}{5}) + 32F=(C×59)+32
Take user input for Celsius and print Fahrenheit.
✅ Q5: Write a program to check if a number is even or odd using conditional statements.
✅ Q6: Write a program to perform addition, subtraction, multiplication, division, modulus,
exponentiation on two user inputs.
✅ Q7: Write a program to check whether a number is positive, negative, or zero.
✅ Q8: Take three numbers from the user and find the largest among them.
✅ Q9: Write a program to calculate the simple interest:
SI=(P×R×T)/100SI = (P \times R \times T) / 100SI=(P×R×T)/100
(P = Principal, R = Rate, T = Time)
✅ Q10: Take a number from the user and check if it is divisible by both 5 and 7.
✅ Q11: Write a program to check whether a given year is leap year or not.
✅ Q12: Take input marks and print the Grade:
• Marks ≥ 90 → "A"
• Marks ≥ 7
• 5 → "B"
• Marks ≥ 50 → "C"
• Else → "Fail"
✅ Q13: Take a character from the user and check if it is vowel or consonant.
✅ Q14: Write a program to check whether a given number is prime or not.
✅ Q15: Write a program to check if a triangle is valid or not based on three sides. (Sum of any two
sides should be greater than the third side.)
✅ Q16: Print the first 10 natural numbers using a for loop.
✅ Q17: Print the multiplication table of any number taken from the user.
✅ Q18: Find the sum of all digits of a number using a while loop.
✅ Q19: Print this pattern using loops:
markdown
*
**
***
****
*****
✅ Q20: Reverse a number using a while loop. (Example: 12345 → 54321)
✅ Q21: Write a function to find the factorial of a number.
✅ Q22: Write a function that checks if a number is palindrome or not.
✅ Q23: Write a function to find the Greatest Common Divisor (GCD) of two numbers.
python chapter 1 Page 7
✅ Q23: Write a function to find the Greatest Common Divisor (GCD) of two numbers.
✅ Q24: Write a function to generate the Fibonacci series up to n terms.
✅ Q25: Write a function that takes a list of numbers and returns the sum and average.
✅ Q26: Create a list of numbers and find the maximum and minimum value.
✅ Q27: Write a program to count occurrences of a particular element in a list.
✅ Q28: Convert a list to a tuple and tuple to a list.
✅ Q29: Write a program to create a dictionary and add some key-value pairs dynamically.
✅ Q30: Merge two dictionaries and print the final dictionary.
✅ Q31: Write a program to create a file "[Link]" and write "Hello, Python!" inside it.
✅ Q32: Read a file "[Link]" and print its content.
✅ Q33: Append "Welcome to Python programming" to "[Link]".
✅ Q34: Write a program to count the number of lines, words, and characters in a text file.
✅ Q35: Take a filename as input and check whether it exists or not before reading it.
How to Use These Questions?
✅ Daily 5-10 questions solve karo
✅ Khud likh ke practice karo, copy-paste mat karo
✅ Agar koi doubt ho toh mujhe batao
python chapter 1 Page 8