Skip to content
Home » META » Meta Back-End Developer Professional Certificate » Programming in Python » Week 2: Basic Programming with Python

Week 2: Basic Programming with Python

Learn basic Python syntax, to use control flow and loops and work with functions and data structures. You will also learn how to recognise possible errors, their causes and how to handle them.

Learning Objectives

  • Explain the core concepts that underpin the Python programming language.
  • Work with variables and different data types in Python.
  • Use control flow and loops to execute code under specific conditions.
  • Work with functions and data structures in Python.
  • Recognize possible errors, their causes and how to handle them.
  • Create, read and write data in files

Functions and Data Structures


Video: Functions

Functions are a set of instructions that take an input and return an output. They are a modular piece of code that can be reused repeatedly.

To declare a function in Python, use the def keyword followed by the name and task to complete. Optional parameters can also be added after the function name within a pair of parentheses.

Here is an example of a function to add two values:

def sum(x, y):
  return x + y

To use a function, simply call it by name and pass in the required arguments. For example, to add the numbers 10 and 20, you would call the sum() function like this:

result = sum(10, 20)

The result of the function call will be stored in the variable result. In this case, result will be equal to 30.

Functions can also be used to return more complex values, such as the result of a calculation or the output of a database query.

For example, the following function calculates the tax amount for a given bill amount and tax rate:

def calculate_tax(bill_amount, tax_rate):
  return bill_amount * tax_rate / 100

To use this function, you would pass in the bill amount and tax rate as arguments. For example, to calculate the tax amount for a bill of $100 with a tax rate of 10%, you would call the function like this:

tax_amount = calculate_tax(100, 10)

The result of the function call will be stored in the variable tax_amount. In this case, tax_amount will be equal to $10.

Functions are a powerful tool that can help you to write more efficient and reusable code.

Functions in Python

Functions are a fundamental building block of Python and most other programming languages. They allow you to group together related code and reuse it throughout your program.

To define a function in Python, use the def keyword followed by the name of the function and its parameters (if any). The body of the function is indented below the def keyword.

For example, the following function prints a greeting to the console:

def greet(name):
  """Prints a greeting to the console."""
  print(f"Hello, {name}!")

# Example usage:
greet("Bard")

Output:

Hello, Bard!

Functions can also return values. To do this, use the return keyword. For example, the following function returns the sum of two numbers:

def add(x, y):
  """Returns the sum of two numbers."""
  return x + y

# Example usage:
result = add(10, 20)
print(result)

Output:

30

You can call functions from anywhere in your program. To do this, simply type the name of the function followed by parentheses. For example, the following code calls the add() function from the previous example:

def main():
  result = add(10, 20)
  print(result)

if __name__ == "__main__":
  main()

Output:

30

Functions can also take other functions as parameters. This is called a higher-order function. For example, the following function takes a function as a parameter and applies it to a given value:

def apply(function, value):
  """Applies the given function to the given value."""
  return function(value)

# Example usage:
result = apply(add, 10)
print(result)

Output:

10

Functions can be used to make your code more modular and reusable. By grouping together related code into functions, you can make your code easier to read, understand, and maintain.

Here are some additional tips for using functions in Python:

  • Use descriptive function names so that it is clear what the function does.
  • Document your functions using comments. This will help other developers to understand how to use your functions.
  • Use functions to break down complex tasks into smaller, more manageable steps.
  • Use functions to avoid repeating yourself. If you find yourself writing the same code multiple times, consider putting it into a function.
  • Use higher-order functions to make your code more flexible and reusable.

Functions are a powerful tool that can help you to write better Python code.

A function is a modular piece of code that can be used repeatedly. True or false?

True

Well done, a function is a modular piece of code that can be used repeatedly.

What are functions? At the most basic level, you can think of
functions as a set of instructions that take an
input and return and outputs. For example, the primary task of the print function
is to print a value. This value is usually printed to the screen and it’s passed to the print function
as argument. In the example we have here, the string hello world is the value passed to
the print function. By the end of this video, you’ll be able to declare
a function in Python, pass data into a function, and return data from a function. A Python function is
a modular piece of code that can be
re-used repeatedly. You’ve used some Python functions
already in this course, such as print and input. Both are functions
and each one has a specific task or
action to complete. The input function will
accept parameters too, but will also accept
input from the user. So how do you
declare a function? A function is declared using the def keyword followed by the name and
task to complete. Optional parameters
can also be added after the function name
within a pair of parentheses. Here is an example of creating a function to add two values. Type the def keyword followed by the
function name of sum, then enter x and
y as parameters. Finally, enter return x plus
y as the task to complete. I’ll now give a practical
demonstration of functions, how to declare them, how they’re used, and
how they can also simplify your code by putting it into a
reusable structure. Let’s start with a short
example that explains how to calculate a tax
amount for a customer, based on the total
value of that bill. I’ll start by declaring
two variables. I type the first variable called bill and I assign it the number, let’s say, 175.00. I know this is going to be a datatype known
as floats because I’m using decimal points as
is the norm for currency. The second variable
is the tax rate, which is the percentage tax rate that should be
applied to the bill, so I put in 15. Then what I want
to do is calculate the amount of tax
for the bill itself. What I do is add this into another variable
called total tax. I then do the calculation, which is the bill
multiplied by the tax rate and then divided by 100
to get a dollar amount. To output the value, I print the total tax and pass the total tax variable
and then run the program. Total tax is 26.25, which is 15 percent of 175. In the real-world, the bill
value will be different for each customer and the tax
rates may also change. Updating each variable
every time is inefficient. To overcome this problem, I’ll create a reusable function. To start creating a function, I use a define command
or def for short. Then I’ll give it a name that relates to the task
it’s carrying out. In this case, it’s going
to be calculate tax. With functions, you
can pass in arguments. The purpose of that is
to make it more dynamic. Consider the arguments
that I need to take in. I’ll take in a bill, which would be the total
value of the bill itself, and then also a tax rate. Then like I’ve done before, I’ll calculate the total
tax by taking the bill, multiplying it by the tax rate, and then dividing it by 100. Then I do a return, write bill in parenthesis, multiply it by tax rate, and divide by 100. Now I can remove the
declaration I made earlier for the variables
and the calculation. With a function, if you run
the current code as is, it will come back with nothing because a
function is only ever run when it’s actually being called. I’ll demonstrate this. If I do a print, I can calculate tax and then I pass
it as I’ve done earlier. One hundred and seventy five is the total bill and then
the tax rate will be 15. I’ll also put in
just the total tax and then click on “Run”, and the total tax is 26.25. If I want to change the rate, I can reuse the same
function, total tax. I’ll call the function,
again, calculate tax. I’ll give it a different value
for a bill, say, 164.33. This time I’ll change the
tax rate to 22 percent. Clear the screen, and
then click on “Run” and my total tax for the
second item is 36.1526. To clean the outputs
up a bit and make it more visually appealing, I’ll put in a round function
which allows control of the number of decimal places
that I want returned. In this case, I’ll do two
and then rerun the code. This is a lot neater with 36.15. One of the nice things about a function is that you
can update it once and any part of the
code that calls that function will get
those changes as well. In this video, you’ve explored basic functions in Python, how to declare functions, and pass and return
data to and from them.

