python logo

Introduction to Python

python logo

Introduction

Python is an excellent first programming language as it is fun and easy to learn, yet powerful. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

With Python you can do many useful things such as data processing, building mobile apps, gaming, navigation, AI, web crawling, automation, database management and more.

This quick intro to Python doesn't begin to touch the surface and if you are interested in learning more, there is so much more you can do with this beautiful language and I suggest you research further on how to create the program(s) you envision.

What You Should Already Know

There are no requirements in order to learn Python, however there are a few skills which will be helpful:

  • Basic computer knowledge. You should be able to install programs, be familiar with keyboard shortcuts and be able to troubleshoot.
  • CLI or Linux experience. Depending on your operating system, you may need to know how change permissions and/or file extensions in order to run the programs.
  • Any programming experience. If you are new to programming and need help, try one of the links below.

Installation

Installing Python is generally easy, and nowadays many Linux and UNIX distributions include a recent Python. Even some Windows computers now come with Python already installed. If you are using Windows, look for Python3 in the Microsoft Store and install it there if you don't have it already.

For simplicity, you can open Python in cmd, PowerShell or bash by typing either:

python
python3

If Python is not installed it will either open up the Microsoft Store for you (Windows) or tell you how to install it (Linux).

If you are using Linux, it is most likely pre-installed. To make sure it is and to check the version that is installed, go to the terminal and type:

python3 --version

It should tell you the version number. If it is not installed, it will tell you how. Do so by typing:

sudo apt install python3

You will also need to install a code editor. One of the major benefits of a code editor is syntax highlighting. It detects which language your script is in (based on the type of file extension used) and makes everything color coded. If you already have one feel free to skip to the next section. There are subtle differences depending on your preferences, however the most popular choices are:

There are extensions you can install to run Python programs directly in the editors, which makes it easier to setup and debug. There is plenty of info about doing that around the web.

Hello World

Whether you're new, or familiar with any kind of programming, here is typically the first lesson in any programming language, your first script, 'Hello World'. This is the most basic use of programming, printing text on the screen. This is where we start.

To get started with writing Python, open a new file in your editor of choice or just a new text document will work and write your first "Hello world" Python script:

print('Hello World!')

Save the script as 'hello_world.py' and run it in your chosen editor or double click it if you are using Windows and it will run.

If you are using Linux, make sure you add this to the beginning of your script in order for it to run:

#!/usr/bin/python3

Also make sure you give the file permission to execute:

chmod +x hello_world.py

Then you can run the script by typing:

./hello_world.py

or

python3 hello_world.py

Comments

As you progress, you might also want to add a comment to your script, which won't run as part of the program. Comments can contain information such as your name or contact info, version number, keeping your code organized by sections, various ways of doing the same thing, etc. Comments start with a (#) hashtag:

# This is a comment

Once you begin to write more detailed code, you might need to remind yourself of what you're doing or explain certain lines of code to someone else. You can comment multiple lines of code with three single quotes (''') before and after the code you want to ignore:

'''
This is
a multi-line
Comment
'''

Usually it is good practice to delete code that is no good but sometimes if you are still testing and trying out different ways of doing something, it can be useful to keep it around and just temporarily comment it until you decide which part of the code you want to keep.

Variables

Variables are essentially placeholders for data stored in memory and you can assign various values to make it easier for reference in your script.

Variables can hold strings, integers or floats:

# This is a string
x = 'This is a string.'

# This is an integer
x = 11

# This is a float
x = 4.0

Our basic 'Hello World' script can be modified using a variable like so:

x = 'Hello World!'
print(x)

You will see the same "Hello World!" print out on your screen when you run this.

You can also define multiple variables to the same value:

x = y = z = 5
# x equals 5, so do y and z

Or you can set multiple variables to multiple values:

x, y, z = 5, 4.44, 'hello'

print(x) # prints 5
print(y) # prints 4.44
print(z) # prints 'hello'

Expressions

There are various types of operators which have many different expressions. Math is very simple in Python. As you would expect it works like this:

Function Operator Description
Addition + Adds values on either side of the operator.
Subtraction - Subtracts right hand operand from left hand operand.
Multiplication * Multiplies values on either side of the operator.
Divison / Divides left hand operand by right hand operand.
Exponent ** Performs exponential (power) calculation on operators.
Modulus % Divides left hand operand by right hand operand and returns remainder.
Floor Division // The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity).
2 + 2 # equals 4
4 - 2 # equals 2
5 * 5 # equals 25
9 / 3 # equals 3.0
10 ** 5 # equals 100000
20 % 6 # equals 2
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0

A nice feature of Python is you can even add strings together:

sleep = 'z'
sleeping = sleep + sleep + sleep

print(sleeping)

# prints out 'zzz'

You will also need to know about Comparison (also known as Relational) Operators:

Function Operator Description
Is Equal to == If the values of two operands are equal, then the condition becomes true.
Not Equal to != If values of two operands are not equal, then condition becomes true.
Greater Than > If the value of left operand is greater than the value of right operand, then condition becomes true.
Less Than < If the value of left operand is less than the value of right operand, then condition becomes true.
Greater Than or Equal to >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.
Less Than or Equal to <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true.

There are many other operators in Python besides Arithmetic and Comparison operators which will not be covered in this introduction. To read more about them, go here.

Conditional Statements

Conditional statements can be any expression that evaluates to true or false. Use the if statement to execute lines of code only if a logical condition is true. This is where the comparison or relational operators a very useful. Use else to execute a statement if the condition is false. An if statement works like this:

a = 5
if a == 5: print(a)
else: print('a is not equal to 5')

If the first statement is true, the code will execute, else it will execute a different line of code. These are also known as Boolean expressions. Notice the indentation after both the 'if' and the 'else', this is very important in Python otherwise it will cause a syntax error if there is improper indentation. Also notice that there is a colon (:) after both the if and else, again this will cause a syntax error if left unwritten.

You may also nest if statements within another if statement in order to test multiple conditions:

a = 11
if a > 5: print('a is greater than 5') if a < 25: print('a is less than 25') else: print('a is less than 5')
  • Quiz: In the example above, if the 'else' statement prints, what is missing in the print statement?
  • Hint: What value could 'a' also be equal to in order for the else statement to run? (See below if you need help.)

Another way to test for relations is in the same line using the AND or OR statement:

  • AND: Executes if both statements are true.
  • OR: Executes if either statement is true.
a = 11
if a > 5 and a < 25:
    print('a is greater than 5 and less than 25')
else:
    print('a is less than or equal to 5')

The code above will only execute if both evaluations result to true. If either one of them is false the first line of code will not get executed and instead run the code in the else statement.

Using the OR statement, if either one of the statements is true it will go through:

a = 11
if a < 3 or a > 9:
    print('a is either less than 3 or greater than 9')
else:
    print('a is between 3 and 9')

The statements will test for true or false from left to right in the order they are written. Notice how the first comparison statement is false but since we used an OR relational operator, it went on to evaluate the second expression (a > 9) which is true, therefore the result of the entire expression using the OR statement is true.

Loops

There are two types of loops in Python:

  • For Loops: execute a certain amount depending on the conditions
  • While Loops: execute as long as the conditions are met

For loops are excellent for looping through a list (which we will learn about next). For now, just take a look at this code and you will understand it more moving forward:

x = 0
print('Before', x)
for number in [1, 19, 5, 15]:
    x = x + number
    print(x, number)
print('After', x)

Explanation: For each number in the list [1, 19, 5, 15], add the number to x and print them both out.

This will execute and print out like so:

  • Before 0
  • 1 1
  • 20 19
  • 25 5
  • 40 15
  • After 40

While loops are great because they allow you to 'loop through' (execute) the same code over and over as long as the condition you specify is true:

a = 1
while a <= 10: print(a) a += 1

With each iteration (loop), the loop prints the value of a on a new line, until a becomes greater than 10.

  • The first pass: a = 1
  • The second pass: a = 2
  • The tenth pass: a = 10
  • At the end of the tenth pass, a becomes 11, therefore the statement is no longer true and the while loop exits.

