Select Page

Python Programming for Beginners: 103 Examples

This article is a comprehensive Python programming for beginners tutorial.

So, why should you learn Python?

According to a recent stackoverflow survey, Python is the fastest-growing major programming language.

I’m going to show you 103 examples of the most important Python programming basics.

If you want to master these essential concepts, or just brush up for an interview, this article is a great resource.

Let’s get started!

Strings

We’re going to start with a basic program creating a string.

Start by typing the following:

print("My first program")
Out:
My first program

Make sure to include the parentheses.

This is a subtle difference between Python 3 and Python 2.

Python 3 requires the parentheses.

Let’s try another string, this time instead of using double quotes, lets use single quotes.

print('guitar')
Out:
guitar

Both double quotes and single quotes work for strings.

We can also print numbers as strings.

print("3")
Out:
3

Numbers

Numeric types include integers and floats.

An integer is a number that doesn’t have a decimal.

print(3)
Out:
3

A float is a number that does have a decimal place.

Here’s that same number, but this time as a float.

print(3.0)
Out:
3.0

Variables

Often times you will need to assign numbers or strings to a variable.

Here’s an example of a numeric variable.

x = 2
print(x)
Out:
2

Here’s another example, but this time we’ll use a string.

y = 'hello'
print(y)
Out:
hello

We can also print multiple variables at the same time. Here’s an example:

a = "good day"
b = "to you"
print(a, b)
Out:
good day to you

Here’s one final example. This time we’ll add two string variables.

c = "another"
d = " example"
print(c + d)
Out:
another example

Lists

In addition to strings and numbers, lists are another Python data type.

Here’s a list of strings:

string_list = ["pizza", "burger", "wings"]
print(string_list)
Out:
['pizza', 'burger', 'wings']

We can also create a list of numbers.

number_list = [1.2, 2.5, 3.7]
print(number_list)
Out:
[1.2, 2.5, 3.7]

Finally, we can create a list of mixed types.

Here’s a small list that includes both strings and numbers.

mixed_list = ["pizza", 1.3, "burger", 5]
print(mixed_list)
Out:
['pizza', 1.3, 'burger', 5]

You can access values in a list by their index. Python starts with index 0.

string_list = ["pizza", "burger", "wings"]
print(string_list[0])
Out:
pizza

Here’s another example, accessing the string at index location 2.

print(string_list[2])
Out:
wings

You can also access multiple values. To do that, you can use the colon : .

print(string_list[0:2])
Out:
['pizza', 'burger']

You can also replace values in a list.

string_list = ["pizza", "burger", "wings"]
string_list[1] = "ice cream"
print(string_list)
Out:
['pizza', 'ice cream', 'wings']

Tuples

Tuples are another Python data type.

They are similar to lists, but instead use parentheses ( ).

Here’s a tuple of some strings.

string_tuple = ("pizza", "burger", "wings")
print(string_tuple)
Out:
('pizza', 'burger', 'wings')

As with lists, you can have mixed types in a tuple.

Here’s a tuple of both strings and numbers.

mixed_tuple = ("pizza", 1.3, "burger", 5)
print(mixed_tuple)
Out:
('pizza', 1.3, 'burger', 5)

You can access data in a tuple the same as a list.

string_tuple = ("pizza", "burger", "wings")
print(string_tuple[0])
Out:
pizza

A big difference between lists and tuples is that you can’t change things in a tuple.

Try the following example. This will produce a TypeError.

string_tuple[1] = "ice cream"
print(string_tuple)

Dictionaries

Dictionaries are another data type that supports a {key: value} structure.

To access the value, you use the key. Here’s an example:

food_dictionary = {"vegetable": "broccoli", "fruit": "apple"}
print(food_dictionary["fruit"])
Out:
apple

Like lists, you can change the values in a dictionary.

To change values, you use the keys.

food_dictionary["vegetable"] = "spinach"
print(food_dictionary)
Out:
{'vegetable': 'spinach', 'fruit': 'apple'}

Dictionary values can also be numbers, or even lists.

food_dictionary = {"vegetables": ["broccoli", "spinach"]}
print(food_dictionary["vegetables"]))
Out:
['broccoli', 'spinach']

Sets

Sets are yet another Python type.

They have curly braces, but look more like a tuple.

They differ from a tuple though, because you can’t access the values using an index.

food_set = {"pizza", "steak", "apple"}
print(food_set)
Out:
{'steak', 'pizza', 'apple'}

If you try accessing an item in the set by using an index you will get an error.

print(food_set[0])
print(food_set)
Out:
TypeError: 'set' object does not support indexing

Booleans

Python also supports booleans. These are the values True and False.

# Is 5 greater than 2?
print(5 > 2)
Out:
True
# Is 2 greater than 5?
print(2 > 5)
Out:
False
# Is 2 equal to 2?
print(2 == 2)
Out:
True
# Is "apple" equal to "apple"?
print("apple" == "apple")
Out:
True
# Is "apple" equal to "pizza"?
print("apple" == "pizza")
Out:
False

Math

Here are some math operators used in Python.

No surprises here. These look very similar to any calculator.

# Addition
print(2 + 3)
Out:
5
# Subtraction
print(5 - 1)
Out:
4
# Multiplication
print(2 * 5)
Out:
10
# Division
print(6 / 3)
Out:
2.0

There’s also a modulus operator.

This is used for determining the remainder when you divide numbers.

# 2 can go in to 5 twice, with a remainder of 1
print(5 % 2)
Out:
1
# Modulus with no remainder
# If there is no remainder, the modulus returns 0
print(6 % 3)
Out:
0

Here’s an example using an exponent.

To raise a number to a power, we use the ** operator.

# Exponentiation 
# 2^3
# Also known as 2*2*2, which equals 8
print(2 ** 3)
Out:
8

We can also perform a special type of division known as “floor division”.

This simply rounds down when your division has a remainder.