Video: Variable scope

Scoping in Python

Python has four types of scope:

  • Built-in scope: This scope contains all of the built-in functions and keywords in Python.
  • Global scope: This scope contains all of the variables that are declared outside of any function.
  • Enclosing scope: This scope contains all of the variables that are declared in the enclosing function.
  • Local scope: This scope contains all of the variables that are declared inside the current function.

The innermost scope has access to all of the outer scopes. So, a local variable can access a global variable, but a global variable cannot access a local variable.

Example:

Python

my_global = 10

def fn1():
    local_v = 5

    def fn2():
        enclosed_v = 8

        print("Access to global:", my_global)
        print("Access to enclosure:", enclosed_v)

    fn2()

fn1()

Output:

Access to global: 10
Access to enclosure: 8

In this example, the fn2() function has access to the enclosed_v variable, which is declared in the enclosing scope (fn1()), and the my_global variable, which is declared in the global scope.

Why is scoping important?

Scoping is important because it helps to prevent accidental or unwanted changes to variables. For example, if a global variable is accidentally changed inside of a function, it could affect the entire program.

Tips for using scope:

  • Avoid using global variables whenever possible.
  • Use descriptive variable names to make it clear which scope a variable belongs to.
  • Use comments to document the scope of variables.

By following these tips, you can help to write more maintainable and reliable Python code.

Variable scope in Python

Variable scope in Python refers to the region of the program where a variable can be accessed. Python has four types of scope:

  • Built-in scope: This scope contains all of the built-in functions and keywords in Python.
  • Global scope: This scope contains all of the variables that are declared outside of any function.
  • Enclosing scope: This scope contains all of the variables that are declared in the enclosing function.
  • Local scope: This scope contains all of the variables that are declared inside the current function.

The innermost scope has access to all of the outer scopes. So, a local variable can access a global variable, but a global variable cannot access a local variable.

Here is an example to illustrate the different types of scope:

Python

# Global variable
my_global = 10

def fn1():
    # Local variable
    local_v = 5

    def fn2():
        # Enclosed variable
        enclosed_v = 8

        print("Access to global:", my_global)
        print("Access to enclosure:", enclosed_v)

    fn2()

fn1()

Output:

Access to global: 10
Access to enclosure: 8

In this example, the fn2() function has access to the enclosed_v variable, which is declared in the enclosing scope (fn1()), and the my_global variable, which is declared in the global scope.

Why is scope important?

Scope is important because it helps to prevent accidental or unwanted changes to variables. For example, if a global variable is accidentally changed inside of a function, it could affect the entire program.

Tips for using scope:

  • Avoid using global variables whenever possible.
  • Use descriptive variable names to make it clear which scope a variable belongs to.
  • Use comments to document the scope of variables.

By following these tips, you can help to write more maintainable and reliable Python code.

Here are some additional tips for using variable scope effectively:

  • Use local variables whenever possible. This will help to keep your code more modular and easier to understand.
  • Use global variables sparingly. Only use global variables when absolutely necessary.
  • Use descriptive variable names. This will help you to keep track of which variables are accessible in which scopes.
  • Use comments to document your code. This includes documenting the scope of your variables.

By following these tips, you can help to write more maintainable and reliable Python code.

In your program, you’ve declared the enclosed variable a = ‘Hello’.

At which scope levels is this variable accessible?

Select all that apply

Local

Correct! Enclosed variables can be accessed locally.

Enclosed

Correct! As this is the level of declaration, the variable is accessible here.

