A Short Introduction to the Python Programming Language

202037703 - Applied Artificial Intelligence

Table of Contents

Hello! My name is Gerardo Becerra, and I am a tutor at UNAD. My profession is Electronics Engineer, with a Masters in control systems and a doctorate in automatics. My main research interest are system dynamics, non linear systems, switched systems and control systems.

In this virtual learning object (OVA), you will review some basic concepts about the Python programming language. These concepts will be required to solve the practical problems proposed during the course. If you don't have previous programming experience in Python it is necessary that you get up to speed with these concepts during phase 1. You may refer to the resources referenced at the end of this OVA in case you need more information.

Welcome

Purpose

I have created this resource to present some of the main elements of the Python programming language that you will use in the development of an applied artificial intelligence project. These elements are:

  • Variables
  • Strings
  • Lists
  • Conditionals
  • Loops
  • Functions
  • Packages.

A general description and usage examples will be presented in each case.

The Python Programming Language

Python is one of the most popular programming languages in the world. Some of the reasons for this are the following:

  • It is easy to read, write and learn for beginners.
  • It is very efficient: a program can be written with fewer lines of code.
  • It is interpreted: it doesn't need to be compiled to be executed.
  • It is dynamically typed: you don't need to define the variable types before execution.
  • It is garbage-collected: memory management is performed automatically.
  • It has vast library support: there are many open-source packages that can be used in many different contexts: machine learning, image processing, scientific computation, web frameworks, databases, automation, etc.

Python Basics - Variables

A variable refers to a place where some information can be stored, such as a number, some text, a list of numbers, a list of texts, etc.

In Python, you use the equals sign (=) to create a variable and assign a value to it. For example, if we want to store the number of students per group we may write:

Variables can be made up of letters, numbers, and the underscore character (_) but they can't start with a number. It is recommended that you use meaningful names for your variables.

You can use variables to perform computations. For example, if you have 15 groups in your course, you can obtain the total number of students with the following code: 

numberOfStudentsPerGroup = 5
numberOfGroups = 15
numberOfStudents = numberOfStudentsPerGroup * numberOfGroups

Python Basics - Strings

