- WaSQL Wired
- Posts
- Python Crash Course
Python Crash Course
What you need to know to become a python guru.
Python has become a very popular scripting language and continues to be a critical player in the emerging field of AI. Python's simplicity also makes it ideal for writing scripts to automate system tasks, data processing, and repetitive workflows.
To help you get up to speed, this article provides a crash course in Python, covering everything from the basics to some more advanced concepts.
Python runs on both Windows and Linux and is relatively easy to install. Simply visit python.org for download and installation instructions. For this course, we will use Windows, as that is the operating system I am using while writing this article. Once installed, you can verify the installation by running the following command from a command prompt (DOS prompt). Note that I am currently running Python version 3.11.3.
python --version
Python 3.11.3
Now that python is installed lets go over the basics…and a bit beyond. Note: take your time as you go over the following sections. Try to put what you learn to long term memory. They are things you will use nearly every time to write a python program.
First, let's talk about comments. Comments are extremely useful and provide a wonderful way to document your code. There are 5 main reasons to add comments when writing code:
Explanation: Comments clarify complex logic, helping other developers (and yourself) understand the code's purpose and approach.
Documentation: They provide context about why specific code choices were made, function purposes, and expected inputs/outputs.
Debugging: Comments can mark problematic sections, note known issues, or explain workarounds.
Collaboration: They facilitate easier teamwork by making code more readable and maintainable.
Future Reference: When you return to code months later, comments help you quickly recall your original thinking and implementation strategy.
Good comments explain "why" something is done, not just "what" is happening, which can typically be understood from the code itself. There are two ways to add comments in Python: single-line comments and multi-line comments.
# this is a single line comment
'''
This is a multiline comment
that spans multiple
lines
'''
print('Helo World')
#I also like to add comments before functions in a JSDocs format
#---------- begin function encodeHtml
# @describe encodes html chars that would mess up in a browser
# @param str string - string to encode
# @return str - HTML encoded string
# @usage html=encodeHtml(str)
def encodeHtml(str=''):
if(len(str)==0):
return str
str=str.replace('?','[[!Q!]]')
str=str.replace('<','<')
str=str.replace('>','>')
str=str.replace('"','"')
str=str.replace('[[!Q!]]','?')
return str
Next is code syntax. In Python there are two main syntax elements to note: indentation (tabs) and colons. The wrong indentation or a missing colon will cause your code to fail.
Below is an example of three functions, isWindows and getParentPath and greet. Notice the colon after the function is defined def isWindows(): and the colon after each logical code block. Every time you use a colon : to define a code clock you also need to tab the content of the code block in so that Python knows when that block ends. Also note that Python does NOT use semi-colons at the end of a line (like PHP or JavaScript). The third function is an example of setting default values in function parameters.
#---------- begin function isWindows ----------
# @describe returns true if script is running on a Windows platform
# @return boolean
# @usage if(common.isWindows()):
def isWindows():
if sys.platform == 'win32':
return True
elif sys.platform == 'win32':
return True
elif sys.platform == 'win64':
return True
elif os.name == 'nt':
return True
else:
return False
#---------- begin function getParentPath
# @describe gets the parent path
# @return string - absolute path of parent
# @usage ppath=getParentPath()
def getParentPath(path):
return os.path.abspath(os.path.join(path, os.pardir))
#below is a python function with a default value
#---------- begin function greet
# @describe returns a greet message
# @param name string - required
# params age integer - defaults to 30
# @return string
# @usage print(greet('Bob'))
# @usage print(greet())
def greet(name,age=30):
return f"Hello, {name}. How does it feel to be {age}"
Up next are variables. In Python, you do not need to explicitly declare variable types; however, the following variable types exist: Integers (int), Floats (float), Strings (str), Booleans (bool), Lists, Tuples, and Dictionaries. The following examples demonstrate each variable type.
x = 10 #int
y = 9.45 #float
name = "Alice" #string
is_student = True #boolean True or False
#lists (called arrays in other languages)
numbers= [12,33,44,1] #list definition
numbers.append(63) #adds element to end of a list
numbers.insert(5) #adds element to the beginning of a list
last = numbers.pop() #removes and returns the last item in a list
first = numbers.pop(0) #removes and returns the first item in a list
#tuples - Once created, tuples cannot be modified
fruits = ("apple", "banana", "cherry") #tuple definition
#dictionary (also called JSON in other languages)
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'} #dictionary definition
# NOTE: lists can also contain other data types. Here is a list of dictionaries. Useful for storing records from a database
recs = [{"name":"bob","age":22},{"name":"sam","age":19}]
Now lets look at Python’s text functions. These are worth memorizing as you will likely use them in nearly every script you write.
#assign a string to a variable
text = "Hello, World!"
# Case modifications
text.upper() # "HELLO, WORLD!"
text.lower() # "hello, world!"
text.capitalize() # "Hello, world!"
text.title() # "Hello, World!"
# Whitespace handling
text.strip() # Removes whitespace from both ends
text.lstrip() # Removes whitespace from left
text.rstrip() # Removes whitespace from right
# Splitting and joining
parts = text.split(",") # Splits into list: ["Hello", " World!"]
text = ",".join(parts) # Joins list with separator:
# Replacement
text.replace("World", "Python") # "Hello, Python!"
# Checking string content
text.startswith("Hello") # Boolean - checks for starts with
text.endswith("!") # Boolean - checks for ends with
text.isdigit() # Boolean - checks for numeric
text.isalpha() # Boolean - checks for alpha
text.isalnum() # Boolean - checks for alphanumeric
text.find("World") # Returns 7 (index where found)
text.count("l") # Returns 3 (number of occurrences)
if "World" in text: # Returns True (membership check)
# Formatting a string is done in two main ways. f-strings are more modern so if you are writing code that must be backwards compatible you should consider using the .format method
name = "Alice"
age = 30
person = f"Name: {name}, Age: {age}" # f-strings (modern)
person = "Name: {}, Age: {}".format(name, age) # .format() method
# Indexing and slicing
text[0] # "H" (first character)
text[-1] # "!" (last character)
text[7:12] # "World" (slice from index 7 to 11)
text[:5] # "Hello" (start to index 4)
text[7:] # "World!" (index 7 to end)
When writing Python you will often need to write conditional code. To do so you will likely use an if statement. Below is an example of an if/else statement. Notice that in If, else if, else statements the else if is written as elif
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is 10")
else:
print("x is less than 10")
Loops allow you to iterate through variables, like lists and dictionaries, that contain multiple elements of data.
#iterate a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
#iterate a dictionary. Note that we are capturing the key and the value
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
for key, value in person.items():
print(f"{key}: {value}")
#iterate a list of dictionaries
people = [
{"name":"bob","age":22},
{"name":"sam","age":19}
]
for person in people:
print(f"Name: {person['name']}, Age: {person['age']}")
While loops are also useful at times but BE CAREFUL when writing while loops so that you do not write an infinite loop.
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1
response = ""
while response != "quit":
response = input("Enter a command (type 'quit' to exit): ")
print(f"You entered: {response}")
#this is an example of an infinite loop. This is really BAD.
b = 0
while b < 5:
print("this is an infinite loop")
#this is the how to fix the infinite loop above
b = 0
while b < 5:
print("hello again")
b += 1
As you have seen in earlier examples, Functions are defined with def. Function arguments are defined in parenthesis after the function name.
def greet(name):
return "Hello, " + name
print(greet("Alice"))
Files - To read and write to files, use the open() function. The second parameter specifies the file mode - read, write, or append - w for write, r for read, and a for append. When reading and writing files your code needs to open AND close the file so that you do not leave files in an open state. However Python has cool little shortcut called “with open” that will automatically close the file for you.
# Writing to a file and explicitly opening and closing the file
file = open('example.txt', 'w')
file.write('Another line of text\n')
file.close()
# Writing to a file using with open
with open("file.txt", "w") as file:
file.write("Hello, World!")
# File is automatically closed here
# Reading from a file using with open
with open("file.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here
# appending to an existing file using with open
with open("file.txt", "a") as file:
file.write("Hello, World!")
# File is automatically closed here
Even if you are an incredible coder and never write code that has errors you still need to handle errors, especially if your code allows for user input. For error handling use the try/except method as shown below
#catches a division by zero error
x = 0
try:
result = 10 / x # Raises ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero!")
#handle errors when file is not found
try:
file = open('example.txt', 'r')
# file operations
except FileNotFoundError:
print("File not found")
finally:
file.close() # Ensures file is closed
There are many different Python error types that can be captured in a try/except block. Here are the most common.
ZeroDivisionError: Raised when dividing by zero
FileNotFoundError: Raised when a file or directory is requested but doesn't exist
TypeError: Raised when an operation is performed on an inappropriate type
ValueError: Raised when a function receives an argument of the correct type but inappropriate value
IndexError: Raised when trying to access an index that doesn't exist in a sequence
KeyError: Raised when trying to access a dictionary key that doesn't exist
AttributeError: Raised when an attribute reference or assignment fails
PermissionError: Raised when an operation lacks proper permissions
ConnectionError: Base class for connection-related errors
ImportError: Raised when an import statement fails
Lastly, the import statement in Python is used to bring in modules or packages of code, making their functions, classes, and other definitions available for use in your current program.
import math
print(math.sqrt(16)) # Square root
There are many python modules. Some are included when you install Python. Others have to be installed. Python modules are installed from the command line as follows:
python -m pip install {module_name}
Here are some of the most commonly used Python modules:
Standard Library - included in most Python installs so you probably do not need to install these to use them.
os: Operating system interactions
sys: System-specific parameters/functions
datetime: Date and time handling
random: Random number generation
math: Mathematical functions
json: JSON encoding/decoding
re: Regular expressions
collections: Advanced container datatypes
logging: Logging system events
Data Science/Analysis:
numpy: Numerical computing
pandas: Data manipulation/analysis
matplotlib: Data visualization
scipy: Scientific computing
Web/Network:
requests: HTTP requests
flask: Web framework
django: Web framework
Utility:
itertools: Iterator functions
functools: Higher-order functions
typing: Type hints
Congratulations on making it to the end of this article! If you're feeling a bit overwhelmed, I highly recommend re-reading it at least three more times before next Friday. Repetition will help immensely. You'll be surprised how much it aids you on your path to becoming a Python guru. After you have these mastered I recommend learning how to connect and query databases. Perhaps there will be a future article on just that….
Thanks again for reading. Please like and SHARE. 🙂