# Floor division
# This type of divison rounds down
# Example: 5 / 2 equals 2.5
# floor division always rounds down, so this will return 2
print(5 // 2)
Out:
2

Assignment

These operators are used for variables.

They assign values in different ways.

Here’s an example of the most basic way to assign a variable using the = operator.

# = operator
x = 2
print(x)
Out:
2

Another type of operator is the +=.

This will add something to the variable, and then assign this new value.

Here’s an example:

# += operator
# Same as x = x + 4
x = 3
x += 4
print(x)
Out:
7

The -= operator is very similar.

Instead of adding, this operator will subtract.

# -= operator
# Same as x = x - 9
x = 12
x -= 9
print(x)
Out:
3

You’re probably starting to get the picture.

The next two examples will multiply and divide.

As with the other examples, the final values will get assigned to the variable.

# *= operator
# same as x = x * 2
x = 5
x *= 2
print(x)
Out:
10
# /= operator
# same as x = x / 4
x = 8
x /= 2
print(x)
Out:
4.0

Next, we have the **= operator.

This will raise the variable to a power using the ** portion.

The = sign at the end will then assign this to the variable.

# **= operator
# same as x = x ** 4
x = 2
x **= 3
print(x)
Out:
8

Comparison

These operators make different types of comparisons.

They return boolean values, either True or False.

I’ve provided the operators and an explanation in plain English in the code comments below.

# == operator
# equal 
print(3 == 2)
Out:
False
# != operator
# not equal
print(3 != 2)
Out:
True
# > operator
# greater than operator
print(3 > 2)
Out:
True
# < operator
# less than
print(3 < 2)
Out:
False
# >= operator
# greater than or equal to 
print(3 >= 3)
Out:
True
# <= operator
# less than or equal to 
print(3 <= 2)
Out:
False

Logical Operators

These operators combine multiple operators.

They return either True or False.

I really like this Python syntax.

Using real words like “and” makes the code very easy to follow.

# "and" operator
# returns True if both conditions are true
print(3 > 2 and 5 < 10)
Out:
True
# "or" operator
# True if one of the conditions is true
print(3 < 2 or 5 > 2)
Out:
True
# "not" operator
# Returns False if the result is true
print(not (4 > 2 and 2 < 8))
Out:
False

Identity Operators

These operators compare objects.

They don’t compare if the objects are equal, but instead if they are the same.

Here’s some examples.

# "is" operator
# True if both are the same
# String example
print("apple" is "apple")
Out:
True
# "is" operator
# True if both are the same
# Number example
print(2 is 2)
Out:
True

Here’s an example of two objects that are equal == but are not the same object when the is operator is used.

# == operator
# An integer equal to a float
print(2 == 2.0)
Out:
True
# "is" operator
# Same example using "is"
print(2 is 2.0)
Out:
False

Here’s a couple of more examples, this time with the is not operator.

# "is not" operator
print(2 is not 2.0)
Out:
True
# "is not" operator
print("apple" is not "apple")
Out:
False

Membership Operators

These operators are used to find out if a variable is in a list, dictionary, tuple, or set.

The membership operators are in and not in.

# "in" operator
# List example
food_list = ["apple", "ice cream", "hamburger"]
print("ice cream" in food_list)
Out:
True
# "in" operator
# Tuple example
food_tuple = ("apple", "ice cream", "hamburger")
print("banana" in food_tuple)
Out:
False

For dictionaries, the membership operator applies to the “keys”.

# "in" operator
# Dictionary example using keys
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}
print("fruit" in food_dictionary)
Out:
True

It won’t work for evaluating values directly from the dictionary.

# "in" operator
# Dictionary example using a value
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}
print("banana" in food_dictionary)
Out:
False

To evaluate the values, the operator needs to be applied to a specific “key” in the dictionary.

# "in" operator
# Dictionary example applied to a specific key
print("banana" in food_dictionary["fruit"])
Out:
True

Here’s an example with a set.


# "in" operator
# Set example
# Set 
food_set = {"pizza", "steak", "apple"}
print("pizza" in food_set)
Out:
True

not in can be applied to each example above in the same way.

If a value is “not in” the object, the operator returns True.

# "not in" operator
# List example
food_list = ["pear", "carrot", "cheese"]
print("apple" not in food_list)
Out:
True
# "not in" operator
# Tuple example
food_tuple = ("pear", "carrot", "cheese")
print("pear" not in food_tuple)
Out:
False

If Statements

if some condition is met, Python will do something.

This type of conditional is an important concept in programming.

In this example, Python will print “this is a fruit” since the food is a pineapple.

# If statement
food = "pineapple"
if food == "pineapple":
    print("this is a fruit")
Out:
this is a fruit

if some condition is not met, Python won’t do anything.

In this example, our food is not a pineapple, so Python won’t print anything.

# If statement
food = "ice cream"
if food == "pineapple":
    print("this is a fruit")
Out:

We can add an else statement to do something if the condition is not met.

Building on the previous example, we can see that “ice cream” is some other food.

# If/else statement
food = "ice cream"
if food == "pineapple":
    print("this is a fruit")
else:
    print("this is some other food")
Out:
this is some other food

We can check another condition using the elif statement.

Here’s a different example using numbers.

# If and elif statements
x = 20
y = 10
z = 30

if x < y:     
    print("x is less than y") 
elif z > y:
    print("z is greater than y")
Out:
z is greater than y

Be careful though.

Multiple conditions can be true, but Python may only return the first one.

Here’s an example.

# If and elif statements
x = 5
y = 12
z = 40

if x < y:     
    print("x is less than y") 
elif z > y:
    print("z is greater than y")
Out:
x is less than y

We can combine the two if statements using the logical operator and.

# If and statements
# If and elif statements
x = 5
y = 12
z = 40

if x < y and z > y:
    print("x is less than y, and z is greater than y")
Out:
x is less than y, and z is greater than y

While Loops

while something is true, keep doing something.

This a programming concept known as a “while loop”.

Let’s start at 0, and add 1 every time we go through the loop.

We’ll keep adding as long as the number is less than 5.

# While Loop
number = 0

