Many computers come with Python pre-installed. To check if your computer has Python installed, go to Terminal (Mac/Linux) or Command Prompt (Windows) and simply type “python”.
If you don’t see a screen like this, you can download Python manually (Windows/Mac). Or, you can install Anaconda, a popular Python package system for AI and data science. If you have installation issues, Ask your favorite AI assistant for help!
Now that we have Python running, we can write some code. As we proceed, it is a good idea to run the examples on your computer.. You can also download all the example code from our GitHub repository.
Strings and numbers
no way Data Type (or simply “type”) How to categorize data so that it can be processed properly and efficiently by a computer..
A type is defined by a set of possible values ​​and operations. For example, hyeon ~is Any character sequence (i.e. text that can be manipulated in a specific way). Try the following string in a command-line Python instance:
"this is a string"
>> 'this is a string'
'so is this:-1*!@&04"(*&^}":>?'
>> 'so is this:-1*!@&04"(*&^}":>?'
"""and
this is
too!!11!"""
>> 'and\n this is\n too!!11!'
"we can even " + "add strings together"
>> 'we can even add strings together'
Strings can be added together (i.e. concatenated), but not appended one after the other. Numeric data type good night int (i.e. integer) or float (i.e. a number with a decimal point). If you try this in Python, you’ll get an error message because operations are only defined for compatible types.
# we can't add strings to other data types (BTW this is how you write comments in Python)
"I am " + 29
>> TypeError: can only concatenate str (not "int") to str
# so we have to write 29 as a string
"I am " + "29"
>> 'I am 29'
Lists and dictionaries
In addition to the basic types of strings, integers, and floats, Python has types for structuring larger collections of data.
One such type is: inventoryone A collection of sorted values. can have strings, numbers, or lists of strings. + It is also a list of numbers, or lists.
# a list of strings
["a", "b", "c"]# a list of ints
[1, 2, 3]
# list with a string, int, and float
["a", 2, 3.14]
# a list of lists
[["a", "b"], [1, 2], [1.0, 2.0]]
Other core data types include: dictionaryIt consists of the following Sequence of key-value pairs where key is a string and The value can be of any data type. This is a good way 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"]}
# a list 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"}
So far we’ve looked at the basic Python data types and operations, but we’re still missing an essential feature: variables.
Variable provide Abstract representation of instances of basic data types.. For example, I could create a variable called user_name that represents a string containing my name “Shaw”. This allows me to write flexible programs that are not limited to specific values.
# creating a variable and printing it
user_name = "Shaw"
print(user_name)#>> Shaw
You can do the same thing for other data types, such as integers 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 sample code snippet is long, let’s look at how to create our first script. This will do it: Write and run more sophisticated programs from the command line..
To do this, create a new folder on your computer. Let’s call mine: Python – Quickstart. If there is something you like IDE (e.g. integrated development environment)Using this, we open this new folder and create a new Python file (e.g. my-script.py). There we can write our conscious “Hello, world” program.
# ceremonial first program
print("Hello, world!")
If you don’t have an IDE (not recommended), you can use a basic text editor (e.g. Text Edit on Apple, Notepad on Windows). In that case, you can do the following: Open a text editor and save a new text file using the .py extension instead of .txt. Note: If you are using TextEditor on a Mac, you may need to switch the application to plain text mode via Format > Make Plain Text.
You can then run this script by navigating to the folder containing the new Python file in Terminal (Mac/Linux) or Command Prompt (Windows) and running the following command:
python my-script.py
Congratulations! You have run your first Python script. Feel free to Extend this program by copying and pasting the following code examples and re-running the script. I want to see their results.
Two basic features of Python (or any programming language) are loops and conditionals.
Loop Please give us permission Execute a specific chunk of code multiple times. The most popular one is for loopExecutes the same code while iterating over variables.
# a simple for loop iterating over a sequence of numbers
for i in range(5):
print(i) # print ith element# for loop iterating over a list
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
Other key features include: conditionsFor example, if-else statements Let us program the logicFor example, you might want to check if a user is an adult or assess their wisdom.
# check if user is 18 or older
if user_dict["Age"] >= 18:
print("User is an adult")# check if user is 1000 or older, if not print they have much to learn
if user_dict["Age"] >= 1000:
print("User is wise")
else:
print("User has much to learn")
It is common Use conditional statements within for loops Apply different actions based on specific conditions, such as counting the number of users interested in bread.
# count the number of users interested in bread
user_list = [{"Name":"Shaw", "Age":29, "Interests":["AI", "Music", "Bread"]},
{"Name":"Ify", "Age":27, "Interests":["Marketing", "YouTube", "Shopping"]}]
count = 0 # intialize countfor user in user_list:
if "Bread" in user["Interests"]:
count = count + 1 # update count
print(count, "user(s) interested in Bread")
function ~is Actions that can be performed on specific data types.
We have already seen the basic functions print()It’s defined for all data types, but there are a few other handy things to know.
# print(), a function we've used several times already
for key in user_dict.keys():
print(key, ":", user_dict[key])# type(), getting the data type 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 it, differently print() and category(), length() It is not defined for all data types, so applying it to int will result in an error. There are several others. Features by type so.
# 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 specific character sequence
print(user_dict["Name"].split("ha"))
# replace a character sequence with another
print(user_dict["Name"].replace("w", "whin"))
# list methods
# ------------
# add an element to the end of a list
user_dict["Interests"].append("Entrepreneurship")
print(user_dict["Interests"])# remove a specific element from a list
user_dict["Interests"].pop(0)
print(user_dict["Interests"])
# insert an element into a specific place in a list
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())
Core Python functions are helpful, but the real power comes from creating: User defined functions to Perform custom actions. Also, using user-defined functions allows you to write much cleaner code. For example, here’s some of 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 interested in {user_dict["Interests"][0]}.'# print user description
description = user_description(user_dict)
print(description)
# print description for a new user!
new_user_dict = {"Name":"Ify", "Age":27, "Interests":["Marketing", "YouTube", "Shopping"]}
print(user_description(new_user_dict))
# define another custom function
def interested_user_count(user_list, topic):
"""
Function to count number of users interested in an arbitrary topic
"""
count = 0for 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) interested in {topic}")
We can implement arbitrary programs using core Python, but this can be prohibitively time-consuming for some use cases. One of the main advantages of Python is that A vibrant developer community and a robust software package ecosystem.. Most things you want to implement in core Python already exist as open source libraries.
We can install these packages using: Python’s default package manager, pip. To install a new package, run the pip command from the command line. Here’s how to install it: Numpy, Essential Data Science Libraries Implements basic mathematical objects and operations.
pip install numpy
After installing numpy, you can import it into a new Python script and use some 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 the default Python environment, or better yet, create one. Virtual environment. These are A collection of Python libraries that are easily compatible with a variety of projects..
Here’s how to create a new virtual environment: My environment.
python -m venv my-env
Then you can activate it.
# mac/linux
source my-env/bin/activate# windows
.\my-env\Scripts\activate.bat
Finally, you can use pip to install new libraries like numpy.
pip install pip
Note: If you are using Anaconda, check this out. A handy cheat sheet How to create a new conda environment.
Several other libraries are commonly used in AI and data science. Here are some: A non-comprehensive overview of some things that are useful for building AI projects..
Now that you know the basics of Python, let’s look at how to implement a simple AI project using it. Here, we’ll create a research paper summarizer and keyword extractor using the OpenAI API.
As with all other code snippets in this guide, the example code is available in the GitHub repository.