Python Tutorial for Beginners
Python is a high-level, interpreted, and dynamically typed programming language that is widely used for web development, data science, automation, AI, and more.
1. Installing Python
Download Python from python.org and install it.
Check if Python is installed by running:
python --version
2. Writing and Running Python Code
You can run Python code in:
- Interactive Mode: Using the Python interpreter (
python
in terminal). - Script Mode: Writing a
.py
file and running it withpython filename.py
.
3. Python Syntax
Hello World Program
print("Hello, World!")
Python Indentation (No {}
)
if True:
print("Python uses indentation") # Correct
4. Python Variables and Data Types
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_valid = True # Boolean
Check data type:
print(type(x)) # Output: <class 'int'>
5. Taking User Input
name = input("Enter your name: ")
print("Hello,", name)
✅ input()
always returns a string, so convert it if needed:
age = int(input("Enter your age: "))
6. Python Operators
Arithmetic Operators
a = 10
b = 5
print(a + b) # Addition: 15
print(a / b) # Division: 2.0
print(a ** b) # Exponentiation: 100000
Comparison Operators
print(10 > 5) # True
print(10 == 5) # False
7. Python Conditional Statements
age = 18
if age >= 18:
print("You are an adult.")
elif age == 17:
print("Almost an adult.")
else:
print("You are a minor.")
8. Python Loops
(a) for
Loop
for i in range(5): # Loops from 0 to 4
print(i)
(b) while
Loop
count = 0
while count < 5:
print(count)
count += 1
✅ Use break
to exit and continue
to skip an iteration.
9. Python Functions
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: Hello, Alice!
✅ Functions make code modular and reusable.
10. Python Lists
Lists store multiple values.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
fruits.append("orange") # Add an element
print(fruits)
✅ Lists are mutable (modifiable).
11. Python Tuples
Tuples are immutable (cannot be modified).
coordinates = (10, 20)
print(coordinates[0]) # Output: 10
12. Python Dictionaries (dict
)
Dictionaries store key-value pairs.
person = {"name": "Alice", "age": 25}
print(person["name"]) # Output: Alice
person["city"] = "New York" # Add new key-value pair
13. Python File Handling
(a) Writing to a File
with open("test.txt", "w") as file:
file.write("Hello, Python!")
(b) Reading a File
with open("test.txt", "r") as file:
print(file.read())
✅ Use with open()
to avoid closing files manually.
14. Exception Handling (try-except
)
Handle errors gracefully:
try:
x = 10 / 0 # Error (division by zero)
except ZeroDivisionError:
print("Cannot divide by zero!")
15. Python Object-Oriented Programming (OOP)
(a) Defining a Class
class Person:
def __init__(self, name, age): # Constructor
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}")
p = Person("Alice", 25)
p.greet() # Output: Hello, my name is Alice
(b) Inheritance
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
s = Student("Bob", 20, "A")
print(s.name, s.grade)
16. Python Modules
Python has built-in and external modules.
(a) Importing a Built-in Module
import math
print(math.sqrt(16)) # Output: 4.0
(b) Creating Your Own Module (my_module.py
)
def add(a, b):
return a + b
Use in another script:
import my_module
print(my_module.add(2, 3)) # Output: 5
17. Python JSON Handling
Working with JSON data:
import json
person = '{"name": "Alice", "age": 25}'
data = json.loads(person) # Convert JSON string to dictionary
print(data["name"]) # Output: Alice
18. Python Regular Expressions (Regex)
import re
text = "My email is example@email.com"
match = re.search(r"\S+@\S+", text)
print(match.group()) # Output: example@email.com
19. Python Date and Time
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # Formatted output
20. Python Web Scraping (BeautifulSoup Example)
from bs4 import BeautifulSoup
import requests
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text) # Get the page title
Conclusion
🚀 Python is easy to learn and powerful!
- ✅ Use variables, functions, loops, and conditions for basic programs.
- ✅ Lists, tuples, dictionaries store data efficiently.
- ✅ OOP, file handling, and modules make Python powerful.
- ✅ Use libraries like
math
,json
,re
,datetime
, andBeautifulSoup
for advanced tasks.
Start practicing Python and build your own projects!
0 comments:
Post a Comment