The concept of scoping
and Python allows for greater control over
elements in your code, which reduces the chances of accidental or unwanted changes. By the end of this video, you’ll be able to understand
the basics of scoping in Python and identify the
four types of scope. Before you explore scope
and its intricacies, It’s important to know that Python has different
types of scope. You’ll examine
each one in detail and I’ll demonstrate them
with coding examples. In order of ascending coverage, the fourth scopes are local, enclosing, global, and built-in. Together, they’re
referred to as LEGB. Variables within the
built-in and global scope are accessible from
anywhere in the code. For example, if there’s a
variable a in the global scope, it can be called encode
at the local level. The purpose of scope is
to protect the variable, so it does not get changed
by other parts of the code. For instance, let’s
say you’ve declared a variable b in the enclosed scope and
variable c locally. While b can be called
in local code, it doesn’t work the
other way round. As a rule, global scope is
generally discouraged in applications as this increases the possibility of
mistakes in outputs. Now, I’ll explore using the four different types of Python scopes in this
practical demonstration. The first one I want to
use is global scope. I declare a variable called my global and then give
it a value of 10, so the next thing
I do is declare a function and I call it fn1, and inside this function, I will declare another variable, which I’ll call local
variables or local_v, and give it a value of five. To show that my global variable is accessible from anywhere, I can do a print statement, say access to global, and then print out the value
of the my_global variable, and if I want to
run that function, I need to specifically call it, so fn1, click on ”Run” and then
the value of 10 is printed out for the
global variable. But if I try and print
out the local variable inside f and one
outside the function, it will return an error, so I access to local
and then puts out local underscore v. I’ve
been clever console, click on ”Run” and I get
an error saying name error, name local underscored
v is not defined. That’s because it’s only
accessible from within the local scope of
the function fn1. Next, to illustrate
an enclosing scope, I’m going to declare
a second function inside fn1 called fn2. I then declare an
enclosed variable, which I call enclosed fee, and assign it the
value of eight. The local v will be
local to the fn2. I’ll now explain how
enclosed scope works. Within fn2, I’ve got
access to the enclosed_v, which I can demonstrate by doing another print statement and printing out the
enclosed_v variable. I’ll just test that
this will works by calling the fn1 function and then making sure that I call our fn2 function inside fn1, I must physically call a
function to make it run, so I clear the
console, click on Run, and then prints out
access to global 10 and access to
enclosure eight. The way scoping works is that the innermost function has access to almost everything
from the outside. You can access the enclosed
variable at this level and then also access the global variable at
the outer level. The same rules still
apply from the outside, so if I try and access the
variable of enclosed_v, or trying to access the
variable of local v, I get the same error that the variable enclosed_v
is not defined. The nested items have
access to both the global and the enclosed,
but from the outside, it can’t be accessed from a
nested or an enclosed scope, both the local and enclosed. The last globe is
built-in scope, which you’ve been using when
writing code in Python. Built-in scope refers to what’s called the reserve keywords, such as print and def. Built-in scope covers all
the language of Python, which means you
can access it from the outermost scopes or the innermost scopes in
the function classes. That’s a brief demonstration
of scope in Python, including examples of global, local, enclosed and built-in. By completing this video, you’ve gained a broad
understanding of why scoping is important
in Python programming, and you are now able to identify
the four types of scope.

Reading: Function and variable scope

Reading

Reading: What are data structures?

Reading

Video: Lists

Lists are a sequence of one or more different or similar datatypes. They are dynamic arrays that can hold any datatype.

To create a list, you use brackets [] and separate the items with commas. For example, list1 = [1, 2, 3, 4, 5].

Lists can be nested. For example, list2 = [1, [2, 3, 4], 5].

To access an item in a list, you use the index of the item. The index starts at 0. For example, list1[0] would return the value 1.

To add an item to a list, you can use the append() method. For example, list1.append(6) would add the value 6 to the end of the list.

To remove an item from a list, you can use the pop() method. For example, list1.pop() would remove the last item from the list.

To iterate through a list, you can use a for loop. For example, for item in list1: print(item) would print each item in the list.

Lists in Python

A list is a collection of items in a particular order. You can store any type of data in a list, such as numbers, strings, or even other lists.

Creating lists

To create a list, you use square brackets [] and separate the items with commas. For example, the following code creates a list of numbers:

Python

list1 = [1, 2, 3, 4, 5]

You can also create a list of strings:

Python

list2 = ["apple", "orange", "banana"]

Or a list of mixed data types:

Python

list3 = [1, "apple", True]

Accessing items in lists

To access an item in a list, you use the index of the item. The index starts at 0. For example, the following code would print the first item in list1:

Python

print(list1[0])  # Prints 1

The following code would print the last item in list2:

Python

print(list2[-1])  # Prints "banana"

Modifying lists

You can modify lists by adding, removing, or changing items.

To add an item to a list, you use the append() method. For example, the following code would add the number 6 to the end of list1:

Python

list1.append(6)

To remove an item from a list, you use the remove() method. For example, the following code would remove the number 2 from list1:

Python

list1.remove(2)

To change an item in a list, you use the index of the item. For example, the following code would change the first item in list2 to “pear”:

Python

list2[0] = "pear"

Iterating over lists

To iterate over a list, you use a for loop. For example, the following code would print each item in list1:

Python

for item in list1:
  print(item)

Nested lists

A nested list is a list that contains other lists. For example, the following code creates a nested list:

Python

list4 = [[1, 2, 3], [4, 5, 6]]

To access an item in a nested list, you use the index of the outer list and the index of the inner list. For example, the following code would print the first item in the first inner list in list4:

Python

print(list4[0][0])  # Prints 1

List comprehension

List comprehension is a way of creating lists in a concise way. For example, the following code creates a list of the squares of the numbers from 1 to 10:

Python

list5 = [x * x for x in range(1, 11)]

This is equivalent to the following code:

Python

list5 = []
for x in range(1, 11):
  list5.append(x * x)

Conclusion

Lists are a versatile and powerful data structure in Python. They can be used to store any type of data, and they can be modified in a variety of ways.

You need to add a new item to an existing list at a specified point in the index in your Python code. Which of the following functions can you use to complete this action?

insert()

Correct! The insert function is used to insert an item within an existing list at a specified index.