while number < 5:
    print(number)
    number+=1
Out:
0
1
2
3
4

We can also stop the while loop early if some condition is met by using break.

In this example we’ll start at 5, and keep adding numbers by 5.

The loop will continue as long as the number is less than 50.

Let’s break out of the loop early once the number equals 25.

# Breaking out of a while loop
number = 5

while number < 50:
    print(number)
    if number == 25:
        break
    number += 5
Out:
5
10
15
20
25

We can also skip an iteration using continue.

In the example below we’ll skip printing the number if it’s equal to 6.

# Breaking out of a while loop
number = 2

while number < 10:
    number += 2
    if number == 6:
        continue
    print(number)
Out:
4
8
10

Here’s a while loop example along with an else statement.

Now we’re starting to combine loops with conditional statements.

This is a very important programming concept.

# While/else example
number = 10

while number < 40:
    print(number)
    number += 10
else:
    print("no more numbers to print")
Out:
10
20
30
no more numbers to print

The last thing I’ll mention about while loops is to make sure you don’t get stuck in an infinite loop.

If your code has some condition that is always true, the loop will just continue to run.

In that case, you’ll need to manually stop Python from running.

For Loops

You can also loop through lists, dictionaries, sets, and tuples.

This is similar to a “while loop”, but also slightly different.

“For loops” will loop through each item “in” a data type.

Here’s an example looping through a “list” data type.

# Loop through a list
car_list = ["Toyota", "Honda", "Chevy"]

for y in car_list:
    print(y)
Out:
Toyota
Honda
Chevy

The variable y is just an indexing variable. It’s used to pull values out of the list.

You can make that indexing variable just about anything you want.

Here’s another example using a different variable.

# Loop through a list
car_list = ["Toyota", "Honda", "Chevy"]

for car in car_list:
    print(car)
Out:
Toyota
Honda
Chevy

We can see that the variable car does exactly the same thing as the variable y did.

Here’s another example. This time, we’ll loop through a dictionary.

# Loop through a dictionary
# this will print the "keys"
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}

for food in food_dictionary:
    print(food)
Out:
vegetable
fruit

If we want to pull out the values we’ll need to access them using the keys.

Here’s how we can do that:

# Loop through a dictionary
# this will print the "values"
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}

for food in food_dictionary:
    print(food_dictionary[food])
Out:
broccoli
banana

We can also loop through tuples.

# Loop through a tuple
number_tuple = (1, 2, 3)

for number in number_tuple:
    print(number)
Out:
1
2
3

Finally, let’s loop through a set.

# Loop through a set
mixed_set = {"apple", 2, "Toyota", 3.2}

for i in mixed_set:
    print(i)
Out:
2
3.2
Toyota
apple

Now let’s start building on our “for loops”.

Maybe we want to stop early. We can do that using break.

# For loop with break example
number_list = [1, 2, 3, 4, 5, 6]

for number in number_list:
    if number > 4:
        break
    print(number)
Out:
1
2
3
4

We can also skip a value in a list when we’re looping.

To do that we use continue.

# For loop with continue
food_list = ["apple", "banana", "fork", "pizza"]

for item in food_list:
    if item == "fork":
        continue
    print(item)
Out:
apple
banana
pizza

You can also use for along with range to print numbers.

# For range example
for i in range(3):
    print(i)
Out:
0
1
2

You can also start from a number other than 0.

# Starting from a different number
for i in range(5, 10):
    print(i)
Out:
5
6
7
8
9

Here’s an example starting from 6 skipping numbers by 2.

# Start from 6, skip numbers by 2
for i in range(6, 12, 2):
    print(i)
Out:
6
8
10

Here’s a final example with multiple for loops.

This is also known as “nested” for loops.

# Nested for loops
manufacturer_list = ["Toyota", "Honda", "Chevy"]
vehicle_list = ["car", "motorcycle", "truck"]

for manufacturer in manufacturer_list:
    for vehicle in vehicle_list:
        print(manufacturer, vehicle)
Out:
Toyota car
Toyota motorcycle
Toyota truck
Honda car
Honda motorcycle
Honda truck
Chevy car
Chevy motorcycle
Chevy truck

Functions

You can save a block of code in a function so that you can re-use it.

This is a very important concept in programming.

Here’s an example of an “add_numbers” function.

# Function example
# adding numbers

def add_numbers(x, y):
    z = x + y
    return z

print(add_numbers(2, 3))
print(add_numbers(1, 6))
Out:
5
7

You can also create a function that doesn’t require any input variables.

This is known as a “stub”.

# Stub function example

def print_hello():
    print("hello")

print_hello()
Out:
hello

Here’s a more complicated function using a for loop and if statement.

# More complicated function
vegetable_list = ["broccoli", "carrots", "spinach"]

def my_favorite_foods(food_list):
    food_i_like = ["broccoli", "spinach", "bananas"]
    for food in food_list:
        if food in food_i_like:
            print(food)

my_favorite_foods(vegetable_list)
Out:
broccoli
spinach

We can re-use that function for a different food list.

# Another example
fruit_list = ["apples", "pears", "bananas", "blueberries"]

def my_favorite_foods(food_list):
    food_i_like = ["broccoli", "spinach", "bananas"]
    for food in food_list:
        if food in food_i_like:
            print(food)

my_favorite_foods(fruit_list)
Out:
bananas

To assign the result of a function to a variable we need to use return.

# Assigning the result of a function to a variable.
# Example using a dictionary

birthdays = {"John" : "2/2/1985", "Mary": "6/12/1989"}

def find_birthday(first_name, birthday_dictionary):
    for name in birthday_dictionary:
        if name == first_name:
            return birthday_dictionary[name]

Marys_birthday = find_birthday("Mary", birthdays)
print(Marys_birthday)
Out:
6/12/1989

Functions can also call other functions.

Let’s use the “add_numbers” function inside the “subtract_numbers” function.

# Using a function to call another function

def add_numbers(x, y):
    z = x + y
    return z

def subtract_numbers(a, b):
    c = a - b
    return c

