Python

Created

September 9, 2020

Modified

July 16, 2025

Python basics

Data types

in Python, understanding data types and structures is essential for writting effective code. Data types determine the kind of data a variable can hold, while data structures allow you to organize and manage that data efficiently.

  • Numbers: Represent numerical values, including integers and floating-point numbers.
  • Strings: Represent sequences of characters, used for text manipulation.
  • Booleans: Represent truth values, either True or False.
  • Lists: Ordered collections of items, allowing for duplicate values and mutable operations.
  • Tuples: Ordered collections of items, similar to lists but immutable.
  • Dictionaries: Unordered, Key-value pairs that allow for efficient data retrieval based on unique keys.
  • Sets: Unordered collections of unique items, useful for membership testing and eliminating duplicates.
# Numbers and strings
integer_num = 42
float_num = 3.14
string_text = "Hello, Python!"

# List: mutable, ordered collection
fruits = ["apple", "banana", "cherry"]

# Tuple: immutable, ordered collection
dimensions = (1920, 1080)

# Dictionary: unordered, key-value pairs
person = {"name": "Alice", "age": 30, "city": "New York"}

# Set: unordered collection of unique items
unique_numbers = {1, 2, 3, 4, 5}

print("Integer:", integer_num)
print("Float:", float_num)
print("String:", string_text)
print("List of fruits:", fruits)
print("Tuple of dimensions:", dimensions)
print("Dictionary of person:", person)
print("Set of unique numbers:", unique_numbers)

Control flow and Loops

Control flow in Python allows you to make decisions and execute different blocks of code based on conditions. Loops enable you to repeat a block of code multiple times.

Best practices for control flow and loops include: - Keep conditions simple and clear. Break down complex conditions into smaller parts. - Use meaningful variable names to enhance readability. - Avoid deeply nested loops and conditions to maintain code clarity. - Use comments to explain the purpose of complex conditions or loops. - Test edge cases to ensure your control flow behaves as expected.

# Conditional statements
x = 10
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

# For loop: iterating over a list
for i in range(5):
    print("Iteration:", i)

# While loop: continues until a condition is met
count = 0
while count < 5:
    print("Count is:", count)
    count += 1

Python for R users

Install and libraries

python3 -m pip install pandas
import pandas as pd
import numpy as np
import matplotlib as plt

## Use a function from library, first specify the library nickname and then 
## the function name, separated by a dot:
np.log(7)
library(dplyr)

Pandas data frame

The syntax for the python involves a single argument corresponding to a type of object called a dictionary (a dictionary is defined with curly brackets) whose named entries each contain a python list ([1,2,3,4] and [5,6,7,8]) of the values that will form a column.

df = pd.DataFrame(
    {
        'a': [1,2,3,4],
        'b': [5,6,7,8]
    }
)
print(df)

Variable

  • Number
  • String
  • Tuple
  • List: Mutable, container
  • Dictionary: Mutable, container
  • Set: Mutable, container
  • None: empty value
tuple = (1, 2, 3)
list = [1, 2, 3]
dict = {"ele1":1, "ele2":2, "ele3":3}

Operators

Numerical Operators: - < : less than - > : greater than - <= : less than or equal to - >= : greater than or equal to - == : equal to - != : not equal to

String Operators: - == : equal to - != : not equal to

Logical Operators: - and - or - not

Conditional execution

Conditional execution in Python is achieved using the if/else construct (if and else are reserved words).

# Conidtional execution
x = 10
if x > 10:
    print("I am a big number")
else:
    print("I am a small number")

# Multi-way if/else
x = 10
if x > 10:
    print("I am a big number")
elif x > 5:
    print("I am kind of small")
else:
    print("I am really number")

Iteration/Lopps

Two looping constructs in Python

  • For : used when the number of possible iterations (repetitions) are known in advance

  • While: used when the number of possible iterations (repetitions) can not be defined in advance. Can lead to infinite loops, if conditions are not handled properly

for customer in [“John”, “Mary”, “Jane”]:
    print(“Hello ”, customer)
    print(“Please pay”)
    collectCash()
    giveGoods()

hour_of_day = 9
while hour_of_day < 17:
    moveToWarehouse()
    locateGoods()
    moveGoodsToShip()
    hour_of_day = getCurrentTime()

What happens if you need to stop early? We use the break keyword to do this.

It stops the iteration immediately and moves on to the statement that follows the looping

while hour_of_day < 17:
    if shipIsFull() == True:
        break
    moveToWarehouse()
    locateGoods()
    moveGoodsToShip()
    hour_of_day = getCurrentTime()
collectPay()

What happens when you want to just skip the rest of the steps? We can use the continue keyword for this.

It skips the rest of the steps but moves on to the next iteration.

for customer in ["John", "Mary", "Jane"]:
    print(“Hello ”, customer)
    print(“Please pay”)
    paid = collectCash()
    if paid == false:
        continue
    giveGoods()

Exceptions

  • Exceptions are errors that are found during execution of the Python program.
  • They typically cause the program to fail.
  • However we can handle them using the ‘try/except’ construct.
num = input("Please enter a number: ")
try:
    num = int(num)
    print("number squared is " + str(num**2))
except:
    print("You did not enter a valid number")

General functions

help()
type()
len() 
range()
list()      
tuple()
dict()

Reference