Lists are a sequence of one or more different
or similar datatypes. A list in Python is essentially a dynamic array that
can hold any datatype. Let’s move to the console
and I’ll demonstrate some practical examples
of Python lists. First, I’ll go through a few examples of
declaring lists. I create my list by typing list1= and then the numbers 1, 2, 3, 4, 5 within brackets
and separated by commas because you use commas to separate
items in a list. List2 is a list
of strings, A, B, C. I can also have a list
of different datatypes. For example, in my list3, I can have a string, an integer, a Boolean, and a float. The type doesn’t
necessarily matter. It’s just going to be
stored in the same way. One thing to keep in mind with lists is that they are
based on an index. For example, let’s
suppose I wanted to access the number 3
from my list1 example. Since the index always
starts with zero, I’d have to write list1[2]. This gets the third
item in the list, which is number 3. If I do print that, I get the value of 3
being printed out. An important option
with lists is that you can also have nested lists. If I declare another
list, for example, list4, and I put in 1, then I can have a
nested list of 2, 3, and 4 and then get
back to a 5, and 6. That’s completely valid as well. Any datatype can be stored
within the list itself, just to keep that in mind. Let’s see what
else lists can do. I’ve got a few different
options to add items to a list. One is to use the
insert function. Just before I do that, I’ll just do a print. To print out the entire list, there are a couple of
different ways I can do it. I can use the star sign list1, click on ”Run”, and I get
the entire list printed out. To print it the way
it is displayed in my code I can use the
print statement type in list1 in just
putting a separator equals and then comma
with just single-space. I click on ”Run” and I get this type of prints returned. Back to adding something
new to the list. The first option that I have is what’s called the
insert function. I can do list1.insert. What it looks for is the
index of where to insert to. Here I can use the LEN, or LEN function to get
the length of the list1. Then I put in what the
next value should be. In this case, I put
it in number 6. I do the same print statement
directly underneath that. Then click on ”Run”
and I find that I get six added to the end list. I can also use another
function called append. Instead of having to specify the index or where the
items should be placed, I can just put it in
the append keyword. I type append 6 and
click on ”Run”, and it’s added in without
having to specify the index. There is another function
I can use if I wanted to add one or more
items to the list. It’s called extend. This will accept a list as well. I can put an extend 6, 7, 8, 9 and then click on ”Run”, and then my list is
extended with 6, 7, 8, and 9. To remove something from a list, there are a few
different options. The first way is to use
pop and then specify the index or location of
which item I want to remove. To demonstrate pop, I’ll
say pop for, for index 4. I click on ”Run” and the last item from
the list is removed. Remember, within the list, the index always starts at zero. Index 4 means the fifth
item being the value 5, and that’s what
has been removed. Another option is the
delete or del keyword. I can say del list 1 and then specify the
index to delete. In this case, I put
in the index of 2, click on ”Run” and
the index 2 is removed, which in this case
is the number 3. 0, 1, 2 is the number three. Lastly, I can iterate
through a list. One of the main reasons I
use lists is that I can iterate through the
values and gain access to large amounts of data. To iterate, I can use
a simple four loop. So, the X in list1, and then I can do a
simple print out. I’ll just remove
this one underneath. I’d like to print
out the value of X. I just put in print
value and then X. When I click on ”Run”, it will print all
values of the list. That’s a brief
demonstration of what you can accomplish using
list in Python. You just covered how a list in Python works as a dynamic array. You explored lists and
learned how to use inbuilt functions of a list
to access the list items, modify them, add to the list, and remove items from the list.

Video: Tuples

Tuples are data structures that can be used to store different types of data. They are immutable, meaning that their values cannot be changed once they have been created. Tuples can be used to create solid, well-performing code.

To declare a tuple, use parentheses to enclose a comma-separated list of values. For example, the following code declares a tuple called my_tuple:

Python

my_tuple = (1, 'string', 4.5, True)

To access the values in a tuple, use the index operator. For example, the following code prints the second value in my_tuple:

Python

print(my_tuple[1])

Tuples provide a number of methods, such as count() and index(). The count() method returns the number of times a given value appears in the tuple. The index() method returns the index of the first occurrence of a given value in the tuple.

Tuples are immutable, meaning that their values cannot be changed. For example, the following code will result in an error:

Python

my_tuple[0] = 5

This is because the value at index 0 in my_tuple is immutable.

Tuples are a versatile and powerful data structure that can be used to create solid, well-performing code.

Tuples in Python

A tuple is a collection of Python objects that are ordered and immutable. Tuples are created by enclosing a comma-separated list of values in parentheses. For example, the following code creates a tuple called my_tuple:

Python

my_tuple = (1, 'string', 4.5, True)

Creating tuples

There are a few different ways to create tuples in Python. The most common way is to use parentheses, as shown in the example above. However, you can also create tuples without using parentheses, as shown in the following code:

Python

my_tuple = 1, 'string', 4.5, True

This is known as the “tuple literal” syntax. It is important to note that the tuple literal syntax is only valid if the last item in the tuple is not a trailing comma. For example, the following code would result in a syntax error:

Python

my_tuple = 1, 'string', 4.5, True,

Accessing tuple elements

Tuple elements can be accessed using the index operator. For example, the following code prints the second element in my_tuple:

Python

print(my_tuple[1])

This will print the string "string".

Tuple methods

Tuples provide a number of methods, such as count() and index(). The count() method returns the number of times a given value appears in the tuple. The index() method returns the index of the first occurrence of a given value in the tuple.

For example, the following code prints the number of times the value 1 appears in my_tuple:

Python

print(my_tuple.count(1))

This will print the number 1.

The following code prints the index of the first occurrence of the value "string" in my_tuple:

Python

print(my_tuple.index('string'))

This will print the number 1.

Tuple immutability

Tuples are immutable, meaning that their values cannot be changed. For example, the following code will result in an error:

Python

