Basics
# Print Statement
print("Hello, World!") # Variables
x = 5
y = "Hello" # Data Types
int_var = 10 # Integer
float_var = 10.5 # Float
str_var = "Hello" # String
bool_var = True # Boolean
list_var = [1, 2, 3] # List
tuple_var = (1, 2, 3) # Tuple
set_var = {1, 2, 3} # Set
dict_var = {"key": "value"} # Dictionary
Control Structures
# If-Else
if x > 0: print("Positive")
elif x == 0: print("Zero")
else: print("Negative") # For Loop
for i in range(5): print(i) # While Loop
count = 0
while count < 5: print(count) count += 1
Functions
def my_function(param1, param2): return param1 + param2 result = my_function(5, 3)
print(result)
Classes
class MyClass: def __init__(self, name): self.name = name def greet(self): return f"Hello, {self.name}!" obj = MyClass("Harlin")
print(obj.greet())
Exception Handling
try: result = 10 / 0
except ZeroDivisionError: print("Cannot divide by zero!")
finally: print("Execution complete.")
File Operations
# Read from a file
with open('file.txt', 'r') as file: content = file.read() print(content) # Write to a file
with open('file.txt', 'w') as file: file.write("Hello, World!")
List Comprehensions
# Basic List Comprehension
squares = [x**2 for x in range(10)]
print(squares) # Conditional List Comprehension
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Lambda Functions
# Lambda Function
add = lambda a, b: a + b
print(add(5, 3))
Map, Filter, Reduce
from functools import reduce # Map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # Reduce
sum_numbers = reduce(lambda a, b: a + b, numbers)
print(sum_numbers)
Modules
# Importing a Module
import math
print(math.sqrt(16)) # Importing Specific Functions
from math import pi, sin
print(pi)
print(sin(0))
Numpy Basics
import numpy as np # Creating Arrays
arr = np.array([1, 2, 3, 4, 5])
print(arr) # Array Operations
print(arr + 5)
print(arr * 2)
print(np.sqrt(arr))
Pandas Basics
import pandas as pd # Creating DataFrame
data = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [24, 27, 22]
}
df = pd.DataFrame(data)
print(df) # Basic Operations
print(df['Name'])
print(df.describe())
print(df[df['Age'] > 23])
Matplotlib Basics
import matplotlib.pyplot as plt # Basic Plot
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Sample Plot')
plt.show()
Discover more from Coursity
Subscribe to get the latest posts sent to your email.