# 10 - (2 + 3) = 5
math_calculation = subtract_numbers(10, add_numbers(2, 3))
print(math_calculation)
Out:
5

Sometimes you might have an unknown number of inputs. To deal with that, you can use *.

Try putting more or less names in the “print_my_name” function.

# Using a function with unknown number of inputs
def print_my_name(*names):
    print("Hi, my name is " + names[2])

print_my_name("Joe", "Mary", "John", "Lucy", "Cathy")
Out:
Hi, my name is John

Lambda Functions

This is another type of function in Python.

It contains an argument and an expression.

Example: my_function = lambda argument: expression

# Lamba function example
# argument: x, y
# expression: x + y

lambda_sum = lambda x, y : x + y
print(lambda_sum(2, 6))
Out:
8

Lambda functions can have numerous arguments.

In the example above we have two, x and y.

They can only have one expression though. In the example, the expression is x + y.

Here’s an example with an if statement.

# Lambda with If statement

lambda_if = lambda x : "less than 5" if x < 5 \
                       else "greater than or equal to 5"

print(lambda_if(2))
print(lambda_if(5))
Out:
less than 5
greater than or equal to 5

Lambda functions must always return something, so you always need to include an else statement, even if it’s just returning nothing, or None.

# Lambda returning None

lambda_if = lambda name : "My name is John" if name == "John" \
                      else None
print(lambda_if("Mary"))
Out:
None

Here’s one final example.

This time we’ll put a lambda function inside of a regular function.

# Lambda example inside a function

def double_the_number(x):
    y = lambda x : x * 2
    return y(x)

print(double_the_number(10))
Out:
20

Libraries

Python has a lot of useful classes and functions that people have already built.

These are contained in packages called libraries.

To use them, you have to make sure the library is installed, and then import the library.

You can install the libraries using the pip package manager. Here’s a useful link that explains pip.

Here’s an example using some built-in functions from the Numpy Library.

# Example with the Numpy Library
# Summing the values in a list
import numpy as np

number_list = [0, 1, 2, 3]

print(np.sum(number_list))
Out:
6

First we import the library, then we shorten the library name using as np.

To use a function, we need to call in from the np library.

When a function is called from a class in a library like this, it’s typically referred to as a “method”.

For the sum function, we use the syntax np.sum and then insert the number_list in to the function.

# Another example
# Find the maximum value

print(np.max(number_list))
Out:
3

Classes

Functions are grouped into libraries in the example above using object oriented programming.

Python already has plenty of libraries for doing math, but let’s create our own math class as an example.

# Creating a math class

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"

print(mathClass.class_name)
print(mathClass.version)
Out:
This is the mathClass
This is version 1.0

First, we start by defining the class using the class syntax, followed by the class name we want to use, which is mathClass.

I set a couple of values for printing the class_name and the version.

To print those, we call the mathClass, and then apply the class_name and version to the mathClass object.

Another important part of classes are the “dunder methods”. They are more formally called constructor methods.

These are special methods used in classes. They are called “dunder” because they use double underscores.

Here’s an example using the most common one, __init__.

# Creating a math class
# Now let's include the __init__ method to "initialize" a list

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"


    # initializing the list value
    def __init__(self, list_value):
        self.list_value = list_value


math_object = mathClass([0, 1, 3])
print(math_object.list_value)
Out:
[0, 1, 3]

We use the __init__ method to “initialize” something in the object.

In our example, we’re creating an instance of the mathClass called math_object that has a list value of [0, 1, 3].

The “self” part is a special class syntax that assigns the input to the variable.

In our example, “self.list_value” is “math_object.list_value”.

Don’t get confused by this. “self” is just a placeholder for “math_object”.

If our object was some other name, such as “guitar”, then “self.list_value” would assign the list to “guitar.list_value”.

Let’s create a new math object.

# Creating a second math object
math_object2 = mathClass([3, 1, 7])
print(math_object2.list_value)
Out:
[3, 1, 7]

We can create as many instances of the mathClass as we want.

This is the real value in this type of programming.

It allows you to easily reuse and apply code to other objects.

Now let’s create a function within the class.

# Adding some functions to the class

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"


    # initializing the list value
    def __init__(self, list_value):
        self.list_value = list_value


    # creating a sum function
    def sum_function(self):
        cnt = 0
        for i in self.list_value:
            cnt += i
        return cnt

math_object3 = mathClass([2, 4, 6])
math_object3.sum_function()
Out:
12

In this example, we’ve created a function called sum_function that sums everything in the list.

Let’s add another function for finding the max value in the list.

# Adding some functions to the class

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"


    # initializing the list value
    def __init__(self, list_value):
        self.list_value = list_value


    # creating a sum function
    def sum_function(self):
        cnt = 0
        for i in self.list_value:
            cnt += i
        return cnt


    # creating a max value function
    def max_value(self):
        max_val = 0
        for i in self.list_value:
            if i > max_val:
                max_val = i
            else:
                max_val = max_val
        return max_val
# Using the max_val function
math_object_new = mathClass([2, 9, 3, 4, 5])
math_object_new.max_value()
Out:
9

This is a simple example, but we can already see how useful this is.

For more info on classes, here’s the official documentation from Python.

Conclusion

In this python programming for beginners article, we went over 103 different examples in Python.

We looked at the basics of different data types, such as floats, lists, and dictionaries.

Next, we went over important programming concepts such as if statements, for loops, and functions.

Finally, we finished up by going over the basics of classes and object oriented programming.

We’ve just started to scratch the surface of Python, but it’s good to revisit these basics once in awhile.

0 Comments

Python Programming for Beginners: 103 Examples

This article is a comprehensive Python programming for beginners tutorial.

So, why should you learn Python?

According to a recent stackoverflow survey, Python is the fastest-growing major programming language.

I’m going to show you 103 examples of the most important Python programming basics.

If you want to master these essential concepts, or just brush up for an interview, this article is a great resource.

Let’s get started!

Strings

We’re going to start with a basic program creating a string.

