Python QuickStart for People Learning AI

-

Many computers include Python pre-installed. To see in case your machine has it, go to your Terminal (Mac/Linux) or Command Prompt (Windows), and easily enter “python”.

Using Python in Terminal. Image by creator.

In the event you don’t see a screen like this, you may download Python manually (Windows/ Mac). Alternatively, one can install Anaconda, a well-liked Python package system for AI and data science. In the event you run into installation issues, ask your favorite AI assistant for help!

With Python running, we will now start writing some code. I like to recommend running the examples in your computer as we go along. You may also download all the instance code from the GitHub repo.

Strings & Numbers

A data type (or simply “type”) is a strategy to classify data in order that it may possibly be processed appropriately and efficiently in a pc.

Types are defined by a possible set of values and operations. For instance, strings are arbitrary character sequences (i.e. text) that could be manipulated in specific ways. Try the next strings in your command line Python instance.

"this can be a string"
>> 'this can be a string'
'so is that this:-1*!@&04"(*&^}":>?'
>> 'so is that this:-1*!@&04"(*&^}":>?'
"""and
that is
too!!11!"""
>> 'andn this isn too!!11!'
"we will even " + "add strings together"
>> 'we will even add strings together'

Although strings could be added together (i.e. concatenated), they will’t be added to numerical data types like int (i.e. integers) or float (i.e. numbers with decimals). If we try that in Python, we’ll get an error message because operations are only defined for compatible types.

# we will not add strings to other data types (BTW that is the way you write comments in Python)
"I'm " + 29
>> TypeError: can only concatenate str (not "int") to str
# so we now have to write down 29 as a string
"I'm " + "29"
>> 'I'm 29'

Lists & Dictionaries

Beyond the fundamental varieties of strings, ints, and floats, Python has types for structuring larger collections of knowledge.

One such type is a list, an ordered collection of values. We will have lists of strings, numbers, strings + numbers, and even lists of lists.

# an inventory of strings
["a", "b", "c"]

# an inventory of ints
[1, 2, 3]

# list with a string, int, and float
["a", 2, 3.14]

# an inventory of lists
[["a", "b"], [1, 2], [1.0, 2.0]]

One other core data type is a dictionary, which consists of key-value pair sequences where keys are strings and values could be any data type. That is an excellent strategy to represent data with multiple attributes.

# a dictionary
{"Name":"Shaw"}

# a dictionary with multiple key-value pairs
{"Name":"Shaw", "Age":29, "Interests":["AI", "Music", "Bread"]}

# an inventory of dictionaries
[{"Name":"Shaw", "Age":29, "Interests":["AI", "Music", "Bread"]},
{"Name":"Ify", "Age":27, "Interests":["Marketing", "YouTube", "Shopping"]}]

# a nested dictionary
{"User":{"Name":"Shaw", "Age":29, "Interests":["AI", "Music", "Bread"]},
"Last_login":"2024-09-06",
"Membership_Tier":"Free"}

Up to now, we’ve seen some basic Python data types and operations. Nonetheless, we’re still missing a necessary feature: variables.

Variables provide an abstract representation of an underlying data type instance. For instance, I’d create a variable called user_name, which represents a string containing my name, “Shaw.” This allows us to write down flexible programs not limited to specific values.

# making a variable and printing it
user_name = "Shaw"
print(user_name)

#>> Shaw

We will do the identical thing with other data types e.g. ints and lists.

# defining more variables and printing them as a formatted string. 
user_age = 29
user_interests = ["AI", "Music", "Bread"]

print(f"{user_name} is {user_age} years old. His interests include {user_interests}.")

#>> Shaw is 29 years old. His interests include ['AI', 'Music', 'Bread'].

Now that our example code snippets are getting longer, let’s see the right way to create our first script. That is how we write and execute more sophisticated programs from the command line.

To do this, create a brand new folder in your computer. I’ll call mine python-quickstart. If you’ve got a favourite IDE (e.g., the Integrated Development Environment), use that to open this recent folder and create a brand new Python file, e.g., my-script.py. There, we will write the ceremonial “Hello, world” program.

# ceremonial first program
print("Hello, world!")

In the event you don’t have an IDE (not beneficial), you should utilize a basic text editor (e.g. Apple’s Text Edit, Window’s Notepad). In those cases, you may open the text editor and save a brand new text file using the .py extension as an alternative of .txt. Note: In the event you use TextEditor on Mac, you might must put the applying in plain text mode via Format > Make Plain Text.

We will then run this script using the Terminal (Mac/Linux) or Command Prompt (Windows) by navigating to the folder with our recent Python file and running the next command.

python my-script.py

Congrats! You ran your first Python script. Be at liberty to expand this program by copy-pasting the upcoming code examples and rerunning the script to see their outputs.

Two fundamental functionalities of Python (or another programming language) are loops and conditions.

Loops allow us to run a specific chunk of code multiple times. The preferred is the for loop, which runs the identical code while iterating over a variable.

# a straightforward for loop iterating over a sequence of numbers
for i in range(5):
print(i) # print ith element

# for loop iterating over an inventory
user_interests = ["AI", "Music", "Bread"]

for interest in user_interests:
print(interest) # print each item in list

# for loop iterating over items in a dictionary
user_dict = {"Name":"Shaw", "Age":29, "Interests":["AI", "Music", "Bread"]}

for key in user_dict.keys():
print(key, "=", user_dict[key]) # print each key and corresponding value

The opposite core function is conditions, comparable to if-else statements, which enable us to program logic. For instance, we should want to check if the user is an adult or evaluate their wisdom.

