Python is a versatile and powerful programming language known for its simplicity and readability. Here, we go over some of the key concepts quickly you need to know for Python coding. Installation / Setup
python --version
.Rest of the crash course just ramps up a user w/ the python syntax, and can be reffered a topic to quickly re-learn / ramp up on how it works. If you are new to programming, please check out a more comprehensive course here:
Learn Python - Full Course for Beginners [Tutorial]
# BASIC SYNTAX
# Python uses indentation (typically four spaces) to define blocks of code. Use the `print` function to display output.
print("Hello, World!")
# Example 1
name = "Alice"
print("Hello, " + name + "!")
# Example 2
age = 25
print("Age:", age)
# Variables and Data Types
# Variables store values that can be used later. Python supports various data types, including numbers, strings, booleans, lists, and dictionaries.
# Example 1
is_new = True
print("Is new user?", is_new)
# Example 2
number = 42
print("The answer to the ultimate question of life, the universe, and everything is", number)
# CONTROL FLOW
# Use `if` statements for conditional execution.
# Example 1
num = 10
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
# MULTIPLE IF Statements -> All individual and will ALL be excecuted
# IF-ELIF- ELSE -> ONLY 1 part of the condition will be excecuted
# The latter is also more better for performance
# Example 2
x = 5
y = 3
if x > y:
print("x is greater than y.")
else:
print("x is not greater than y.")
# LOOPS
# Use `for` loops to iterate over sequences.
# Example 1
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Example 2
for i in range(5):
print(i)
# While loops
# Use `while` loops to repeatedly execute code until a condition is met.
# Example 1
count = 0
while count < 5:
print(count)
count += 1
# Example 2
num = 1
while num <= 10:
if num % 2 == 0:
print(num)
num += 1
# FUNCTIONS
# A function is a reusable set of operations.
# Functions allow you to reuse code blocks. They can take input arguments and optionally return a value.
# Example 1
def square(x):
return x ** 2
print(square(5)) # Output: 25
# Example 2
def greet(name):
print("Hello, " + name + "!")
greet("Bob") # Output: Hello, Bob!
# LISTS
# Lists are ordered collections of items that can be of different types.
# You can add, remove, or access elements using indexing.
# Example 1
numbers = [1, 2, 3, 4, 5]
print("First number:", numbers[0])
# Example 2
fruits = ["apple", "banana", "orange"]
fruits.append("grape")
print(fruits) # Output: ['apple', 'banana', 'orange', 'grape']
# DICTIONARIES
# Dictionaries store key-value pairs. Keys must be unique and can be used to
# retrieve corresponding values.
# Example 1
person = {"name": "Alice", "age": 25}
print("Name:", person["name"])
# Example 2
person["city"] = "New York"
print("City:", person["city"])
# FILE HANDLING
# Python provides built-in functions to read from and write to files.
# Example 1
file = open("data.txt", "w")
file.write("Hello, World!")
file.close()
# Example 2 -- with automatically takes care of opening and closing the file
with open("data.txt", "r") as file:
content = file.read()
print(content)
# EXCEPTION HANDLING
# Use `try-except` blocks to handle and recover from exceptions.
# Example 1
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
# Example 2
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ValueError:
print("Invalid input. Please enter a number.")
except ZeroDivisionError:
print("Error: Division by zero!")
# LIBRARIES & MODULES
# Python has a vast ecosystem of libraries and modules to extend its functionality.
# Example 1
import math
print("Square root of 16:", math.sqrt(16))
# Example 2
import random
print("Random number between 1 and 10:", random.randint(1, 10))
# OBJECT ORIENTED PROGRAMMING (OOP)
# Python supports OOP concepts like classes, objects, inheritance, and
# polymorphism.
# Example 1
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("Hello, my name is", self.name, "and I'm", self.age, "years old.")
person = Person("Alice", 25)
person.introduce()
# Example 2
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
rectangle = Rectangle(5, 3)
print("Area of the rectangle:", rectangle.area())
# DATA SCIENCE MODULES
# Python has several popular modules for data manipulation, analysis, and visualization.
# Example 1
import pandas as pd
data = pd.read_csv("data.csv")
print("Data shape:", data.shape)
# Example 2
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print("Array mean:", np.mean(arr))
# STRING MANIPULATION
# Python provides many built-in functions and methods for string manipulation.
# Example 1
message = "Hello, World!"
print("Length of the message:", len(message))
# Example 2
name = "Alice"
print("Uppercase name:", name.upper())
# REGULAR EXPRESSIONS (RE)
# Regular expressions (regex) allow you to search, match, and manipulate strings based on specific patterns.
# Example 1
import re
text = "Contact me at 123-456-7890"
pattern = r"\\d{3}-\\d{3}-\\d{4}"
match = re.search(pattern, text)
if match:
print("Phone number:", match.group(0))
# Example 2
text = "The cat is sitting on the mat."
pattern = r"\\bcat\\b"
new_text = re.sub(pattern, "dog", text)
print(new_text)
# VIRTUAL ENVS -- Do the code samples below in your terminal!
# Virtual environments allow you to create isolated Python environments with their own packages and dependencies.
# Example 1
# Creating a virtual environment
# python -m venv myenv
# Example 2
# Activating the virtual environment
# source myenv/bin/activate (for Linux/Mac)
# myenv\\Scripts\\activate.bat (for Windows)
# DATES AND TIME IN PYTHON
# Python provides the `datetime` module for working with dates, times, and time intervals.
# Example 1
import datetime
current_time = datetime.datetime.now()
print("Current time:", current_time)
# Example 2
date = datetime.datetime(2023, 6, 1)
formatted_date = date.strftime("%Y-%m-%d")
print("Formatted date:", formatted_date)
# WEB SCRAPING DATA
# Python offers powerful libraries such as `requests` and `BeautifulSoup` for web scraping.
# Example 1
import requests
from bs4 import BeautifulSoup
url = "<https://example.com>"
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, "html.parser")
title = soup.title.string
print("Title:", title)
# Example 2
links = soup.find_all("a")
for link in links:
print("Link:", link.get("href"))
# Variables are dynamicly typed
n = 0
print('n =', n)
>>> n = 0
n = "abc"
print('n =', n)
>>> n = abc
# Multiple assignments
n, m = 0, "abc"
n, m, z = 0.125, "abc", False
# Increment
n = n + 1 # good
n += 1 # good
n++ # bad
# None is null (absence of value)
n = 4
n = None
print("n =", n)
>>> n = None
# If statements don't need parentheses
# or curly braces.
n = 1
if n > 2:
n -= 1
elif n == 2:
n *= 2
else:
n += 2
# Parentheses needed for multi-line conditions.
# and = &&
# or = ||
n, m = 1, 2
if ((n > 2 and
n != m) or n == m):
n += 1
n = 5
while n < 5:
print(n)
n += 1
# Looping from i = 0 to i = 4
for i in range(5):
print(i)
# Looping from i = 2 to i = 5
for i in range(2, 6):
print(i)
# Looping from i = 5 to i = 2
for i in range(5, 1, -1):
print(i)
# Division is decimal by default
print(5 / 2)
# Double slash rounds down
print(5 // 2)
# CAREFUL: most languages round towards 0 by default
# So negative numbers will round down
print(-3 // 2)
# A workaround for rounding towards zero
# is to use decimal division and then convert to int.
print(int(-3 / 2))
# Modding is similar to most languages
print(10 % 3)
# Except for negative values
print(-10 % 3)
# To be consistent with other languages modulo
import math
from multiprocessing import heap
print(math.fmod(-10, 3))
# More math helpers
print(math.floor(3 / 2))
print(math.ceil(3 / 2))
print(math.sqrt(2))
print(math.pow(2, 3))
# Max / Min Int
float("inf")
float("-inf")
# Python numbers are infinite so they never overflow
print(math.pow(2, 200))
# But still less than infinity
print(math.pow(2, 200) < float("inf"))
# Queues (double ended queue)
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
print(queue)
queue.popleft()
print(queue)
queue.appendleft(1)
print(queue)
queue.pop()
print(queue)