0% found this document useful (0 votes)
9 views60 pages

Python

Uploaded by

9797kjh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
9 views60 pages

Python

Uploaded by

9797kjh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 60

Lab 1

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.

• Python consistently ranks as one of the most popular


programming languages.

• From the begin with version 0.9.0, now, the most recent version of
Python is 3.12.

• Python have many applications:


• Web Development Guido van Rossum
Distinguished Engineer at
• Software Development
Microsoft
• Scientific Data Analysist
• Machine Learning and Artificial Intelligence
• Desktop GUI
• Business Applications 2
Introduction

• Some useful resource for learning Python:


• Websites:
• Official Python tutorial:
https://docs.python.org/ko/3/tutorial/
• W3 school, concise python tutorial with example:
https://www.w3schools.com/python/
• Tutorial points, like W3 school, but with more information:
https://www.tutorialspoint.com/python/index.htm
• Book:
• A Practical Introduction to Python Programming :
https://www.brianheinold.net/python/python_book.ht
ml
• Hands-On Machine Learning with Scikit-Learn,
Keras, and TensorFlow, 2nd Edition: 3
https://www.oreilly.com/library/view/hands-on-
List of contents

• Install Python • For loops – While loops

• Work with Python on Cheetah • If statements

• Python basic syntax (Printing, Getting • Functions


input)
• Object-Oriented Programming in
• Variables Python

• Numbers • Importing modules

• String, Lists • Working with files and directories

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
• ...

• For simplicity, in this course, I will use an online


sites for coding Python (not require installing,
can restart the environment anytime): Cheetah
Cloud server

7
Getting Started –
Work with Python on
Cheetah

8
Introduction

• A cloud server service for Artificial Intelligence System


• School internal Cheetah cloud server: http://168.131.30.107/
• List of accounts:
• ID: class-01 / PW: Aicoss01*
• ID: class-02 / PW: Aicoss02*
• ID: class-03 / PW: Aicoss03*
• ID: class-04 / PW: Aicoss04*

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

• Spaces matter at the beginning of lines, but not elsewhere.

• 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.

• Anything inside quotes will (with a few exceptions) be printed


exactly as it appears. In the following, the first statement will
output 3+4, while the second will output 7.
Getting input

• 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)

• Read from text files:


variable name = open(file path).read()
Variables

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

• Basic Variable type:


• Integer - 정수 (int): is a whole number (not a fractional number) that can be positive, negative,
or zero.
• Float - 떠있다 (float): is a common data type in computer programming that represents a
number with a decimal point
• String: represents a sequence of characters.
• List: is a sequence data type which is used to store the collection of data.
• Dictionary: is a collection of key: value pair
• You can use str, int, float, and list functions are used to convert one data type into another.
Number

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

• Random number: At this point, there is


only one function, called randint, that we
will need from the random module. To load
this function, we use the following
statement:
• Using randint: randint(a,b) will return a
random integer between a and b including
both a and b. (Note that randint includes
the right endpoint b unlike the range
function).
String, Lists

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

• The "in" operator: The in operator is used to tell if a


string contains something.
• The "not in" operator: You can combine in with the
not operator to tell if a string does not contain
something.
String, List

• Indexing: We will often want to pick out


individual characters from a string. Python uses
square brackets to do this.
String, List

• Slices: A slice is used to pick out part of a string. It


behaves like a combination of indexing and the range
function.
String

• Some String function: Lower, upper case, replace


• lower() : returns a string with every letter of the original in lowercase
• upper() : returns a string with every letter of the original in uppercase
• replace(x, y) : returns a string with every occurrence of x replaced by y
• index(x): returns the location of the first occurrence of x
• One very important note about lower, upper, and replace is that they do not change the original string. If you want to
change a string, to all lowercase, it is not enough to just use string_name.lower().
List

• There are several built-in functions


that operate on lists. Here are some
useful ones:
For/ While loop

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 structure of a for/ while loop is as follows:


for variable name in range( number of times to repeat ):
statements to be repeated
while condition is true:
statements to be repeated

• 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.​

• The Break statement: The break


statement can be used to break out of
a for or while loop before the loop is
finished.
• In many cases the break statement
can help make your code easier to
understand and less clumsy.
IF statements

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

• Elif statement: else + if


• The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon
as one of the conditions evaluates to TRUE.
• Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one
statement, there can be an arbitrary number of elif statements following an if.
Function

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

• Default arguments and keyword arguments: You can


specify a default value for an argument. This makes it
optional, and if the caller decides not to use it, then it
takes the default value.
Functions

• Keyword arguments: A related concept to default arguments is keyword arguments.


• Every time you call this function, you have to remember the correct order of the arguments.
• Fortunately, Python allows you to name the arguments when calling the function. In this case, the order of the arguments does
not matter when you use keyword arguments.
Functions – local
variables and global
variables

• 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 ​

• Creating and deleting files:


• mkdir: create a directory

• rmdir: remove a directory


Working with files and directories ​

• Creating and deleting files:


• Create a file:

• rename: rename a file

• remove: delete a file


Thank you

You might also like