my_tuple[0] = 5

This is because the value at index 0 in my_tuple is immutable.

Tuple uses

Tuples are a versatile data structure that can be used for a variety of purposes. Some common uses for tuples include:

  • Storing data that is unlikely to change
  • Creating keys for dictionaries
  • Passing arguments to functions
  • Returning multiple values from functions

Conclusion

Tuples are a powerful and useful data structure that can be used to create solid, well-performing code. By understanding the basics of tuples, you can start using them to solve your own programming problems.

You have declared the following tuple my_tuple = (1, 2, "hello"). This tuple contains two items of type integer and a third item of type string. Can you create tuples that have items with different data types?

Yes

Correct! A tuple can accept any mix of data types.

In this video,
you will learn about tuples and how that can be used to store
different types of data. They’re used as data structures and help
to create solid, well performing code. To declare a tuple,
I declare a simple variable. I’ll name it my underscore tuple. And then I do the assignment
operator of equals, then to declare the tuple itself,
I use parentheses. A tuple can accept any mix of data types. And it can range from integers like one,
to strings, to a double,
such as 4.5 to a boolean like true. To access any of the items
within the tuple. I can use methods similar to those used
with the list by referring to an index. So in my underscore tuple, if I want to get access to the string
which I know is going to be on index one. I just print out the value. So I write,
Print My _ Triple Brackets, one. Remember Index always starts with zero. A quick on run and I find that
it returns the value of strings. If I want to determine
the type of the tuple, I can use the type function
that python provides. I click on run and I get a class tuple. We could also declare a tuple
without using the parentheses. It has the same effect and
will still be classed as a tuple. However, it’s best practice
to use the parentheses. Tuples also provide different
methods of count and index. I can do my underscore tuple dot count and
passing the value of strings. I click on run and
I get back to count of one. What it does is it looks for the number of occurrences of
that value within the tuple. Before I move on, I’ll type clear into my
terminal to clear the previous output. So we could start fresh and
see what’s going to happen next. The other method is index, which would give me back the index of
where the value lies in the tuple. I’ll change the print statement to
look up the index of the double 4.5. When I click on run, I get back two. This means that the double 4.5
is at Index two in the Tuple. I can also do a loop manageable. That is iterate through the values and
print them out. I can write a loop for X in my underscore
tuple and then print out the value of X. I click on run and I get back one,
strings 4.5 and true. So all the values of the tuple itself. The one key difference of a tuple over
a list is that tuple values are what’s called immutable. And this just means that
they cannot be changed. So I’ll prove this and
demonstrate how this works. Let’s say that I want to change the value
with the very first item in the tuple being the value one. I’ll use zero to access
it based on the index. And let’s say that I want
to change it to be five. If I run this, I’ll get back an error. And it gives me the error
saying type error, tuple object does not
support item assignment. That’s because anything that is
declared in a tuple is immutable. In this video, you learned about tuples,
including how to declare them and work with their contents.

Video: Sets

This video is about sets, a collection of unique and unaltered items. Sets are created using curly braces and can be manipulated using various methods such as add(), remove(), discard(), union(), intersection(), difference(), and symmetric_difference(). Sets are not sequences and do not have an ordered index of elements.

Sets in Python

A set is a collection of unique and unordered elements. Sets are created using curly braces {}, and the elements within a set are separated by commas. For example, the following code creates a set called my_set:

Python

my_set = {1, 2, 3, 4, 5}

Sets can be used to store a variety of data types, such as integers, floats, strings, and even other sets. For example, the following code creates a set containing a mix of data types:

Python

my_set = {1, 2.5, "Hello", {1, 2, 3}}

Set Operations

Sets support a number of operations, including:

  • add(): Adds an element to the set.
  • remove(): Removes an element from the set.
  • discard(): Removes an element from the set if it is present. If the element is not present, nothing happens.
  • union(): Returns a new set containing the union of two sets.
  • intersection(): Returns a new set containing the intersection of two sets.
  • difference(): Returns a new set containing the difference of two sets.
  • symmetric_difference(): Returns a new set containing the symmetric difference of two sets.

For example, the following code adds the element 6 to the set my_set:

Python

my_set.add(6)

The following code removes the element 3 from the set my_set:

Python

my_set.remove(3)

The following code creates a new set called new_set containing the union of my_set and the set {6, 7, 8}:

Python

new_set = my_set.union({6, 7, 8})

The following code creates a new set called new_set containing the intersection of my_set and the set {6, 7, 8}:

Python

new_set = my_set.intersection({6, 7, 8})

The following code creates a new set called new_set containing the difference of my_set and the set {6, 7, 8}:

Python

new_set = my_set.difference({6, 7, 8})

The following code creates a new set called new_set containing the symmetric difference of my_set and the set {6, 7, 8}:

Python

new_set = my_set.symmetric_difference({6, 7, 8})

Set Membership

The in operator can be used to test whether an element is a member of a set. For example, the following code returns True if the element 3 is in the set my_set:

Python

3 in my_set

Set Comprehensions

Set comprehensions can be used to create sets in a concise and readable way. For example, the following code creates a set containing the squares of the integers from 1 to 10:

Python

my_set = {x * x for x in range(1, 11)}

Conclusion

Sets are a powerful and versatile data structure that can be used to store a variety of data. Sets support a number of operations that make them well-suited for a variety of tasks.

Can you place duplicate values inside your declared sets?

No

Correct! Sets do not accept duplicate values.