A string usually refers to some text or a collection of characters. These may include letters, numbers and special symbols. To represent a string, you may use single quote marks (') or double quote marks ("). The following are examples of valid strings:

'This is a valid string'
"This is also a valid string"
"A single quote (') in the middle is correct."
'This is an invalid string"
"This string is also wrong'
'This string can't have single quote in the middle'

You must use the same quote mark at the beginning and the end of the string. Also, to have single quotes in the middle of a string you must use double quotes at the beginning and the end:

To create a string spanning multiple lines of text, you must use three single or double quote marks:

'''Roses are red
Violets are blue
This is a correct
multiline string'''

Python Basics - Lists

A list is a collection of elements that is ordered, changeable and allows duplicates. To represent a list you must use square brackets:

fruits = ['apples', 'bananas', 'oranges']

The elements in the list have an order. This means that each element is located at a given position:

>>> fruits[0]
'apples'
>>> fruits[1]
'bananas'
>>> fruits[2]
'oranges'

Notice that the first element has an index equal to zero.

The elements in the list can be changed:

>>> fruits[1] = 'papayas'
>>> print(fruits)
['apples', 'papayas', 'oranges']

Lists can contain any data type:

list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

Also, lists can contain elements with different data types:

list4 = ['abc', 34, True, 40.5, "male"]

Python Basics - Conditionals

Conditionals are structures useful for making decisions. The flow of the program execution changes depending on the condition evaluated. Consider the following example:

a = 200
b = 33
if b > a:
  print("b is greater than a")

The condition evaluated is          .

The if keyword indicates the start of the conditional structure. After it, you will find the condition to be evaluated.

b > a

Given the values assigned to a and b, the condition is false and the print statement isn't executed.

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

We can evaluate subsequent conditions using the keyword elif. After them, you can use the keyword else to execute the code if none of the previous conditions were true.

Python Basics - For Loops

A for loop is used to iterate over a sequence (that is either a list, a string, etc). With the for loop you can execute a set of statements, once for each item in the list, string, etc.

One important difference with other programming languages is that you don't need to use an indexing variable, as shown in the following example:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

Here, each value in the list will be assigned to variable x.

Strings are also iterable objects, containing a sequence of characters:

for x in "banana":
  print(x)

Using the break statement you can stop the loop before its completion:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

Using the continue statement you can stop the current loop iteration and continue with the next one:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

Python Basics - While Loops

A for loop is used to execute a set of statements as long as a condition is true:

i = 1
while i < 6:
  print(i)
  i += 1

In this example it is important to increment the variable i inside the loop. Otherwise, it will continue executing forever!

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

With the continue statement you can stop the current iteration and continue to the next one:

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

Using the break statement we can stop the loop even if the condition is true:

Python Basics - Functions

def my_function():
  print("Hello from a function")

To call a function, use the function name followed by a parenthesis:

A function is a block of code which only runs when it is called. A function can return data as well. To define a function the def keyword is used:

>>> my_function()
Hello from a function

Information can be passed into functions as arguments:

def my_name(name):
  print("My name is " + name)
>>> my_name("Gerardo")
My name is Gerardo

By default, a function must be called with the correct number of arguments. Otherwise, you will get an error:

>>> my_name("Gerardo","Becerra")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_name() takes 1 positional 
           argument but 2 were given

You can also send arguments with the key=value syntax:

def my_name(first_name,last_name):
  print("My last name is " + last_name)
>>> my_name(first_name="Gerardo", last_name="Becerra")
My last name is Becerra

Python Basics - Packages

pip install SomeProject

The functionality of the Python language can be extended using packages. There are different repositories where software development teams share their code. The Python Package Index (PyPI) is one of these repositories. To install a package you can use the pip tool:

where SomeProject is the name of the package you want to install. Some of the main packages that you will use in our course are the following:

  • Pandas: a fast, powerful, flexible, easy to use data analysis and manipulation tool.
  • Numpy: the fundamental package for scientific computing in Python.
  • Plotly: create interactive, publication-quality graphs.
  • Scikit-Learn: Machine learning in Python.
  • Tensorflow: Machine learning and deep learning in Python.

All these packages are open-source and free to use!

Exercises

  1. Write a function that given a list of scores in a test for all students in a group, returns the mean score value for the student group. For example if the student scores are [25, 95, 100, 35, 20], the function should return the value 55.
  2. Write a function that takes as argument two positive integer numbers and returns the list of common divisors. For example, given the numbers 54 and 24, the function should return the list [1, 2, 3, 6].
  3. Write a function that takes as input a list of names and prints the number of characters that each name has. For example, if the name list is ["Juan", "María", "Rosa", "Alejandro"], the function should print the numbers 4, 5, 4, 9.

Evaluation

Conclusion

We have reviewed some of the fundamental concepts in the Python language. It is important that you master these basic elements, because they will be required to develop the different coding activities throughout the course.

As you advance with the course, you will see why Python is the language of choice by the majority of developers, teachers and researchers for developing artificial intelligence and machine learning projects.

References

Briggs J R (2012). Python for Kids: A Playful Introduction To Programming. No Starch Press, 2012. 344 pp.

 

Matthes E (2015). Python Crash Course: A Hands-On, Project-Based Introduction to Programming. No Starch Press. 560 pp

 

w3schools.com (2022), Python Tutorial. https://www.w3schools.com/python/default.asp

Credits

 

Universidad Nacional Abierta y a Distancia (UNAD)

Escuela de Ciencias Básicas, Tecnología e Ingeniería (ECBTI)

Ingeniería Electrónica

 

Ing. Gerardo de Jesús Becerra Becerra, PhD

2022

 

 

 

 

A Short Introduction to the Python Programming Language

By Gerardo Dejesus Becerra Becerra

A Short Introduction to the Python Programming Language

  • 37