Python
Python
Introduction to Python
Artificial Intelligence course
Fall Semester 2023
Vu Ngoc Tu
Pattern Recognition Lab
1
Introduction
• Python: a high-level, general-purpose programming language designed
by Guido van Rossum (https://gvanrossum.github.io/) at Centrum
Wiskunde & Informatica (CWI) in the Netherlands.
• From the begin with version 0.9.0, now, the most recent version of
Python is 3.12.
4
Install Python
5
• 2 popular ways to install Python:
• Through original Python:
• https://wiki.python.org/moin/BeginnersGuide/Download
• Through Python distribution:
• Anaconda (the most popular – recommend):
Install • CPython:
• ...
Python • In most Linux distributions, Python is installed by default.
• If you don't want to install Python, there are many online sites
provide free machine with Python environment for you to
use.
• Google Colab
• Cheetah
6
• Some development environment for you to
code Python on local machine.
• IDLE: Python default IDE
• VSCode
• Pycharm
Install • JupyterNotebook - JupyterLab
Python • Spyder
• ...
7
Getting Started –
Work with Python on
Cheetah
8
Introduction
9
Cheetah Login page
Cheetah container
Cheetah container
Connect working environment (container)
SSH
• Cheetah offer 4 working spaces:
VSCode
Desktop
Jupyter Notebook
Python basic syntax
14
Typing things
in
• Case matters. To Python, print, Print,
and PRINT are all different things. For
now, stick with lowercase as most
Python statements are in lowercase.
Typing things in
• Python uses indentation of lines for things we’ll learn about soon. On the other hand, spaces in most other places don’t
matter.
Printing
• The print function requires parenthesis around its arguments.
• The input function is a simple way for your program to get information from people using your program (From
input keyboard).
variable name = input(message to user)
19
Variables
• Variables are used to store information to be referenced and manipulated in a computer program.
• One of the major purposes of a variable is to remember a value from one part of a program so that it can be used in another
part of the program.
• Variables name: There are just a couple of rules to follow when naming your variables.
• Variable names can contain letters, numbers, and the underscore.
• Variable names cannot contain spaces.
• Variable names cannot start with a number.
• Case matters – for instance, temp and Temp are different.
• It helps make your program more understandable if you choose names that are descriptive, but not so long that they
clutter up your program
Variables
22
Number
• Decimal numbers are represented by what are called floating point numbers. The important thing to remember about
them is you typically only get about 15 or so digits of precision. It would be nice if there were no limit to the precision,
but calculations run a lot more quickly if you cut off the numbers at some point.
• Integers in Python have no restrictions. They can be arbitrarily large.
• Round float numbers in Python – round(number, digits): The round() function returns a floating point number that is a rounded version
of the specified number, with the specified number of decimals.
• The default number of decimals is 0, meaning that the function will return the nearest integer.
Number
• Math Operators
• The Integer division operator: Basically, for positive numbers it behaves like ordinary division except that it throws away
the decimal part of the result.
• The Modulo operator: The modulo operator, %, returns the remainder from a division.
Number
26
String, List
• Creating a string A string is created by enclosing text in quotes. You can use either single quotes, ', or double quotes, ". A
triple-quote can be used for multi-line strings.
• Creating lists: Use square brackets to indicate the start and end of the list and separate the items by commas.
• Empty string: The empty string '' or "" is the string equivalent of the number 0. It is a string with nothing in it.
• Empty List: The empty list is []. It is the list equivalent of 0 or ''.
String, List
• Length: To get the length of a string/list (how many characters/items it has), use the built-in function len.
• Concatenation and repetition: The operators + and * can be used on strings. The + operator combines
two strings. This operation is called concatenation. The * repeats a string a certain number of times.
• + and *: The + operator adds one list to the end of another. The * operator repeats a list.
String, List
34
For/ While loop
• Probably the most powerful thing about computers is that they can repeat things over and over very quickly. There are
several ways to repeat things in Python, the most common of which is the for loop.
• Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the
condition becomes false, the line immediately after the loop in the program is executed.
• The syntax is important here. The word for/while must be in lowercase, the first line must end with a colon, and the
statements to be repeated must be indented. Indentation is used to tell Python which statements will be repeated.
For/ While
loop Example: Enter 5 positive numbers as input.
37
If statements
• Quite often in programs we only want to
do something provided something else is
true. Python’s if statement is what we
need.
• We have added an else statement, which is
like an “otherwise.”
If statements
• Conditional operators: The comparison operators are ==, >, <, >=, <=, and !=.
• == : equal
• > : greater
• < : less
• >=: greater or equal
• <=: less or equal
• !=: not equal
• Order of operations: In terms of order of operations, and is done before or, so if you have a complicated condition that
contains both, you may need parentheses around the or condition. Think of and as being like multiplication and or as
being like addition.
If statements
41
Functions
• Functions are defined with the def
statement. The statement ends with a
colon, and the code that is part of the
function is indented below the def
statement.
Functions
• The terms parameter and argument can be
used for the same thing: information that
are passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside
the parentheses in the function
definition.
• An argument is the value that are sent
to the function when it is called.
Functions
• The Python return statement is a special statement that you can use inside a function or method to send the function’s
result back to the caller. A return statement consists of the return keyword followed by an optional return value.
• The return value of a Python function can be any Python object.
• If you use a bare return without a return value, it will return None.
Functions
• Local variables:
• In a large program it would be a nightmare trying to
make sure that we don’t repeat variable names in
different functions, and, fortunately, we don’t have
to worry about this.
• When a variable is defined inside a function, it is
local to that function, which means it essentially
does not exist outside that function. This way each
function can define its own variables and not
have to worry about if those variable names are
used in other functions.
Functions – local
variables and global
variables
• Global variables:
• On the other hand, sometimes you
actually do want the same variable to
be available to multiple functions. Such
a variable is called a global variable.
You have to be careful using global
variables, especially in larger programs,
but a few global variables used
judiciously are fine in smaller
programs.
Object-Oriented
Programming in Python
49
Object-Oriented Programming in Python
• Python is an object-oriented programming language, and we have in fact been using many object-oriented concepts
already. The key notion is that of an object. An object consists of two things:
• data
• functions (called methods) that work with that data.
• Everything in Python is an object.
• That includes not only strings and lists, but also integers, floats, and even functions themselves.
Object-Oriented
Programming in
Python
• Creating your own classes: A class is a template for
objects. It contains the code for all the object’s methods.
• To create a class, we use the class statement. Class names
usually start with a capital.
• Most classes will have a method called __init__: The
underscores indicate that it is a special kind of method. It
is called a constructor, and it is automatically called when
someone creates a new object from your class. The
constructor is usually used to set up the class’s variables.
In the above program, the constructor takes two values, a
and b, and assigns the class variables a and b to those
values.
Object-Oriented
Programming in
Python
• self: The first argument to every method in your
class is a special variable called self. Every time your
class refers to one of its variables or methods, it
must precede them by self. The purpose of self is to
distinguish your class’s variables and methods from
other variables and functions in the program.
• To create a new object from the class, you call the
class name along with any values that you want to
send to the constructor. You will usually want to
assign it to a variable name.
• To use the object’s methods, use the dot operator,
as in e.add().
Importing modules
53
Importing modules
• import statements go at the beginning of the program, but there is no restriction. They can go anywhere as long as they
come before the code that uses the module.
• How to import modules
• The first way imports just two functions from the module.
• The second way imports every function from the module. You should usually avoid doing this, as the module may contain some
names that will interfere with your own variable names.
• For instance: if your program uses a variable called total and you import a module that contains a function called total, there
can be problems. Some modules, however, like tkinter, are fairly safe to import this way.
• The third way imports an entire module in a way that will not interfere with your variable names. To use a function from the
module, preface it with module name followed by a dot.
Importing modules
• The as keyword can be used to change the name that your program uses to refer to a module or things from a module.
Working with files and
directories
56
Working with files and directories
• The os module and the submodule os.path contain functions for working with files and directories.
• If you just want the files and not the subdirectories or vice versa, the os.path module contains the functions isfile and isdir to tell if
an entry is a file or a directory.
• Getting the current directory: The function getcwd returns the path of current directory.
• Getting the files in a directory: The function listdir returns a list of the entries in a directory, including all files and
subdirectories.
Working with files and directories