Skip to content

python

Python basics covering data types, control flow, functions and common operations.

Data Types

Common data types in Python.

Modules & Imports

Bringing external or standard library code into your script.

Standard Import

Importing entire modules.

import math

Selective Import

Importing specific functions or classes.

from math import sqrt

Control Flow

Controlling the execution of code.

if statement

Conditional execution.

if x > 0:
print("Positive")

for loop

Iterating over a sequence.

for i in range(5):
print(i)

while loop

Repeating code while a condition is true.

while x < 10:
x += 1

break

Exiting a loop.

for i in range(10):
if i == 5:
break

continue

Skipping to the next iteration of a loop.

for i in range(10):
if i % 2 == 0:
continue
print(i)

Functions

Reusable blocks of code.

Function definition

Creating a function.

def greet(name):
return f"Hello, {name}!"

Function call

Using a function.

message = greet("Alice")
print(message)

Lambda function

Anonymous, small functions.

square = lambda x: x * x

Common Operations

Frequent operations in Python.

String formatting

Creating strings with embedded values.

f'The value is {x}'

List comprehension

Creating lists concisely.

[x**2 for x in range(10)]

Slicing

Accessing parts of a sequence.

my_list[1:4]

File I/O

Reading and writing files.

with open("my_file.txt", "r") as f:
content = f.read()

Error Handling

Managing runtime exceptions safely.

Try Except Block

Catching and handling exceptions gracefully.

try:
result = 10 / 0
except ZeroDivisionError:
result = 0

Object-Oriented Programming

Defining classes and object structures.

Class Definition

Creating classes with initializers.

class Person:
def __init__(self, name):
self.name = name