Python Introduction
I started this section by following this video to "Learn Python in 1 Hour", but then immediately got distracted by Python's potential and went down a rabbit hole.[1]
Also, if you want some real data to mess with[2], you can use Kaggle to access a TON of CSV files on a range of topics.
Key Features and Definitions in Python
- Case-sensitive
- "True" represents the Boolean true value, and "true" is just a string
- Object-oriented
- Bundles attributes and functions to individual units (objects)
- Classes identify which attributes are used to define a type of object
- e.g.,
class Hognose:
- e.g.,
- Methods are used by Classes to define or represent the specific attributes
- The method
def __init__(self,...)
defines attributes for the class, and then to further define the attributes.- e.g.,
def __init__(self, name, age, length, ...) # Identifies the attributes name, age, length, etc. to define the class
self.age = int(years) # Identifies the age for the Hognose class as the "years" variable converted to an integer.
- e.g.,
- The method
def __repr__(self):...
provides an "official" string representation of the object- e.g.,
def __repr__(self): # Initiates representation.
return (f"Hognose(name='{self.name}', age={self.age},...) # Returns
- e.g.,
- The method
- Primitive data types
- Strings
- Unformatted, considered text
"12"
is a string, and cannot be added to or subtracted from
- Special note
- F-Strings are a special kind of formatting for strings, introduced in Python 3.6, which allow you to easily input variables into a string.
- Variables are identified using curly[3] brackets
- e.g.
greeting = f'Hello, my name is {name} and I am {age} years old.'
- Unformatted, considered text
- Integers
- Whole numbers that can be manipulated with equations
1+1
will equate to2
- Can also convert strings to integers with
int()
(see example below)birth_year = input("Enter your birth year (YYYY): ") # Accepts the birth year from a user as a string
int(birth_year) # Converts the "birth_year" variable from a string to an integer
- Float
- "Floating point number", which are rational numbers that usually end in decimal figures
- e.g.,
3.14
or0.5
- Boolean
- Simple
True
andFalse
or 1 and 0 - Boolean values[4]
- Simple
- Conversion Functions
- Strings, integers, float, and Boolean data types all have associated functions that convert values from one type to another
- The functions are
str()
,int()
,float()
, andbool()
- For example,
int(age)
will convert the "age" variable into an integer
- For example,
- Function
bool()
evaluates any value as "True" or "False"- True in this case effectively refer to any non-null[5] value
- Even
-1
returns True
- Strings
- Non-primitive data types (non-comprehensive)
- Lists
- Holds a large number of items of any data type
- Highly flexible; items can be added or removed
- Arrays
- Not natively supported in Python
- Like lists, but more efficient when handling large data sets of the same type
- Tuples
- Not a sex thing[6], but is an ordered list of values.
- There can be duplicates, and they are not changeable once created
- Dictionary
- A list of key-value pairs.
- The keys must be unique, but the values do not
- e.g.,
dictionary = {'a': 1, 'b': 2, 'c': 1}
- a, b, and c are the unique keys, followed by their values
- e.g.,
- The keys must be unique, but the values do not
- A list of key-value pairs.
- Lists
- Style guide
- PEP (Python Enhancement Proposals)
- PEP 8 – Style Guide for Python Code | peps.python.org
- This is a style guide with a bunch of specific recommendations
- CapWord Convention
- When stringing a bunch of words together, capitalize the first letter of each word
- e.g. BigHairySpider
- Typically reserved for class names
- NOTE: Sometimes IDEs like PyCharm are too smart for their own good, and will read words like "Hognose" as a violation of this convention (it expects "HogNose")
- In PyCharm, if you're working with a term frequently, this can be resolved by adding it to PyCharm's dictionary
- Right-click the alert, select "Show Quick-Fixes", and then "Save 'Hognose' to dictionary"
- When stringing a bunch of words together, capitalize the first letter of each word
- snake_case convention
- String words together with underscores
_
instead of capital letters- e.g., big_hairy_spider
- Typically used for functions, methods, and variables
- String words together with underscores
- Commenting
- Comments should be written as a sentence, begin with a capital letter, end with a period, and are identified with a pound and single space (
#
) at the start - Block comments begin at the start of a line
- e.g.,
# This is a comment.
- e.g.,
- Inline comments should be used sparingly
- Don't state the obvious
- e.g.,
x = y + 1 # Compensate for image border.
- Where
y
is the true edge of the image, andx
is the image edge with 1 pixel buffer-zone for a stylized border.
- Where
- Comments should be written as a sentence, begin with a capital letter, end with a period, and are identified with a pound and single space (
- PEP (Python Enhancement Proposals)
- Objects
- Any variable can be an object, and can have methods run against it
- The changes do not impact the original variable; they create a new variable in memory.
- e.g.,
snake.upper()
d
- e.g.,
- e.g., let's say we have the variable
snake = "my best friend hoggy the hognose"
; we can use methods to manipulate the value.- find:
snake.find("Hog")
to find if the string "Hog" exists in the value- If it exists, the output is the position of the first character, starting at
0
- If it doesn't exist, the output is
-1
- If it exists, the output is the position of the first character, starting at
- capitalize:
snake.capitalize()
would capitalize the first letter of the string- Printing this gives us "My best friend..." instead of "my best friend..."
- replace:
snake.replace(x,y)'
to replace valex
with valuey
snake.replace('friend','buddy')
would result in "my best buddy..."
- find:
- The changes do not impact the original variable; they create a new variable in memory.
- Any variable can be an object, and can have methods run against it
Basic/Imporant Commands/tools
print()
- Print the contents of the parenthesis to the console
variable = value
- Declare a variable
- Used in code without quotes
3. For example, let's saynice = 69
4.print(nice)
would print the value ofnice
, 69
5.print("nice")
would print the string "nice" (but without the quotes)
datetime
- datetime — Basic date and time types — Python 3.12.2 documentation
strptime()
converts a string into a datetime object, andstrftime()
converts a datetime object into a string
Hognose Census Project
Let's say we have a CSV list of hognose snakes with a bunch of data. The CSV was created by a human for humans, and has pretty long headers to help human operators input correct information.
We want to ingest the data from the CSV file, converting strings into their most appropriate value type (Boolean, integer, datetime, etc.) for maximum utility.
For this project, I'm going to over-comment to help the tl;drs out there.