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.

CategoryConcept/FunctionDescriptionExample
Data TypesintInteger typex = 5
floatFloating-point numbery = 3.14
strString typename = "Alice"
boolBoolean typeis_valid = True
Operators+, -, *, /Arithmetic operators5 + 3, 4 * 2
==, !=, >, <Comparison operatorsx > y
and, or, notLogical operatorsTrue and False
Data StructureslistOrdered, mutable collectionfruits = ["apple", "banana", "cherry"]
tupleOrdered, immutable collectionpoint = (3, 5)
setUnordered, unique collectionunique_nums = {1, 2, 3}
dictKey-value pairsperson = {"name": "Alice", "age": 25}
Control Structuresif, elif, elseConditional statementsif x > 5: print("High")
for loopIterate over a sequencefor item in items: print(item)
while loopRepeat as long as a condition is truewhile x < 10: x += 1
FunctionsdefDefine a functiondef add(a, b): return a + b
lambdaAnonymous functionsquare = lambda x: x**2
Common Methods.append()Add item to a listfruits.append("orange")
.remove()Remove item from a listfruits.remove("banana")
.get()Get value from dictionary by keyperson.get("name")
LibrariesimportImport a moduleimport math
math.sqrt()Square root functionmath.sqrt(16)
random.choice()Randomly select an item from a listrandom.choice(fruits)
File Handlingopen()Open a filefile = open("data.txt", "r")
with open()Open and automatically close a filewith open("data.txt") as file:
Exception Handlingtry, except, finallyHandle exceptionstry: x = 1 / 0 except ZeroDivisionError
Basic Input/Outputinput()Get input from username = input("Enter your name: ")
print()Output data to the screenprint("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 either True or False.

      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 is True.

      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!

0
Subscribe to my newsletter

Read articles from Anastasia Zaharieva directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anastasia Zaharieva
Anastasia Zaharieva