Python Basics - Beginner to Advanced
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely
used in web development, data analysis, artificial intelligence, scientific computing, and more.
Variables and Data Types
Python supports multiple data types:
- int: Integer values (e.g., 10, -3)
- float: Floating point numbers (e.g., 3.14, -0.5)
- str: Strings of text (e.g., 'hello', "world")
- bool: Boolean values (True or False)
- list: Ordered, mutable sequence (e.g., [1, 2, 3])
- tuple: Ordered, immutable sequence (e.g., (1, 2, 3))
- dict: Key-value pairs (e.g., {'name': 'Alice', 'age': 25})
- set: Unordered collection of unique items (e.g., {1, 2, 3})
Operators in Python
- Arithmetic: +, -, *, /, // (floor division), % (modulus), ** (power)
- Comparison: ==, !=, >, <, >=, <=
- Logical: and, or, not
- Assignment: =, +=, -=, etc.
Control Flow
- if, elif, else:
if x > 0:
print('Positive')
elif x == 0:
print('Zero')
else:
print('Negative')
Python Basics - Beginner to Advanced
- Loops:
for i in range(5):
print(i)
while x < 5:
x += 1
Functions
Functions are blocks of reusable code:
def greet(name):
return 'Hello ' + name
Built-in functions: print(), len(), type(), input(), range(), int(), float(), str()
Data Structures
- List Methods: append(), remove(), pop(), sort(), reverse()
- String Methods: upper(), lower(), strip(), split(), replace()
- Dictionary Methods: keys(), values(), items(), get(), update()
- Set Methods: add(), remove(), union(), intersection()
Exception Handling
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
Modules and Imports
You can use built-in and external modules:
import math
print(math.sqrt(16))
Python Basics - Beginner to Advanced
File Handling
Reading a file:
with open('file.txt', 'r') as f:
data = f.read()
Writing to a file:
with open('file.txt', 'w') as f:
f.write('Hello, world!')
Indentation in Python
Indentation is crucial in Python. Code blocks are defined by their indentation:
def add(a, b):
return a + b
if a > b:
print('A is greater')