Day 3: Python Basics Cheatsheet
Python Basics Cheatsheet
Here's a summary of the Python basics, from data types and structures to commonly used functions.
Category | Concept/Function | Description | Example |
Data Types | int | Integer type | x = 5 |
float | Floating-point number | y = 3.14 | |
str | String type | name = "Alice" | |
bool | Boolean type | is_valid = True | |
Operators | + , - , * , / | Arithmetic operators | 5 + 3 , 4 * 2 |
== , != , > , < | Comparison operators | x > y | |
and , or , not | Logical operators | True and False | |
Data Structures | list | Ordered, mutable collection | fruits = ["apple", "banana", "cherry"] |
tuple | Ordered, immutable collection | point = (3, 5) | |
set | Unordered, unique collection | unique_nums = {1, 2, 3} | |
dict | Key-value pairs | person = {"name": "Alice", "age": 25} | |
Control Structures | if , elif , else | Conditional statements | if x > 5: print("High") |
for loop | Iterate over a sequence | for item in items: print(item) | |
while loop | Repeat as long as a condition is true | while x < 10: x += 1 | |
Functions | def | Define a function | def add(a, b): return a + b |
lambda | Anonymous function | square = lambda x: x**2 | |
Common Methods | .append() | Add item to a list | fruits.append("orange") |
.remove() | Remove item from a list | fruits.remove("banana") | |
.get() | Get value from dictionary by key | person.get("name") | |
Libraries | import | Import a module | import math |
math.sqrt() | Square root function | math.sqrt(16) | |
random.choice() | Randomly select an item from a list | random.choice(fruits) | |
File Handling | open() | Open a file | file = open("data.txt", "r") |
with open() | Open and automatically close a file | with open("data.txt") as file: | |
Exception Handling | try , except , finally | Handle exceptions | try: x = 1 / 0 except ZeroDivisionError |
Basic Input/Output | input() | Get input from user | name = input("Enter your name: ") |
print() | Output data to the screen | print("Hello, world!") |
Detailed Explanation of Python Basics
Here’s a deeper look at each element from the cheatsheet. These explanations and examples will make it easier to understand and use each concept as I continue my data science journey.
Data Types
int
: Represents an integer value, used for whole numbers.float
: Represents a floating-point number, used for numbers with decimals.str
: Represents a string, used for sequences of characters.bool
: Represents a boolean value, which can be eitherTrue
orFalse
.x = 5 # x is an integer with a value of 5 y = 3.14 # y is a float with a value of 3.14 name = "Alice" # name is a string containing the text "Alice" is_valid = True # is_valid is a boolean set to True
Operators
Arithmetic Operators: Used for basic mathematical operations.
Comparison Operators: Used to compare two values and return a boolean result.
Logical Operators: Used to combine multiple conditions.
5 + 3 # adding numbers 4 * 2 # multiplying numbers x > y # checks if x is greater than y True and False # evaluates to False since both conditions aren’t true
Data Structures
list
: Ordered, mutable collection that can hold multiple items.tuple
: Ordered, immutable collection, meaning items cannot be changed after creation.set
: Unordered collection with unique items only, useful for removing duplicates.dict
: Key-value pairs that allow fast lookups by keys, useful for structured data.# fruits is a list with three items fruits = ["apple", "banana", "cherry"] # point is a tuple representing coordinates point = (3, 5) # unique_nums is a set with three unique numbers unique_nums = {1, 2, 3} # person is a dictionary with name and age person = {"name": "Alice", "age": 25}
Control Structures
if
,elif
,else
: Conditional statements to control program flow.if x > 5: print("High") elif x == 5: print("Equal") else: print("Low")
for
loop: Iterates over a sequence like a list or string.items = [1, 2, 3] for item in items: print(item)
while
loop: Repeats as long as a condition isTrue
.x = 0 while x < 5: print(x) x += 1
Functions
def
: Used to define a function, which is a reusable block of code.def add(a, b): return a + b
lambda
: Defines an anonymous function in a single line, often used for short functions.square = lambda x: x**2 # Defines a function that squares a number.
Common Methods
.append()
: Adds an item to the end of a list.fruits = ["apple"] fruits.append("banana") print(fruits) # Output: ["apple", "banana"]
.remove()
: Removes an item from a list.fruits = ["apple", "banana"] fruits.remove("apple") print(fruits) # Output: ["banana"]
.get()
: Retrieves a value from a dictionary by its key.person = {"name": "Alice"} print(person.get("name")) # Output: "Alice"
Libraries
import
: Brings a library into the current script.import math print(math.sqrt(16)) # Output: 4.0
math.sqrt()
: Returns the square root of a number.math.sqrt(25) # Output: 5.0
random.choice()
: Selects a random item from a list.import random fruits = ["apple", "banana", "cherry"] print(random.choice(fruits)) # Output could be "banana"
File Handling
open()
: Opens a file, allowing reading or writing.file = open("data.txt", "r") content = file.read() file.close()
with open()
: Opens a file and ensures it is closed afterward.with open("data.txt", "r") as file: content = file.read()
Exception Handling
try
,except
,finally
: Manages errors without crashing the program.try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero")
Basic Input/Output
input()
: Prompts the user to enter data.name = input("Enter your name: ") print("Hello", name)
print()
: Displays output on the screen.print("Hello, world!")
Reflection on Day 3
Today’s exercise in summarizing Python basics into a single reference sheet felt like building a strong foundation. These basics will be invaluable in the days ahead, as they form the backbone of all data science projects.
Thanks for following along! I’m excited to keep progressing in Python and getting one step closer to tackling real-world data problems. If you’re also on this journey or have resources to share, feel free to connect!
Subscribe to my newsletter
Read articles from Anastasia Zaharieva directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by