Start by typing the following:

print("My first program")
Out:
My first program

Make sure to include the parentheses.

This is a subtle difference between Python 3 and Python 2.

Python 3 requires the parentheses.

Let’s try another string, this time instead of using double quotes, lets use single quotes.

print('guitar')
Out:
guitar

Both double quotes and single quotes work for strings.

We can also print numbers as strings.

print("3")
Out:
3

Numbers

Numeric types include integers and floats.

An integer is a number that doesn’t have a decimal.

print(3)
Out:
3

A float is a number that does have a decimal place.

Here’s that same number, but this time as a float.

print(3.0)
Out:
3.0

Variables

Often times you will need to assign numbers or strings to a variable.

Here’s an example of a numeric variable.

x = 2
print(x)
Out:
2

Here’s another example, but this time we’ll use a string.

y = 'hello'
print(y)
Out:
hello

We can also print multiple variables at the same time. Here’s an example:

a = "good day"
b = "to you"
print(a, b)
Out:
good day to you

Here’s one final example. This time we’ll add two string variables.

c = "another"
d = " example"
print(c + d)
Out:
another example

Lists

In addition to strings and numbers, lists are another Python data type.

Here’s a list of strings:

string_list = ["pizza", "burger", "wings"]
print(string_list)
Out:
['pizza', 'burger', 'wings']

We can also create a list of numbers.

number_list = [1.2, 2.5, 3.7]
print(number_list)
Out:
[1.2, 2.5, 3.7]

Finally, we can create a list of mixed types.

Here’s a small list that includes both strings and numbers.

mixed_list = ["pizza", 1.3, "burger", 5]
print(mixed_list)
Out:
['pizza', 1.3, 'burger', 5]

You can access values in a list by their index. Python starts with index 0.

string_list = ["pizza", "burger", "wings"]
print(string_list[0])
Out:
pizza

Here’s another example, accessing the string at index location 2.

print(string_list[2])
Out:
wings

You can also access multiple values. To do that, you can use the colon : .

print(string_list[0:2])
Out:
['pizza', 'burger']

You can also replace values in a list.

string_list = ["pizza", "burger", "wings"]
string_list[1] = "ice cream"
print(string_list)
Out:
['pizza', 'ice cream', 'wings']

Tuples

Tuples are another Python data type.

They are similar to lists, but instead use parentheses ( ).

Here’s a tuple of some strings.

string_tuple = ("pizza", "burger", "wings")
print(string_tuple)
Out:
('pizza', 'burger', 'wings')

As with lists, you can have mixed types in a tuple.

Here’s a tuple of both strings and numbers.

mixed_tuple = ("pizza", 1.3, "burger", 5)
print(mixed_tuple)
Out:
('pizza', 1.3, 'burger', 5)

You can access data in a tuple the same as a list.

string_tuple = ("pizza", "burger", "wings")
print(string_tuple[0])
Out:
pizza

A big difference between lists and tuples is that you can’t change things in a tuple.

Try the following example. This will produce a TypeError.

string_tuple[1] = "ice cream"
print(string_tuple)

Dictionaries

Dictionaries are another data type that supports a {key: value} structure.

To access the value, you use the key. Here’s an example:

food_dictionary = {"vegetable": "broccoli", "fruit": "apple"}
print(food_dictionary["fruit"])
Out:
apple

Like lists, you can change the values in a dictionary.

To change values, you use the keys.

food_dictionary["vegetable"] = "spinach"
print(food_dictionary)
Out:
{'vegetable': 'spinach', 'fruit': 'apple'}

Dictionary values can also be numbers, or even lists.

food_dictionary = {"vegetables": ["broccoli", "spinach"]}
print(food_dictionary["vegetables"]))
Out:
['broccoli', 'spinach']

Sets

Sets are yet another Python type.

They have curly braces, but look more like a tuple.

They differ from a tuple though, because you can’t access the values using an index.

food_set = {"pizza", "steak", "apple"}
print(food_set)
Out:
{'steak', 'pizza', 'apple'}

If you try accessing an item in the set by using an index you will get an error.

print(food_set[0])
print(food_set)
Out:
TypeError: 'set' object does not support indexing

Booleans

Python also supports booleans. These are the values True and False.

# Is 5 greater than 2?
print(5 > 2)
Out:
True
# Is 2 greater than 5?
print(2 > 5)
Out:
False
# Is 2 equal to 2?
print(2 == 2)
Out:
True
# Is "apple" equal to "apple"?
print("apple" == "apple")
Out:
True
# Is "apple" equal to "pizza"?
print("apple" == "pizza")
Out:
False

Math

Here are some math operators used in Python.

No surprises here. These look very similar to any calculator.

# Addition
print(2 + 3)
Out:
5
# Subtraction
print(5 - 1)
Out:
4
# Multiplication
print(2 * 5)
Out:
10
# Division
print(6 / 3)
Out:
2.0

There’s also a modulus operator.

This is used for determining the remainder when you divide numbers.

# 2 can go in to 5 twice, with a remainder of 1
print(5 % 2)
Out:
1
# Modulus with no remainder
# If there is no remainder, the modulus returns 0
print(6 % 3)
Out:
0

Here’s an example using an exponent.

To raise a number to a power, we use the ** operator.

# Exponentiation 
# 2^3
# Also known as 2*2*2, which equals 8
print(2 ** 3)
Out:
8

We can also perform a special type of division known as “floor division”.

This simply rounds down when your division has a remainder.

