Python Basics

Python
Published

February 17, 2025

Values, Variables, and Types

A ‘value’ in Python is any amount of data, no matter what type

Examples of values:

10 #Integer
'Hello' # String
5.71 # Float
True # Bool

When these values are assigned to a data container, they become ‘variables’

Variables are capable of storing one or more values for use in data collection, transformation, etc.

a = 10 # 'a' is the name of the variable
print(a)
example_list = [20, 9, True, 'string']
10

Data Frames

A ‘data.frame’ is a format of data structure that stores data using observations (rows) and variables (columns). Each individual value corresponds to a ‘cell’, which has meaning based on its associated row index and variable.

Example:

import pandas as pd
nba = pd.read_csv("https://bcdanl.github.io/data/nba.csv")
nba
Name Team Position Birthday Salary
0 Shake Milton Philadelphia 76ers SG 9/26/96 1445697
1 Christian Wood Detroit Pistons PF 9/27/95 1645357
2 PJ Washington Charlotte Hornets PF 8/23/98 3831840
3 Derrick Rose Detroit Pistons PG 10/4/88 7317074
4 Marial Shayok Philadelphia 76ers G 7/26/95 79568
... ... ... ... ... ...
445 Austin Rivers Houston Rockets PG 8/1/92 2174310
446 Harry Giles Sacramento Kings PF 4/22/98 2578800
447 Robin Lopez Milwaukee Bucks C 4/1/88 4767000
448 Collin Sexton Cleveland Cavaliers PG 1/4/99 4764960
449 Ricky Rubio Phoenix Suns PG 10/21/90 16200000

450 rows × 5 columns

Lists, Dictionaries, and Slicing

As previously shown, a ‘list’ is a data container that works in a singlular series of data (i.e. A single row of values). The values in a list are able to be gathered with [] (see below):

example_list
[20, 9, True, 'string']
example_list[0] # Produces the FIRST value in the list, because Python begins counting at 0 instead of 1
20

A ‘dictionary’, in comparison, is a list that utilizes a key-value pair to identify values rather than a numerical index:

example_dict = {'a' : 10, 'b' : 14, 'c' : 'Hello'}
  #example_dict[1] would not work, because dictionaries do not have numerical indexes

print(example_dict.keys())
print(example_dict.values())

example_dict['b']
dict_keys(['a', 'b', 'c'])
dict_values([10, 14, 'Hello'])
14

Strings and Lists can be ‘sliced’ with []

  • For strings, their characters are sliced
  • For lists, their individual values are sliced

Kinds of slicing:

  • [ _ :]
    • Slices from the indicated position to the end
  • [ : _ ]
    • Slices from the beginning to the indicated position
  • [ _ : _ ]
    • Slices from the (left) indicated position to the (right) indicated position
      • Can add an additional ’: _’ at the end of any of these slicing methods to indicate the ‘step’ of the slicing (eg. A step of ‘2’ = every other value).
eg_string = "Hello, I am a string."
print(eg_string[4]) # 5th character, starting at 0

print(example_list[-1]) # Last item in the list

print(eg_string[3:13]) # Characters starting at position 3 and ending at position 13
o
string
lo, I am a

Operators

Python includes symbols that work as operations that act on data, including:

  • ‘+’ for addition
  • ‘-’ for subtraction
  • ’*’ for multiplication
  • ‘/’ for division
  • ’**’ for exponents
  • ‘//’ for integer division

These operations work on most data types, though some work better than others. For example:

string_1 = "My name is"
string_2 = "Steven"
print(string_1 + " " + string_2)
  #string_1 - string_2 would not work; subtraction is not supported by strings
print((string_2 + ' ') * 4)
My name is Steven
Steven Steven Steven Steven 

Value Conversion

We are able to alter a value’s ‘type’ with built-in Python functions, such as:

  • int()
  • float()
  • str()
  • bool()
eg_int = int(29.75)
eg_float = float(10)
eg_str = str(92)
eg_bool = bool(0)

