Python Basics - Detailed Guide with Examples and Exercises
1. Introduction to Python
- Python is easy to learn and widely used in web development, AI, ML, data science, etc.
- It is interpreted, meaning you don't need to compile your code.
2. Variables and Data Types
- Example:
name = "Alice"
age = 25
height = 5.4
is_student = True
Exercise: Create variables for your name, age, and whether you're a student.
3. Operators
- Arithmetic: +, -, *, /, %, **
- Comparison: ==, !=, >, <, >=, <=
- Logical: and, or, not
Example:
x = 10
y=5
print(x > y and y < 10) # True
Exercise: Try all arithmetic operators with x = 10 and y = 3
4. Control Flow (if, elif, else)
Example:
score = 75
if score >= 90:
print("A")
elif score >= 70:
print("B")
else:
print("C")
Exercise: Write a program to check if a number is positive, negative, or zero.
5. Loops
- for loop:
for i in range(5):
print(i)
- while loop:
i=0
while i < 5:
print(i)
i += 1
Exercise: Print all even numbers from 1 to 20 using a for loop.
6. Functions
Example:
def greet(name):
return "Hello " + name
print(greet("Alice"))
Exercise: Write a function to return the square of a number.
7. Data Structures
- List: nums = [1, 2, 3]
- Tuple: t = (1, 2)
- Dictionary: person = {"name": "Bob", "age": 30}
- Set: s = {1, 2, 3}
Exercise: Create a dictionary for a student with name, age, and subjects.
8. String Operations
Example:
msg = " hello "
print(msg.upper(), msg.strip())
Exercise: Take input from user and reverse the string.
9. Input and Output
Example:
name = input("Enter your name: ")
print("Hello", name)
10. File Handling
Example:
with open("file.txt", "w") as f:
f.write("Hello")
with open("file.txt", "r") as f:
print(f.read())
Exercise: Write a program to store user input into a file.
11. Exception Handling
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Exercise: Handle input errors using try-except
12. Modules and Packages
Example:
import math
print(math.sqrt(16))
Exercise: Use datetime module to print current date and time.
13. Classes and Objects
Example:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hi", self.name)
p = Person("Alice")
p.greet()
Exercise: Create a class for a Book with title and author.
14. Lambda and Built-in Functions
Example:
square = lambda x: x * x
print(square(5))
nums = [1, 2, 3]
print(list(map(lambda x: x*2, nums)))
Exercise: Use filter to select even numbers from a list.
15. Comments
- Single line: # This is a comment
- Multi-line: '''This is a multi-line comment'''
Practice all sections with your own examples!