# Floor division
# This type of divison rounds down
# Example: 5 / 2 equals 2.5
# floor division always rounds down, so this will return 2
print(5 // 2)
Out:
2

Assignment

These operators are used for variables.

They assign values in different ways.

Here’s an example of the most basic way to assign a variable using the = operator.

# = operator
x = 2
print(x)
Out:
2

Another type of operator is the +=.

This will add something to the variable, and then assign this new value.

Here’s an example:

# += operator
# Same as x = x + 4
x = 3
x += 4
print(x)
Out:
7

The -= operator is very similar.

Instead of adding, this operator will subtract.

# -= operator
# Same as x = x - 9
x = 12
x -= 9
print(x)
Out:
3

You’re probably starting to get the picture.

The next two examples will multiply and divide.

As with the other examples, the final values will get assigned to the variable.

# *= operator
# same as x = x * 2
x = 5
x *= 2
print(x)
Out:
10
# /= operator
# same as x = x / 4
x = 8
x /= 2
print(x)
Out:
4.0

Next, we have the **= operator.

This will raise the variable to a power using the ** portion.

The = sign at the end will then assign this to the variable.

# **= operator
# same as x = x ** 4
x = 2
x **= 3
print(x)
Out:
8

Comparison

These operators make different types of comparisons.

They return boolean values, either True or False.

I’ve provided the operators and an explanation in plain English in the code comments below.

# == operator
# equal 
print(3 == 2)
Out:
False
# != operator
# not equal
print(3 != 2)
Out:
True
# > operator
# greater than operator
print(3 > 2)
Out:
True
# < operator
# less than
print(3 < 2)
Out:
False
# >= operator
# greater than or equal to 
print(3 >= 3)
Out:
True
# <= operator
# less than or equal to 
print(3 <= 2)
Out:
False

Logical Operators

These operators combine multiple operators.

They return either True or False.

I really like this Python syntax.

Using real words like “and” makes the code very easy to follow.

# "and" operator
# returns True if both conditions are true
print(3 > 2 and 5 < 10)
Out:
True
# "or" operator
# True if one of the conditions is true
print(3 < 2 or 5 > 2)
Out:
True
# "not" operator
# Returns False if the result is true
print(not (4 > 2 and 2 < 8))
Out:
False

Identity Operators

These operators compare objects.

They don’t compare if the objects are equal, but instead if they are the same.

Here’s some examples.

# "is" operator
# True if both are the same
# String example
print("apple" is "apple")
Out:
True
# "is" operator
# True if both are the same
# Number example
print(2 is 2)
Out:
True

Here’s an example of two objects that are equal == but are not the same object when the is operator is used.

# == operator
# An integer equal to a float
print(2 == 2.0)
Out:
True
# "is" operator
# Same example using "is"
print(2 is 2.0)
Out:
False

Here’s a couple of more examples, this time with the is not operator.

# "is not" operator
print(2 is not 2.0)
Out:
True
# "is not" operator
print("apple" is not "apple")
Out:
False

Membership Operators

These operators are used to find out if a variable is in a list, dictionary, tuple, or set.

The membership operators are in and not in.

# "in" operator
# List example
food_list = ["apple", "ice cream", "hamburger"]
print("ice cream" in food_list)
Out:
True
# "in" operator
# Tuple example
food_tuple = ("apple", "ice cream", "hamburger")
print("banana" in food_tuple)
Out:
False

For dictionaries, the membership operator applies to the “keys”.

# "in" operator
# Dictionary example using keys
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}
print("fruit" in food_dictionary)
Out:
True

It won’t work for evaluating values directly from the dictionary.

# "in" operator
# Dictionary example using a value
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}
print("banana" in food_dictionary)
Out:
False

To evaluate the values, the operator needs to be applied to a specific “key” in the dictionary.

# "in" operator
# Dictionary example applied to a specific key
print("banana" in food_dictionary["fruit"])
Out:
True

Here’s an example with a set.


# "in" operator
# Set example
# Set 
food_set = {"pizza", "steak", "apple"}
print("pizza" in food_set)
Out:
True

not in can be applied to each example above in the same way.

If a value is “not in” the object, the operator returns True.

# "not in" operator
# List example
food_list = ["pear", "carrot", "cheese"]
print("apple" not in food_list)
Out:
True
# "not in" operator
# Tuple example
food_tuple = ("pear", "carrot", "cheese")
print("pear" not in food_tuple)
Out:
False

If Statements

if some condition is met, Python will do something.

This type of conditional is an important concept in programming.

In this example, Python will print “this is a fruit” since the food is a pineapple.

# If statement
food = "pineapple"
if food == "pineapple":
    print("this is a fruit")
Out:
this is a fruit

if some condition is not met, Python won’t do anything.

In this example, our food is not a pineapple, so Python won’t print anything.

# If statement
food = "ice cream"
if food == "pineapple":
    print("this is a fruit")
Out:

We can add an else statement to do something if the condition is not met.

Building on the previous example, we can see that “ice cream” is some other food.

# If/else statement
food = "ice cream"
if food == "pineapple":
    print("this is a fruit")
else:
    print("this is some other food")
Out:
this is some other food

We can check another condition using the elif statement.

Here’s a different example using numbers.

# If and elif statements
x = 20
y = 10
z = 30

if x < y:     
    print("x is less than y") 
elif z > y:
    print("z is greater than y")
Out:
z is greater than y

Be careful though.

Multiple conditions can be true, but Python may only return the first one.

Here’s an example.

# If and elif statements
x = 5
y = 12
z = 40

if x < y:     
    print("x is less than y") 
elif z > y:
    print("z is greater than y")
Out:
x is less than y

We can combine the two if statements using the logical operator and.

# If and statements
# If and elif statements
x = 5
y = 12
z = 40

if x < y and z > y:
    print("x is less than y, and z is greater than y")
Out:
x is less than y, and z is greater than y

While Loops

while something is true, keep doing something.

This a programming concept known as a “while loop”.

Let’s start at 0, and add 1 every time we go through the loop.

We’ll keep adding as long as the number is less than 5.

# While Loop
number = 0

while number < 5:
    print(number)
    number+=1
Out:
0
1
2
3
4

We can also stop the while loop early if some condition is met by using break.

In this example we’ll start at 5, and keep adding numbers by 5.

The loop will continue as long as the number is less than 50.

Let’s break out of the loop early once the number equals 25.

# Breaking out of a while loop
number = 5

while number < 50:
    print(number)
    if number == 25:
        break
    number += 5
Out:
5
10
15
20
25