In this video, you will learn about sets,
and how they can help with storing certain types of
data in different types of formats. First, I declare a set, I can start
by declaring a simple variable called set_a= and then use curly braces
to define the set itself. Then the values go inside the brackets,
I put in 1, 2, 3, 4 and 5. I’ll do a simple print out
to prove that we have a set, I click on run to get
the values 1 to 5 printed out. Sets differ slightly from lists,
in that they don’t allow duplicate values. I can demo this by putting in another 5,
when I click on run, I find that the second 5 is
not printed out in the list. Sets also have methods that we can use,
I can use a method to add new content. If I use set_a.add (6),
I can add in the number 6, I click on run to find that
the value 6 is added to the set. I could also use the remove method,
I’ll remove the number 2, when I clicked on run, I found
the number 2 was removed from the set. There’s also discard, which essentially
does the same thing as remove. Using discard, when I click on run
I’ll find that I get the same output. Let me clear the console
before we go any further. There are also a few useful methods
that can be used with sets to perform mathematical operations,
let me demo some of them now. First, I will create a new set,
set_b, I will put in 4, 5, 6, 7 and 8, and reset the values
of set_a to the original values. There are two ways I could
use mathematical operators. For instance, for a union join,
I can do set_a.union and then pass in set_b, then, I can click
on the run button to see what happens. I discover that it joins the two sets
together minus the duplicate values like 4 and 5, union merges them into one. So, you have a set 1, 2, 3, 4, 5, 6, 7, 8. For the other options for union,
I can use the vertical line symbol or the 0 symbol and
that works in the same way. Let me clear the console before we go on. Another operation I can use is the
intersection, I can apply this to set_a by writing set_a.intersection and
passing set_b as the argument. When I click run, I get back all
the items that match in both set_a and set_b, here we have 4 and 5. The intersection can also be
represented by the ampersand and will work in the same way. When I click on run,
I also got back 4 and 5, let me clear the console
again before we continue. Another mathematical operation I
can use is the set difference. To use this,
all print set_a.difference(set_b), and this should give me back all the elements
that are only in set_a and not in set_b. When I clicked run,
we got the correct output of 1, 2 and 3. I could also represent difference
by using the minus symbol, when I click on run, I’ll also get
back the same values, 1, 2 and 3. The last operation I’ll discuss is
what’s called symmetrical difference. This is represented by
the symmetric difference function, which is used in a similar way. When I click on run,
I get back 12367 and eight. In other words, all of the elements
that are present in set A. Or set B. But not in both sets, symmetrical difference can also be
represented by the carrot operator. When I click on run,
I get back the same values. An additional important thing about
sets is that a set is a collection with no duplicates but
it’s also a collection of unaltered items. Unlike a list where I can print
out content based on index. If I try to print out set a bracket zero
to get the zeroth element in the set, I’ll get an error. Let me clear my console. Before we attempt to print this output. When I click on run, I get back a type
error saying that the set object is not subscriptable this means
that the set is not a sequence, it doesn’t contain an ordered
index of all elements inside. Okay, that concludes our
gentle introduction to sets. Great job.

Video: Dictionaries

A dictionary in Python is a collection of key-value pairs. The keys can be numeric, string, or any other type of object. The values can be any type of object as well. Dictionaries are optimized for retrieving values based on their keys. This makes them much faster than using traditional lists for this purpose. To create a dictionary, you use curly braces {}. Inside the curly braces, you list a series of key-value pairs, separated by commas. For example, the following code creates a dictionary with two key-value pairs:

Python

my_dict = {
  "name": "John Doe",
  "age": 30
}

To access the value for a key, you use the square bracket notation. For example, the following code prints the value of the “name” key in the my_dict dictionary:

Python

print(my_dict["name"])

This will print the string “John Doe” to the console.

Dictionaries are a powerful data structure that can be used for a variety of purposes. They are commonly used to store data about objects, such as user profiles or product information. Dictionaries can also be used to store data about relationships between objects, such as a mapping of friends on a social network.

In summary, dictionaries are a versatile and efficient data structure that can be used for a variety of purposes.

Tutorial on Dictionaries in Python

A dictionary is a collection of key-value pairs. The keys are used to identify the values. Dictionaries are unordered, meaning that the order of the key-value pairs does not matter.

Creating a Dictionary

To create a dictionary, you use curly braces {}. Inside the curly braces, you list a series of key-value pairs, separated by commas. For example, the following code creates a dictionary with two key-value pairs:

Python

my_dict = {
  "name": "John Doe",
  "age": 30
}

Accessing Values in a Dictionary

To access the value for a key, you use the square bracket notation. For example, the following code prints the value of the “name” key in the my_dict dictionary:

Python

print(my_dict["name"])

This will print the string “John Doe” to the console.

Adding and Removing Items from a Dictionary

To add an item to a dictionary, you use the square bracket notation and assign a value to the key. For example, the following code adds a new key-value pair to the my_dict dictionary:

Python

my_dict["city"] = "San Francisco"

To remove an item from a dictionary, you use the del keyword. For example, the following code removes the “age” key-value pair from the my_dict dictionary:

Python

del my_dict["age"]

Iterating over a Dictionary

To iterate over a dictionary, you can use the for loop. The following code iterates over the key-value pairs in the my_dict dictionary:

Python

for key, value in my_dict.items():
  print(key, value)

This will print the following output to the console:

name John Doe
city San Francisco

Dictionary Methods

Dictionaries have a number of built-in methods that can be used to perform various tasks. Some of the most common methods include:

  • clear(): Removes all items from the dictionary.
  • copy(): Creates a shallow copy of the dictionary.
  • get(): Returns the value for a key, or a default value if the key does not exist.
  • items(): Returns a list of tuples containing the key-value pairs in the dictionary.
  • keys(): Returns a list of the keys in the dictionary.
  • pop(): Removes an item from the dictionary and returns the value.
  • popitem(): Removes and returns a random key-value pair from the dictionary.
  • setdefault(): Returns the value for a key, or sets a default value if the key does not exist.
  • update(): Updates the dictionary with the key-value pairs from another dictionary.
  • values(): Returns a list of the values in the dictionary.