Be careful with while loops because you can create an infinite loop which will keep running forever. This is why we have the [a = a + 1] statement at the end, so eventually a will be false and the loop will stop.

If you find yourself in an infinite loop situation, you can usually end the program by hitting CTRL + C or CTRL + Z. If that doesn't work you will need to close the terminal or whatever program you are running it in. ALT + F4 is the keyboard shortcut to close the current open window.

If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.

Strings

Strings are usually anything that is not a number and they are within quotes ' ' or " ". We have already used strings in previous examples, such as 'Hello World!'.

One of the most common ways you will use strings in writing your own interactive programs is taking user input and doing something with it:

user_name = input('Enter your name: ')
print('Hello', user_name)

This code asks the user to enter their name and assigns it to user_name and says 'Hello' to them. The comma in the print statement automatically adds a space for you. Again, input() is a great way to make your scripts and programs interactive.

You can alter or manipulate strings in the following way:

  • Loop through them
  • Count their letters
  • Slice them up
  • Add them together (concatenate)
  • Other manipulations

If you want to see how long the string is you can do this:

fruit = watermelon
x = len(fruit)
print(x)

# or

print(len(fruit))

Let's say you wanted to loop through a string and output each letter on a new line:

fruit = 'watermelon'
for letter in fruit:
    print(letter)

You can make strings uppercase or lowercase by doing this:

print(fruit.upper())
# WATERMELON

# or

print('MAKE ME LOWERCASE'.lower())
# make me lowercase

You will learn more about manipulation in the following sections, but keep in mind Python is much more powerful than just manipulating numbers or printing things out.

Lists

Lists are a very common and useful thing in Python, as there is a lot you can do with lists. We already used a list in one of the previous examples to loop through some numbers.

A list is just a list of strings, ints or floats which are contained in one list variable. You can manipulate the list in many different ways:

  • Print the entire list
  • Print certain parts of the list
  • Add or remove items from the list
  • Find the length of the list
  • Add the numbers in a list together
  • Combine lists together
  • Slice lists apart
  • Search for something in lists

Here are a couple examples:

# defines a blank list
my_list = ()

# defines a list
my_list = [11, 22, 33, 44, 55]

# prints the entire list
print(my_list)

# prints first number in list
print(my_list[0])

# also prints the first number in the list [:1] means up to but not including 1
print(my_list[:1])

# adds to the end of the list
my_list.append(66)

# adds the numbers in the list together
print(sum(my_list))

# prints the length of the lists
print(len(my_list))

# sorts the list
print(my_list.sort())

Notice that list indices start at 0. Therefore 1 is second in the list, 0 is first. This is important to remember.

Keep in mind you can also slice strings in this same way.

Lists can also contain strings or a combination of strings, int or float:

names = ['John', 'Rob', 'James']

# prints last item
print(names[2])

# append list
names.append('Apple')
names.append(3)
names.append(4.5)

# print selected parts of the list (just the strings in this case) print(names[0:3])

# sorting only works with one type (strings or integers)
# so you would need to remove the last two items which are not strings
names.pop()

# pop only removes the last item in the list, or you can specify the index
names.pop(4)

# now you can sort the list alphabetically
names.sort()

As one of the previous examples showed, you could use a list in a for loop going through each item and do something, or you could also process some data, and add the result to the end of that list and append it. From there you could add them together, average them, etc.

There are a lot of other things you can do with lists, see the functions section for more info.

Dictionaries

Dictionaries are similar to lists in that they store 'lists' of data. This data can also be referenced a variety of ways, very similar to lists.

The main difference is that Lists are 'numbered' while Dictionaries are 'named'. Dictionaries:

  • Have a 'key : value' pair
  • Can be referenced or sorted by either their key (name) or value.

Creating a dictionary is simple:

# definite it before you start adding things to it
my_dict = ()
my_dict['name'] = 'Jack'
my_dict['age'] = 21
my_dict['country'] = 'US'

print(my_dict)
# {'name' : 'Jack', 'age' : 21, 'country' : 'US'}

# or you could define it all at once
my_dict = { 'name' : 'Jack', 'age' : 21, 'country' : 'US' }