We can also skip an iteration using continue.

In the example below we’ll skip printing the number if it’s equal to 6.

# Breaking out of a while loop
number = 2

while number < 10:
    number += 2
    if number == 6:
        continue
    print(number)
Out:
4
8
10

Here’s a while loop example along with an else statement.

Now we’re starting to combine loops with conditional statements.

This is a very important programming concept.

# While/else example
number = 10

while number < 40:
    print(number)
    number += 10
else:
    print("no more numbers to print")
Out:
10
20
30
no more numbers to print

The last thing I’ll mention about while loops is to make sure you don’t get stuck in an infinite loop.

If your code has some condition that is always true, the loop will just continue to run.

In that case, you’ll need to manually stop Python from running.

For Loops

You can also loop through lists, dictionaries, sets, and tuples.

This is similar to a “while loop”, but also slightly different.

“For loops” will loop through each item “in” a data type.

Here’s an example looping through a “list” data type.

# Loop through a list
car_list = ["Toyota", "Honda", "Chevy"]

for y in car_list:
    print(y)
Out:
Toyota
Honda
Chevy

The variable y is just an indexing variable. It’s used to pull values out of the list.

You can make that indexing variable just about anything you want.

Here’s another example using a different variable.

# Loop through a list
car_list = ["Toyota", "Honda", "Chevy"]

for car in car_list:
    print(car)
Out:
Toyota
Honda
Chevy

We can see that the variable car does exactly the same thing as the variable y did.

Here’s another example. This time, we’ll loop through a dictionary.

# Loop through a dictionary
# this will print the "keys"
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}

for food in food_dictionary:
    print(food)
Out:
vegetable
fruit

If we want to pull out the values we’ll need to access them using the keys.

Here’s how we can do that:

# Loop through a dictionary
# this will print the "values"
food_dictionary = {"vegetable" : "broccoli", "fruit": "banana"}

for food in food_dictionary:
    print(food_dictionary[food])
Out:
broccoli
banana

We can also loop through tuples.

# Loop through a tuple
number_tuple = (1, 2, 3)

for number in number_tuple:
    print(number)
Out:
1
2
3

Finally, let’s loop through a set.

# Loop through a set
mixed_set = {"apple", 2, "Toyota", 3.2}

for i in mixed_set:
    print(i)
Out:
2
3.2
Toyota
apple

Now let’s start building on our “for loops”.

Maybe we want to stop early. We can do that using break.

# For loop with break example
number_list = [1, 2, 3, 4, 5, 6]

for number in number_list:
    if number > 4:
        break
    print(number)
Out:
1
2
3
4

We can also skip a value in a list when we’re looping.

To do that we use continue.

# For loop with continue
food_list = ["apple", "banana", "fork", "pizza"]

for item in food_list:
    if item == "fork":
        continue
    print(item)
Out:
apple
banana
pizza

You can also use for along with range to print numbers.

# For range example
for i in range(3):
    print(i)
Out:
0
1
2

You can also start from a number other than 0.

# Starting from a different number
for i in range(5, 10):
    print(i)
Out:
5
6
7
8
9

Here’s an example starting from 6 skipping numbers by 2.

# Start from 6, skip numbers by 2
for i in range(6, 12, 2):
    print(i)
Out:
6
8
10

Here’s a final example with multiple for loops.

This is also known as “nested” for loops.

# Nested for loops
manufacturer_list = ["Toyota", "Honda", "Chevy"]
vehicle_list = ["car", "motorcycle", "truck"]

for manufacturer in manufacturer_list:
    for vehicle in vehicle_list:
        print(manufacturer, vehicle)
Out:
Toyota car
Toyota motorcycle
Toyota truck
Honda car
Honda motorcycle
Honda truck
Chevy car
Chevy motorcycle
Chevy truck

Functions

You can save a block of code in a function so that you can re-use it.

This is a very important concept in programming.

Here’s an example of an “add_numbers” function.

# Function example
# adding numbers

def add_numbers(x, y):
    z = x + y
    return z

print(add_numbers(2, 3))
print(add_numbers(1, 6))
Out:
5
7

You can also create a function that doesn’t require any input variables.

This is known as a “stub”.

# Stub function example

def print_hello():
    print("hello")

print_hello()
Out:
hello

Here’s a more complicated function using a for loop and if statement.

# More complicated function
vegetable_list = ["broccoli", "carrots", "spinach"]

def my_favorite_foods(food_list):
    food_i_like = ["broccoli", "spinach", "bananas"]
    for food in food_list:
        if food in food_i_like:
            print(food)

my_favorite_foods(vegetable_list)
Out:
broccoli
spinach

We can re-use that function for a different food list.

# Another example
fruit_list = ["apples", "pears", "bananas", "blueberries"]

def my_favorite_foods(food_list):
    food_i_like = ["broccoli", "spinach", "bananas"]
    for food in food_list:
        if food in food_i_like:
            print(food)

my_favorite_foods(fruit_list)
Out:
bananas

To assign the result of a function to a variable we need to use return.

# Assigning the result of a function to a variable.
# Example using a dictionary

birthdays = {"John" : "2/2/1985", "Mary": "6/12/1989"}

def find_birthday(first_name, birthday_dictionary):
    for name in birthday_dictionary:
        if name == first_name:
            return birthday_dictionary[name]

Marys_birthday = find_birthday("Mary", birthdays)
print(Marys_birthday)
Out:
6/12/1989

Functions can also call other functions.

Let’s use the “add_numbers” function inside the “subtract_numbers” function.

# Using a function to call another function

def add_numbers(x, y):
    z = x + y
    return z

def subtract_numbers(a, b):
    c = a - b
    return c

# 10 - (2 + 3) = 5
math_calculation = subtract_numbers(10, add_numbers(2, 3))
print(math_calculation)
Out:
5

Sometimes you might have an unknown number of inputs. To deal with that, you can use *.

Try putting more or less names in the “print_my_name” function.

# Using a function with unknown number of inputs
def print_my_name(*names):
    print("Hi, my name is " + names[2])