Conclusion

Dictionaries are a powerful and versatile data structure that can be used for a variety of purposes. By understanding the basics of dictionaries, you will be able to use them to store and retrieve data efficiently.

In a Python dictionary, each value has a unique identifier. This combination is known as:

The Key-Value Pair

Well done. Each item in the dictionary is a value within a key-value pairing.

What is a dictionary in Python? In many ways, it’s
very similar to how an actual dictionary works. In a normal dictionary, to locate a word, you look it up by the
first letter and then use the alphabetical ordering
system to find its location. Likewise, Python dictionaries are optimized to
retrieve values. You may remember how useful Python lists are to access
an array of values. Dictionaries access
values based on keys and not on index position. Therefore, they are faster and more flexible in operation. By the end of this video, you’ll be able to explain the purpose and function
of dictionaries in Python and identify the performance
benefits of dictionaries. With a Python dictionary, a key is assigned to
a specific value. This is called the
key-value pair. The benefits of this
method is that it’s much faster than using
traditional lists. To find an item in a list, you need to keep
reviewing the list until you locate the item. But in a Python dictionary, you can go straight
to the item you need by using its key. A dictionary is also
immutable in that the values can be
changed or updated. For example, you could declare
the number 1 as the key, and coffee is the item, and then change these to any
other number or drink item. But how does this work? How do you access or
locate the item you need within a Python dictionary
with the use of the keys? To demonstrate this, I’ll access the coffee item within
a Python dictionary. First, I declare my dictionary name as
sample dictionary. Then an equals with a series
of key-value pairings or keys and items in a
pair of curly braces. I also make sure to separate
each pairing with a comma. I then type the print function followed by the name
of my dictionary. I need to access coffee item, which has been
given a key of one. I insert the number one
in square brackets. I run the print function and it returns coffee as a result, just as I intended. I can also update
a dictionary by replacing one item with another. I just need to use the key
to reference it while using the assignment operator
equals to assign the value. For example, I can change Item 2 in my dictionary
from tea to mint tea. I just write a new
line of code that starts with the name
of the dictionary, followed by the key I want to
change in square brackets. Then I add an equals operator followed by the name
of the new item. What the coding says
is to take Item 2 in the sample dictionary
and change it to mint tea. When I run this function, it changes the item. I can also delete an item
from the dictionary. To do this, I write
a line of code with the delete function followed by the name of my dictionary. Then I add the key
for the item I want to delete in
square brackets. In this instance, I want
to delete Item 3, juice. When I run this delete function, it will remove the juice
value from my dictionary. Finally, I can also use three different methods to
iterate over the dictionary. I can use the standard
iteration method, the items function or
the values function. Let’s explore these
iteration methods and the other dictionary operations
functions in more detail. To create my dictionary, I’ll start by declaring a
simple variable called my_d, and then use the
assignment operator and then curly brackets. It can be the same as a set, but by default, that’s classed
as an empty dictionary. I can print that out by
using a print statement, using the type function
and then passing in the my_d variable,
clicking on “Run”. The class has actually come
back as a type dictionary. Next, I’ll add some values
into the dictionary, and I need to do
it in two parts. A dictionary holds what’s
called a key and a value. The key can be numeric,
it can be string. But to signify the assignment, I use a colon and then put in
whatever value that I want. In this case, I’ll put in a
simple string value of test. To signify this, I can change
or have different keys, strings, integers or ints. I put in a string key of name, and then the value, Jim. I print out my dictionary
using the print function. I now have a basic dictionary
setup with a key of one name and then one being
test name, being Jim. If I want to access a
key in the dictionary, I just have to use
the square brackets and then pass in the key-value. In this case of one I’m
passing the numeric one. In the case of the string value, I just need to pass in the
actual string value itself. Name, click on “Run”, and I get back
both test and Jim, which are the values for
each corresponding key. If I want to add a new key into the dictionary or update it, I can simply do my d and
then add a new assignment, two in this case, Test
2 click on “Run”. The key is then added with
the current dictionary. Update the key, I have to
call out the values I want. I’m just going to
update the first key, which is number 1, with a value of not a
test instead of test. Click on “Play” and it’s
updated on the screen. The other thing to note
about the dictionary is, if I try and put in
a duplicate key, it doesn’t allow this. If I put in the Number
1 and then not a test. Click on “Run” and the key will actually be overwritten
with the latest one. Number 1 only appears once in the outputs
and it doesn’t allow the two keys to be printed out because it won’t allow
duplicate values to be set. If I want to delete a key from the dictionary I’ll
use the del operator, now I type my_d and then specify which key
I want to delete. In this case, number 1 is then removed
from the dictionary. With a dictionary, I can
also iterate though. For example, I can
use the for x in my dictionary and then
print out the value of x. Click on “Run”, and I get one. This only prints out the keys. In a lot of cases, I may
need access to both. To do that, I use a
method called my items. With that, I can
then gain access to the assignment of both
the key and the value. I do a printout here,
key plus value. I’ll use some concatenation to print out both the
key and the value. Click on “Run”. I have to be mindful because I’m using an integer with a string. I wrap that with the type
str, click on “Run” again, and I get the value of
the key and the value for each of the items in
the dictionary itself. You should now
understand the purpose and function of dictionaries in Python and their benefits
in terms of performance.

Video: kwargs

Args and kwargs are two special parameters that can be used in Python functions to accept a variable number of arguments. Args are used for non-keyword arguments, while kwargs are used for keyword arguments.

Args

To use args, you simply define a function parameter with the asterisk (*) symbol before the name of the parameter. For example:

Python

