Python is a popular interpreted, interactive, object-oriented, high-level, and beginner friendly programming language used in a variety of general-purpose applications. It was created by Guido van Rossum and was first released in 1991.
Python powers many websites and applications that you use everyday. Some of the most popular uses are:
- YouTube
- Google Search Engine
- Spotify
This resource is intended to help you learn the basics of Python along with the Introduction to Programming course.
Data is information. In Python, there are several different ways to represent data or information. For example, a person's age is stored as a number, his or her name is stored as alphabetic characters, and his or her home address is stored as alphanumeric characters. Not only can we store data in Python we can also perform operations on the data.
Below are the most commonly used data types in Python.
- Numbers
- String
- List
- Tuple
- Dictionary
It is important to understand the type of data that you are working with because all data types behave differently in Python.
Variables are names attached to memory locations, and they store information for us. For example, we can create a variable called age and another called name. We can then tell the computer to assign a value to the variable. To do this, we use an assignment statement.
name = "Severus Snape"
age = 37
Assignment statements consist of a variable name, an equal sign, and either a value or a computation.
greeting = "Hello " + name
print(greeting)
# returns Hello Severus Snape
The + is used to “add” strings together (known as string concatenation). In this case, we are creating a string of "Hello " (with a space) and a name combined together, placed into the variable greeting. Now if greeting is written by itself (calling the variable) Python returns the string combination: Hello Severus Snape
Assignment statements are often used not just to store values but to perform computations. One type of computation is to change a value already stored in a variable. For this, we use a variation of the assignment statement where the variable appears on both the left and right side of the equal sign.
It is now Snape's birthday so let’s add 1 to age. Consider the following sequence:
age = 37
age = age + 1
print(age) # returns 38
In a program, this means “take the value of age, add 1, and store the result in age.”
In Python there are 2 types of numbers that we will be working with, ints and floats.
An int, which stands for integer, is a whole number, positive or negative, without decimals.
42
1001
-978137415700
A float, which stands for "floating point number" is a number, positive or negative, containing one or more decimals.
42.0
1.001
3.14159265359
Ints and floats operate just like the numbers you've worked with all your life. Formulas and calculations even follow the rules of PEMDAS in Python. Here are the basic operations for numbers that we'll be using:
4 + 2 # addition, returns 6
4 - 2 # subtraction, returns 2
4 * 1 # multiplication, reutrns 4
4 / 2 # division, returns 2.0
4 // 2 # floor division, returns 2
4 ** 2 # exponent, returns 16
4 % 2 # modulo, returns 0
I assume you know addition, subtraction, multiplication, and division so let's cover floor division, exponents, and modulo operators.
# regular division
10 / 5 # returns 2.0
# floor division
10 // 5 # returns 2
You may notice, regular division returns the answer as a float. Floor division returns the answer as an integer. Floor division rounds down. Even if the number is 1.999999, floor division will return 1.
# exponents
3 ** 2 # returns 9
5 ** 2 # reutrns 25
2 ** 10 # returns 1024
You're familiar with exponents from Algebra so there isn't much to cover except how to use an exponent in Python. We'll use two asterisks in order to use exponents.
# modulo
3 % 2 # returns 1
4 % 2 # returns 0
5 % 2 # returns 1
6 % 2 # reutrns 0
8 % 5 # returns 3
The % (modulo) operator yields the remainder from the division of the first argument by the second. Essentially, modulo returns whatever is left over when you divide two numbers. It's not an operator that we'll use often but it's important to know
A string is a series of characters placed inside quotations marks. You can use either double or single quotes.
"Expelliarmus"
Individual characters in a string can be accessed using it's location or index. The first character in a string is located at position 0. The second character is at position 1. All programmers start counting at 0.
"Expelliarmus"[0] # returns "E"
"Expelliarmus"[8] # returns "r"
"Harry Potter and the Goblet of Fire"
Strings can also be broken down (sliced) into substrings using the slice operator. A slice operator is reprsented with square brackets and takes multiple indexes to know what characters to slice.
"Expelliarmus"[0:5] # returns "Expel"
"Wingardium Leviosa"[3:7] # returns "gard"
"Avada Kedavra"[3:8]" # returns "da Ke"
Notice that the first index in the slice operator is what position in the string the slice begins. The second index number is what character to slice up to but won't be included.
We use lists daily. Students follow a schedule which is a list of classes. Teachers take attendance with a list of student names. People purchase food using a grocery list. A music playlist is a list of songs. Some of us write to-do lists to help us organize our lives.
In Python, a list is created using square brackets [ ] and contains items separated by commas.
# list of student names
students = ["Harry Potter", "Hermione Granger", "Ronald Weasley", "Draco Malfoy"]
# list of grades
grades = [97, 88, 100, 76, 100]
Lists can contain any type of data or even a combination of all types.
list_all_data = ["A", "z", 1, 3.14, ["a", "list", "inside", "a list"], ":)"]
Like strings, the contents or items of a list can be accessed using indexes. Remember, in Python, we begin counting at 0.
students = ["Harry Potter", "Hermione Granger", "Ronald Weasley", "Dobby", "Draco Malfoy"]
students[0] # returns "Harry Potter"
students[3] # returns "Dobby"
Lists are mutable, meaning we have the ability to change the contents of a list. We just need to know the index of the item we want to change.
students = ["Harry Potter", "Hermione Granger", "Ronald Weasley", "Dobby", "Draco Malfoy"]
students[3] = "Luna Lovegood"
print(students)
# returns ["Harry Potter", "Hermione Granger", "Ronald Weasley", "Luna Lovegood", "Draco Malfoy"]
Python has many features that are included in the language. You're probably familiar with the print function that Python includes to display information but there are many other built in functions that are available for use.
# len() returns the length of a sequence
books = ["The Philosopher's Stone", "The Chamber of Secrets", "The Prisoner of Azkaban",
"The Goblet of Fire", "The Order of the Phoenix", "The Half-Blood Prince", "The Deathly Hallows"]
len(books) # returns 7
# str() converts an int or float to a string
number = 42
str(number) # returns "42"
# int() converts a string to an int
number = "42"
int(number) # returns 42
# input() prompts a user for information
favorite_food = input("What is your favorite food? ")
>>>What is your favorite food? pizza
print(favorite_food) # returns pizza
Built-in functions are an easy way to incorporate functionality quickly into your programs. Check out all of Python's built in functions from the official Python Documentation.
Sometimes we need our programs to make a decision based on some condition. If something is true then do one thing, otherwise, do something else.
name = "Harry Potter"
age = 11
if age > 12:
print("Welcome to Hogwarts!")
else:
print("Wait until you're 12.")
In Python, code is executed line by line. The first statement is executed first, followed by the second, and so on. Sometimes there is a need to execute a block of code for a several number of times.
Loop statements allow us to repeat a block of code multiple times. There are two types of loops that we will be using:
- For Loops
- While Loops
For loops allow you to repeat a block a code for a certain number of times.
for number in range(3):
print("Hello")
# returns
Hello
Hello
Hello
Or another example using the built in function range:
for x in range(5):
print(x)
# returns
0
1
2
3
4
While loops repeat a block of code until a condition is met.
a = 0
b = 5
while a < b:
print(a)
a = a + 1
# returns
0
1
2
3
4
A user-defined function is a reusable block of code that only needs to be written once, but then can be reused over and over again.
The basic steps in writing user-defined functions in Python are:
- Declare the function with the keyword def followed by the function name.
- Write the arguments inside the opening and closing parentheses of the function, and end the declaration with a colon.
- Add the program statements to be executed.
- End the function with/without return statement.
Here is an example of a function that says hello.
def hello(name):
return "Hello " + name
As you can see, def is how we tell Python that we are defining a function. Inside the () we can specify an argument, which is a variable that only belongs to the function. Any code tabbed under the function is considered belonging to the function.