print(eg_int)
print(eg_float)
print(eg_str)
print(eg_bool)
29
10.0
92
False

Boolean Conditions

Boolean conditions are operations which result in a boolean ‘True’ or ‘False’ value, and are used to either filter the data we are looking at or proceed with an action based on the True/False value of the condition.

print(10 == 20) # False
print(20 == '20') # False
False
False

Kinds of conditions (using x/y as placeholders for data):

  • x and y
    • “Are both x and y True?”
  • x or y
    • “Is either x or y True?”
  • not x
    • “Is x False?”
  • x in y
    • “Does x exist within y?”
  • x == y
    • “Is x equal to y?”
  • x != y
    • “Is x not equal to y?”
  • x > y
    • “Is x greater than y?”
  • x >= y
    • “Is x greater than or equal to y?”
  • x < y
    • “Is x less than y?”
  • x <= y
    • “Is x less than or equal to y?”

‘if’ statements are lines of code that run when the outlined condition is met

num = 20
if num == 20:
  print('That is correct!')
That is correct!

‘else’ statements are lines of code that are run when the outlined condition of an ‘if’ statement is NOT met

num = 15
if num == 20:
  print('That is correct!')
else:
  print('That is incorrect...')
That is incorrect...

‘elif’ statements are lines of code that are run when the previous ‘if’ or ‘elif’ condition is not met

num = 0
if num == 20:
  print('That is correct!')
elif 18 <= num < 20:
  print("You're getting closer.")
elif num > 20:
  print('Too far!')
else:
  print("Too low!")
Too low!

While and For loops

  • A ‘while’ loop carries out a set of instructions for as long as a certain condition is met

  • A ‘for’ loop iterates on a data container and carries out a set of instructions for as many times as the container is iterated

    • ‘continue’ is used to skip to the end of the loop
    • ‘break’ is used to stop the loop
count = 1
while count <= 5:
    print(count)
    count += 1
1
2
3
4
5
word = 'thud'
for letter in word:
    print(letter)
t
h
u
d
1
2
3
4
5
6
7
8
9
word = 'thud'
for letter in word:
    if letter == 'u':
        break # Ends the loop before it can finish fully
    print(letter)
t
h
word = 'thud'
for letter in word:
    if letter == 'u':
        continue # Skips over the print() function for 'u'
    print(letter)
t
h
d

List Comprehension

A way of creating or filtering list values using conditions

  • Syntax: listname_new = [ _ for _ in listname_old if ‘condition’ ]
numbers = list(range(1, 21))
print(numbers)

evens = [num for num in numbers if num % 2 == 0]
print(evens)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Dictionary Comprehension

A way of creating or filtering dictionary keys / values using conditions

  • Syntax: dictname_new = { k:v for k, v in dictname_old if ‘condition’ }
# Filtering
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {k: v for k, v in my_dict.items() if v != 2}
print(filtered_dict)

# Swapping Values
original_dict = {'a': 1, 'b': 2, 'c': 3}
swapped_dict = {v: k for k, v in original_dict.items()}
print(swapped_dict)
{'a': 1, 'c': 3, 'd': 4}
{1: 'a', 2: 'b', 3: 'c'}

List / Dictionary Modification

A method (.__) can be used to modify certain aspects of lists and dictionaries

Lists

  • list.append(): Add a new item to the end of the list
  • list. remove(): Remove the FIRST occurrence of the specified value
  • del list[]: Deletes a list’s values by index rather than value

Dictionaries:

  • dict.update({}): Add a new key-value pair or change an existing pair
  • del dict[]: Deletes a dictionary’s key-value pair based on the specified key

Try-Except

Try-Except code blocks tries to run a block of code, and if an error is raised from attempting to run that code, then an exception is raised instead that is specified by the user.

For example:

eg_list = [1, 2, 3, 4, 5, 6]
position = 9
try:
  print(eg_list[position])
except:
  print(f"Invalid position. Expected a value between 0 and {len(eg_list)-1} but got '{position}' instead.")
Invalid position. Expected a value between 0 and 5 but got '9' instead.