def sum_of_args(*args):
  """Returns the sum of all arguments passed to the function."""
  sum = 0
  for arg in args:
    sum += arg
  return sum

print(sum_of_args(1, 2, 3))

This function will accept any number of arguments and return the sum of all of them. For example, calling the function with the arguments 1, 2, and 3 will return the value 6.

Kwargs

To use kwargs, you simply define a function parameter with two asterisk (**) symbols before the name of the parameter. For example:

Python

def calculate_total_bill(**kwargs):
  """Returns the total bill for a restaurant."""
  total = 0
  for item, price in kwargs.items():
    total += price
  return total

print(calculate_total_bill(coffee=299, cake=455, juice=299))

This function will accept any number of keyword arguments and return the sum of all of the values. For example, calling the function with the keyword arguments coffee=299, cake=455, and juice=299 will return the value 1053.

Args and kwargs are powerful tools that can be used to make your Python functions more flexible and reusable.

Sure. Here is a tutorial on kwargs in Python:

What is kwargs?

Kwargs, or keyword arguments, are a special type of argument that can be passed to Python functions. They allow you to pass in any number of keyword arguments to a function, without having to specify the names of the arguments in advance.

How to use kwargs

To use kwargs, you simply define a function parameter with two asterisk (**) symbols before the name of the parameter. For example:

Python

def my_function(**kwargs):
  """A function that accepts keyword arguments."""
  print(kwargs)

This function will accept any number of keyword arguments and print them out to the console.

To pass keyword arguments to a function, you simply use the keyword syntax. For example:

Python

my_function(name="Alice", age=25)

This will call the my_function() function with the keyword arguments name="Alice" and age=25.

Example of using kwargs

Here is an example of how to use kwargs to implement a function that calculates the total price of a shopping cart:

Python

def calculate_total_price(**kwargs):
  """Calculates the total price of a shopping cart."""
  total = 0
  for item, price in kwargs.items():
    total += price
  return total

# Example usage:
cart = {
  "apples": 2,
  "oranges": 3,
  "bananas": 4
}

total_price = calculate_total_price(**cart)

print(total_price)

This code will print the following output to the console:

19
Benefits of using kwargs

Kwargs offer a number of benefits, including:

  • Flexibility: Kwargs allow you to pass in any number of keyword arguments to a function, without having to specify the names of the arguments in advance. This makes your functions more flexible and reusable.
  • Readability: Kwargs can make your code more readable by making it clear which arguments are keyword arguments.
  • Maintainability: Kwargs can make your code more maintainable by making it easier to add new arguments to your functions later on.
Conclusion

Kwargs are a powerful tool that can be used to make your Python functions more flexible, reusable, readable, and maintainable.

The advantage of using args and kwargs is that you can pass in which of the following? Select all that apply.

Keyword arguments

Correct! You can use kwargs to pass keyword arguments.

Non-keyword variables

Correct! You can use kwargs to pass in non-keyword variables.

In this video, you’ll
explore args and also kwargs, or keyword args. Using these has the advantage that you could pass
in any amounts of non-keyword variables,
and keyword arguments. To start with a short example, I’ll define a sum of function that accepts
two parameters, a and b, and then return
back the addition, a plus b. If I do a print statement, called the function sum
of, with the two values, 4 and 5, I should get back
the value of 9, which I do. That all works fine. But let’s say I wanted
to add in another value, 6, for example. If I click on “Run” again,
I get back an error, and it tells me that the
sum of function takes two positional arguments,
but three were given. If I want a way around this, this is where args are useful. To define args, I
use the star symbol, and I call it args
for naming purposes. Instead of passing in
just two arguments, args will allow n
arguments to come through any number of arguments. When dealing with more
than one argument, there may be many
to iterate through. To calculate the total sum, I’ll have a variable called
sum, assign it to 0, then I’ll create a
simple for loop, and then I’ll loop
through the argument parameters that’s
been passed in. Then I’m going to
add all the values that come in as part of args, which is assigned
to the x variable using the plus equals, and then finally return
the value of sum. Again, if I run the statement, I get back the value of 15. As I mentioned, you could pass in any number of arguments, and the total sum should
be returned for each. In this case, it’s 30 with the number of arguments that
have been passed through. That’s a simple intro to args. Now I’ll demonstrate kwargs. Let’s clear the terminal and
switch to my kwargs file. I’ll copy the code from
the args file to start. Let’s say, for example, you wanted to calculate a
total bill for a restaurant. A user got a cup of
coffee that was 299. Then they also got a
cake that was 455, and also a juice for 299. The first thing I could do
is change the for loop. Let’s change the argument to kwargs by adding another star, and then update the
variable in the for loop. Next, I get the
key in the value, and then I extend the kwargs
with the item’s function. Then I can simply
change the sum to add all the items that are
passed through on the value, because adding the
key makes no sense. It’s just the string,
and it won’t give you the actual value
you intend to get. When I run this, I
get back a value of 10.53 with a bunch
of extra zeros. Now I can change
the decimal place for the final
return statement by using the round function and I limit it to two decimal places. When I click on “Run” again, I get back the total of 10.53. To summarize, with args, you could pass in any amount
of non-keyword variables. With the kwargs, you can pass in any amount
of keyword arguments. That’s a simple intro to
both args and kwargs.

Practice Quiz: Functions, loops and data structures

What keyword is used to create a function in Python?

What function in Python allows you to output data onto the screen?

A variable that is declared inside a function cannot be accessed from outside the function?

Which of the declarations is correct when creating a for loop?

What error will be thrown from the below code snippet?

Reading: Choosing and using data structures

Reading

Errors, exceptions and file handling



Home » META » Meta Back-End Developer Professional Certificate » Programming in Python » Week 2: Basic Programming with Python