# check if user is eighteen or older
if user_dict["Age"] >= 18:
print("User is an adult")

# check if user is 1000 or older, if not print they've much to learn
if user_dict["Age"] >= 1000:
print("User is smart")
else:
print("User has much to learn")

It’s common to use conditionals inside for loops to use different operations based on specific conditions, comparable to counting the variety of users excited about bread.

# count the variety of users excited about bread
user_list = [{"Name":"Shaw", "Age":29, "Interests":["AI", "Music", "Bread"]},
{"Name":"Ify", "Age":27, "Interests":["Marketing", "YouTube", "Shopping"]}]
count = 0 # intialize count

for user in user_list:
if "Bread" in user["Interests"]:
count = count + 1 # update count

print(count, "user(s) excited about Bread")

Functions are operations we will perform on specific data types.

We’ve already seen a basic function print(), which is defined for any datatype. Nonetheless, there are just a few other handy ones value knowing.

# print(), a function we have used several times already
for key in user_dict.keys():
print(key, ":", user_dict[key])

# type(), getting the information style of a variable
for key in user_dict.keys():
print(key, ":", type(user_dict[key]))

# len(), getting the length of a variable
for key in user_dict.keys():
print(key, ":", len(user_dict[key]))
# TypeError: object of type 'int' has no len()

We see that, unlike print() and type(), len() isn’t defined for all data types, so it throws an error when applied to an int. There are several other type-specific functions like this.

# string methods
# --------------
# make string all lowercase
print(user_dict["Name"].lower())

# make string all uppercase
print(user_dict["Name"].upper())

# split string into list based on a particular character sequence
print(user_dict["Name"].split("ha"))

# replace a personality sequence with one other
print(user_dict["Name"].replace("w", "whin"))

# list methods
# ------------
# add a component to the tip of an inventory
user_dict["Interests"].append("Entrepreneurship")
print(user_dict["Interests"])

# remove a particular element from an inventory
user_dict["Interests"].pop(0)
print(user_dict["Interests"])

# insert a component into a particular place in an inventory
user_dict["Interests"].insert(1, "AI")
print(user_dict["Interests"])

# dict methods
# ------------
# accessing dict keys
print(user_dict.keys())

# accessing dict values
print(user_dict.values())

# accessing dict items
print(user_dict.items())

# removing a key
user_dict.pop("Name")
print(user_dict.items())

# adding a key
user_dict["Name"] = "Shaw"
print(user_dict.items())

While the core Python functions are helpful, the true power comes from creating user-defined functions to perform custom operations. Moreover, custom functions allow us to write down much cleaner code. For instance, listed here are among the previous code snippets repackaged as user-defined functions.

# define a custom function
def user_description(user_dict):
"""
Function to return a sentence (string) describing input user
"""
return f'{user_dict["Name"]} is {user_dict["Age"]} years old and is excited about {user_dict["Interests"][0]}.'

# print user description
description = user_description(user_dict)
print(description)

# print description for a brand new user!
new_user_dict = {"Name":"Ify", "Age":27, "Interests":["Marketing", "YouTube", "Shopping"]}
print(user_description(new_user_dict))

# define one other custom function
def interested_user_count(user_list, topic):
"""
Function to count variety of users excited about an arbitrary topic
"""
count = 0

for user in user_list:
if topic in user["Interests"]:
count = count + 1

return count

# define user list and topic
user_list = [user_dict, new_user_dict]
topic = "Shopping"

# compute interested user count and print it
count = interested_user_count(user_list, topic)
print(f"{count} user(s) excited about {topic}")

Although we could implement an arbitrary program using core Python, this could be incredibly time-consuming for some use cases. Considered one of Python’s key advantages is its vibrant developer community and a sturdy ecosystem of software packages. Almost anything it is advisable to implement with core Python (probably) already exists as an open-source library.

We will install such packages using Python’s native package manager, pip. To put in recent packages, we run pip commands from the command line. Here is how we will install numpy, a necessary data science library that implements basic mathematical objects and operations.

pip install numpy

After we’ve installed numpy, we will import it right into a recent Python script and use a few of its data types and functions.

import numpy as np

# create a "vector"
v = np.array([1, 3, 6])
print(v)

# multiply a "vector"
print(2*v)

# create a matrix
X = np.array([v, 2*v, v/2])
print(X)

# matrix multiplication
print(X*v)

The previous pip command added numpy to our base Python environment. Alternatively, it’s a best practice to create so-called virtual environments. These are collections of Python libraries that could be readily interchanged for various projects.

Here’s the right way to create a brand new virtual environment called my-env.

python -m venv my-env

Then, we will activate it.

# mac/linux
source my-env/bin/activate

# windows
.my-envScriptsactivate.bat

Finally, we will install recent libraries, comparable to numpy, using pip.

pip install pip

Note: In the event you’re using Anaconda, take a look at this handy cheatsheet for making a recent conda environment.

Several other libraries are commonly utilized in AI and data science. Here’s a non-comprehensive overview of some helpful ones for constructing AI projects.

A non-comprehensive overview of Python libs for data science and AI. Image by creator.

Now that we now have been exposed to the fundamentals of Python, let’s see how we will use it to implement a straightforward AI project. Here, I’ll use the OpenAI API to create a research paper summarizer and keyword extractor.

Like all the opposite snippets on this guide, the instance code is obtainable on the GitHub repository.

ASK ANA

What are your thoughts on this topic?
Let us know in the comments below.

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Share this article

Recent posts

0
Would love your thoughts, please comment.x
()
x