print_my_name("Joe", "Mary", "John", "Lucy", "Cathy")
Out:
Hi, my name is John

Lambda Functions

This is another type of function in Python.

It contains an argument and an expression.

Example: my_function = lambda argument: expression

# Lamba function example
# argument: x, y
# expression: x + y

lambda_sum = lambda x, y : x + y
print(lambda_sum(2, 6))
Out:
8

Lambda functions can have numerous arguments.

In the example above we have two, x and y.

They can only have one expression though. In the example, the expression is x + y.

Here’s an example with an if statement.

# Lambda with If statement

lambda_if = lambda x : "less than 5" if x < 5 \
                       else "greater than or equal to 5"

print(lambda_if(2))
print(lambda_if(5))
Out:
less than 5
greater than or equal to 5

Lambda functions must always return something, so you always need to include an else statement, even if it’s just returning nothing, or None.

# Lambda returning None

lambda_if = lambda name : "My name is John" if name == "John" \
                      else None
print(lambda_if("Mary"))
Out:
None

Here’s one final example.

This time we’ll put a lambda function inside of a regular function.

# Lambda example inside a function

def double_the_number(x):
    y = lambda x : x * 2
    return y(x)

print(double_the_number(10))
Out:
20

Libraries

Python has a lot of useful classes and functions that people have already built.

These are contained in packages called libraries.

To use them, you have to make sure the library is installed, and then import the library.

You can install the libraries using the pip package manager. Here’s a useful link that explains pip.

Here’s an example using some built-in functions from the Numpy Library.

# Example with the Numpy Library
# Summing the values in a list
import numpy as np

number_list = [0, 1, 2, 3]

print(np.sum(number_list))
Out:
6

First we import the library, then we shorten the library name using as np.

To use a function, we need to call in from the np library.

When a function is called from a class in a library like this, it’s typically referred to as a “method”.

For the sum function, we use the syntax np.sum and then insert the number_list in to the function.

# Another example
# Find the maximum value

print(np.max(number_list))
Out:
3

Classes

Functions are grouped into libraries in the example above using object oriented programming.

Python already has plenty of libraries for doing math, but let’s create our own math class as an example.

# Creating a math class

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"

print(mathClass.class_name)
print(mathClass.version)
Out:
This is the mathClass
This is version 1.0

First, we start by defining the class using the class syntax, followed by the class name we want to use, which is mathClass.

I set a couple of values for printing the class_name and the version.

To print those, we call the mathClass, and then apply the class_name and version to the mathClass object.

Another important part of classes are the “dunder methods”. They are more formally called constructor methods.

These are special methods used in classes. They are called “dunder” because they use double underscores.

Here’s an example using the most common one, __init__.

# Creating a math class
# Now let's include the __init__ method to "initialize" a list

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"


    # initializing the list value
    def __init__(self, list_value):
        self.list_value = list_value


math_object = mathClass([0, 1, 3])
print(math_object.list_value)
Out:
[0, 1, 3]

We use the __init__ method to “initialize” something in the object.

In our example, we’re creating an instance of the mathClass called math_object that has a list value of [0, 1, 3].

The “self” part is a special class syntax that assigns the input to the variable.

In our example, “self.list_value” is “math_object.list_value”.

Don’t get confused by this. “self” is just a placeholder for “math_object”.

If our object was some other name, such as “guitar”, then “self.list_value” would assign the list to “guitar.list_value”.

Let’s create a new math object.

# Creating a second math object
math_object2 = mathClass([3, 1, 7])
print(math_object2.list_value)
Out:
[3, 1, 7]

We can create as many instances of the mathClass as we want.

This is the real value in this type of programming.

It allows you to easily reuse and apply code to other objects.

Now let’s create a function within the class.

# Adding some functions to the class

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"


    # initializing the list value
    def __init__(self, list_value):
        self.list_value = list_value


    # creating a sum function
    def sum_function(self):
        cnt = 0
        for i in self.list_value:
            cnt += i
        return cnt

math_object3 = mathClass([2, 4, 6])
math_object3.sum_function()
Out:
12

In this example, we’ve created a function called sum_function that sums everything in the list.

Let’s add another function for finding the max value in the list.

# Adding some functions to the class

class mathClass:
    # setting a couple of values
    class_name = "This is the mathClass"
    version = "This is version 1.0"


    # initializing the list value
    def __init__(self, list_value):
        self.list_value = list_value


    # creating a sum function
    def sum_function(self):
        cnt = 0
        for i in self.list_value:
            cnt += i
        return cnt


    # creating a max value function
    def max_value(self):
        max_val = 0
        for i in self.list_value:
            if i > max_val:
                max_val = i
            else:
                max_val = max_val
        return max_val
# Using the max_val function
math_object_new = mathClass([2, 9, 3, 4, 5])
math_object_new.max_value()
Out:
9

This is a simple example, but we can already see how useful this is.

For more info on classes, here’s the official documentation from Python.

Conclusion

In this python programming for beginners article, we went over 103 different examples in Python.

We looked at the basics of different data types, such as floats, lists, and dictionaries.

Next, we went over important programming concepts such as if statements, for loops, and functions.

Finally, we finished up by going over the basics of classes and object oriented programming.

We’ve just started to scratch the surface of Python, but it’s good to revisit these basics once in awhile.

0 Comments

Free Bonus: Top 12 Data Science Books

Free Bonus: Top 12 Data Science Books

Subscribe to our email list to get instant access to the Top 12 Data Science Books!

You have Successfully Subscribed!

Free Bonus: Top 12 Data Science Books for 2018

Free Bonus: Top 12 Data Science Books for 2018

You have Successfully Subscribed!

Top 12 Data Science Books

Top 12 Data Science Books

Sign up with your email address to get instant access for free!

You have Successfully Subscribed!

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive access to the Python Programming for Beginners PDF guide for FREE!

You have Successfully Subscribed!

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive access to the Python Programming for Beginners PDF guide for FREE!

You have Successfully Subscribed!