# prints a list of just the keys (names)
print(my_dict.keys())
# ['name', 'age', 'country']

# prints a list of just the values
print(my_dict.values())
# ['Jack', 21, 'US']

# prints the key:value pairs as list
print(my_dict.items())
# [('name', 'Jack'), ('age', 21), ('country', 'US')]

As you can see, dictionaries are very versatile, we can do a lot of different things with them, as well as turn them into lists and process them further.

The most common application of dictionaries is counting. This code by Dr. Chuck counts the most common name in the list 'names', also known as a 'histogram' of names:

counts = dict()
names = ['Rob', 'John', 'Jason', 'John', 'Charles', 'Rob', 'James', 'John']
for name in names:
    if name not in counts:
        counts[name] = 1
    else:
        counts[name] = counts[name] + 1
print(counts)

Explanation:

  • Create a blank dictionary called 'counts'.
  • Create a list called 'names'.
  • Loop through each name in 'names'.
    • If the name does not exist in the dictionary 'counts' already, add that name to it with a value of 1.
    • Else (it exists) and increase its value by 1.
  • Print the dictionary.

There is a simpler way to do this names histogram with the get() method. I encourage you to do your own research and look into this further (Python for Everybody).

Functions

A function or method is useful when you have multiple lines of code that you may use more than once and when the function is 'called' it executes those lines of code.

They are also great at processing and modifying information passed to them inside of the parenthesis () and returning the processed information.

We have been using functions for most of this introductory lesson:

  • the print() function, which prints or outputs the value(s) specified
  • the append() function, which appends the value specified to the end of your list.
  • the sum() function, which adds all of the values in the list together.
  • the upper() and lower() functions, which adjust the string to either uppercase or lowercase.

There are many more functions we will not get into here, but if you want to see what type() a variable is, type:

type(name_of_your_variable)

To get a list of that variable type's capable functions, use the dir() function by typing:

dir(name_of_your_variable)

and you will see a list of that variable type's functions (ignore the ones with the underscores, as they are used by Python).

To define your own functions, you need to have a def (which defines it as a function) followed by the function name, followed by parentheses and a colon, as such:

def hello_world():
    print('Hello World!')

You call this function by typing:

hello_world()

You aren't required to pass data into the function through the parenthesis, as above. However, most of the time you will want to write functions in order to process data:

a = 5
def multiply_by_five(a): x = a * 5 return x
multiply_by_five(a)

The above function will multiply anything passed to it (in the parenthesis) by five and return the result. In this case you pass in a with a value of 5 when the function is called and get a result of 25.

This was a simple example but you can see how this will be useful with more complicated equations or something you need to repeat throughout your program.

Let's try another one:

a = 44
b = 11 def add_these(a, b): return a + b

Now we're taking two numbers and adding them together. Simple, yes, but we can get much more complicated than this. Here is an example from one of my projects I'm working on, Numerology. This is still relatively simple but it will hopefully give you an idea that so much more can be done in Python. This function of the Numerology script changes letters into their respective numbers and reduces them if they are not master numbers:

def name_num(name):
    x = 0
    total = 0
    r = 0
    for chars in name:
        x = ord(chars) - 96
        if x >= 10:
            r = sum(int(digit) for digit in str(x))
            total = total + r
        else:
            total = total + x
    return total

A more detailed explanation: This function takes a name passed into it, changes each letter to its numerological value (using the ord() function). For each digit in the string, if that number is greater than or equal to 10, it reduces it down to one digit and adds it to a total, otherwise it is already one digit and doesn't need to be reduced and adds it to the total.

That completes some of the basics and this short introduction to Python. Hopefully this has been a good start for you in your journey learning Python. This should be enough for you to start writing your own basic scripts or programs.

Thank you for reading and I hope you check out the resources below to keep learning.

Reference

The information on this page comes from various sources from which I've learned, as well as from the Python Documentation. There is a lot of other information and courses out there. If you enjoyed this brief introduction I encourage you to check out additional sources.

Thank you to:

Please refer to the official Python Documentation, FAQ or one of the above mentioned sources for more information.

Now, go write some Python programs!