Python Building Blocks 1: Types, Loops, and Conditionals

Welcome to our first tutorial on the building blocks of Python. In this tutorial we’ll go over the basics you’ll need to know to understand what is being “said” in Python. The basics that we’ll go over here are the same as the basics for any other programming language, we’ll cover types, loops, and conditionals.

The blocks of code are for you to copy and try running yourself. You will get the most learning out of this by actually typing the code yourself and understanding what it is telling the program to do! The ‘#’ symbol is what is used to write a comment in Python. Comments are ignored when executing the code.

Python Types

The basic types in Python are String (str), Integer (int), Float (float), and Boolean (bool). There are also built in data structures to know when you learn Python. These data structures are made up of the basic types, you can think of them like Legos, the data structures are made out of these basic types. The core data structures to learn in Python are List (list), Dictionary (dict), Tuple (tuple), and Set (set).

Strings

Strings in Python are assigned with single or double quotations. As in many other programming languages, characters in strings may be accessed as if accessing an array. In the example below we’ll assign a string to a variable, access the first element, check for a substring, and check the length of the string.

x = 'abcd'
# should print a
print(x[0])

# should print True
print('a' in x)

# should print False
print('a' is not in x)

# should print 4
print(len(x))

Numbers

Integers and Floats in Python are both Number types. They can interact with each other, they can be used in all four operations. In the example code we’ll explore how these numbers can interact.

x = 2.5
y = 2

# should print 5
print(x * y)

# should print 1.25
print(x / y)

# should print 0
# // is integer divide and returns the QUOTIENT
print(y // x)

# should print 0.5
print(x - y)

Boolean

Boolean variables in Python are either True or False. They will also return True for 1 and False for 0. The example shows how to assign either True or False to a variable in Python

x = True
y = False

Lists

Lists in Python are represented with brackets. Like characters in a string, the elements in a list can be accessed with brackets. Lists can also be enumerate‘d on to return both the index and the element. We’ll go over enumerate when we cover for loops in Python. The example code shows how to declare lists, print elements in them, add to them, and remove from them.

x = [10, 25, 63, 104]
y = ['a', 'q', 'blah']

# should print 25 and blah
print(x[1])
print(y[2])

x.append(22)
# should print [10, 25, 63, 104, 22]
print(x)

# remove an element that you know exists in the list
# if it's not there, the program will throw an error
x.remove(25)
# should print [10, 63, 104, 22]
print(x)

# remove an element at an index
y.pop(0)
# should print ['q', 'blah']
print(y)

Dictionaries

Dictionaries in Python are a group of key-value pairs. Dictionaries are declared with curly braces and their entries can be accessed in two ways, a) with brackets, and b) with .get. The example code shows how we can access items in a dictionary.

_dict = {
    'a': 'Sally sells sea shells',
    'b': 'down by the seashore'
}

# should print Sally sells sea shells
print(_dict['a'])
# should print down by the seashore
print(_dict.get('b'))
# .get will return none for keys that don't exist
# this should print None
print(_dict.get('c'))

# should print dict_items([('a', 'Sally sells sea shells'), ('b', 'down by the seashore'))
print(_dict.items())

# add a new element
_dict['c'] = 'Nice'
# should now print Nice
print(_dict['c'])

Tuples

Tuples is an immutable sequence in Python. Unlike lists, you can’t move objects out of order in a Tuple. Tuples are declared with parenthesis and must contain a comma (even if it is a tuple of 1). The example below shows how to add tuples, get a tuple from a list, and return information about it.

x = (a, b)
y = (c, d)
# we can add tuples
# should print (a, b, c, d)
print(x + y)

_list = [1, 2, 3, 4]
_tuple = tuple(_list)
# should print 1, 4, and 4
print(min(_tuple))
print(max(_tuple))
print(len(_tuple))

Sets

Sets in Python are the non-duplicative data structure. That means they can only store one of an element. Sets are declared with curly braces like dictionaries, but do not contain ‘:’ in them. The example code shows how to turn a list into a set, access set elements by index, add to a set, and remove from a set.

# we can turn a list into a set
x = ['a', 'a', 'b', 'c', 'c']
x = set(x)
# should print {'a', 'b', 'c'}
print(x)

# can still access by index
# should print 'a'
print(x[0])

# add 'd' to the set
x.add('d')
# should now print {'a', 'b', 'c', 'd'}
print(x)

# remove 'c' from the set
x.remove('c')
# should print {'a', 'b', 'd'}
print(x)

Looping in Python

As in most useable programming languages, Python also has loops. When you learn Python, there are two loops to pay attention to. The while loop and the for loop. In a while loop, the program will execute some set of commands while a conditional that you set is true. In a for loop, the program will execute some set of commands for some condition.

Example of a while loop that adds to a number while it is still under 10:

x = 0
while x < 10:
    x += 1

Example of a for loop that adds to a number until it has added to it 10 times:

x = 0
for _ in range(10):
    x += 1

Python Conditionals

There are three important conditional patterns to learn in Python. The patterns are a) if – else, b) if – elif* – else and c) if.

Example for an if-else statement that prints x if x is equal to 5, else it will print that x is not equal to 5

if x == 5:
    print(x)
else:
    print("x is not equal to 5")

Example for an if-elif*-else statement that prints x if x is less than 5, else if x is greater than 5 it will print that x is greater than 5, else it will print that x is equal to 5

if x < 5:
    print(x)
elif x > 5:
    print("x is greater than 5")
else:
    print("x is equal to 5")

Example for an if statement that will print x if x is equal to 5 but won’t do anything otherwise. To learn more feel free to reach out to me @yujian_tang on Twitter, follow the blog, or join our Discord.

if x == 5:
    print(x)

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

For more advanced Python Tutorials check out my Blog Posts

How to do RAG with an AI Agent built on LlamaIndex

There are two big “types” of LLM Apps out there right now. First, “retrieval augmented generation” or RAG. Second, AI Agents. It turns out that you can use AI Agents to perform RAG. This tutorial shows you how. I did not come up with this example, I’m simply explaining how it works. I’ve also uploaded…

A Simple Introduction to Zero Trust Networks

The biggest security breaches in history have cost companies billions of dollars. Most recently, in 2022, a security breach at T-Mobile cost them $350M in customer payouts alone. Security issues are some of the most pressing concerns in today’s ever evolving software world.  While security can be implemented in many ways, some are better than…