0% found this document useful (0 votes)
32 views65 pages

Introduction To Python

Debugging is the process of finding and fixing errors in software code. When programs do not work as expected, programmers use debugging tools to methodically check the code line-by-line to analyze and resolve issues. Debugging helps improve software quality and the user experience by enabling faster fixing of problems. The typical debugging process involves identifying errors, analyzing their cause, and validating a fix while ensuring the issue does not recur.

Uploaded by

voduykhoa2504
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)
32 views65 pages

Introduction To Python

Debugging is the process of finding and fixing errors in software code. When programs do not work as expected, programmers use debugging tools to methodically check the code line-by-line to analyze and resolve issues. Debugging helps improve software quality and the user experience by enabling faster fixing of problems. The typical debugging process involves identifying errors, analyzing their cause, and validating a fix while ensuring the issue does not recur.

Uploaded by

voduykhoa2504
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/ 65

DEBUGGING

• Debugging is the process of finding and fixing errors or bugs in the


source code of any software.
• When software does not work as expected, computer programmers
study the code to determine why any errors occurred.
• They use debugging tools to run the software in a controlled
environment, check the code step by step, and analyze and fix the
issue.

Source: https://aws.amazon.com/what-is/debugging/?nc1=h_ls

12/14/2023 Introduction to Programming 1


WHY IS DEBUGGING IMPORTANT?
• Bugs and errors happen in computer programming because it is an abstract and
conceptual activity.
• Computers manipulate data in the form of electronic signals.
• Programming languages abstract this information so humans can interact with
computers more efficiently.
• Any type of software has several layers of abstraction, with different
components communicating for an application to work correctly.
• When errors occur, finding and resolving the issue can be challenging.
• Debugging tools and strategies help to fix problems faster and improve
developer productivity.
•Source:
As https://aws.amazon.com/what-is/debugging/?nc1=h_ls
a result, both software quality and the end-user experience improve.
12/14/2023 Introduction to Programming 2
HOW DOES THE DEBUGGING PROCESS
WORK?
• The debugging process typically requires the following steps.
1. Error identification: Developers, testers, and end-users report bugs they
discover while testing or using the software. Developers locate the exact line
of codes or code module causing the bug. This can be a tedious and time-
consuming process.
2. Error analysis: Coders analyze the error by recording all program state
changes and data values. They also prioritize the bug fix based on its impact
on software functionality. The software team also identifies a timeline for bug
fixing depending on development goals and requirements.
3. Fix and validation: Developers fix the bug and run tests to ensure the
software continues to work as expected. They may write new tests to check if
Source:the bug recurs in the future.
https://aws.amazon.com/what-is/debugging/?nc1=h_ls

12/14/2023 Introduction to Programming 3


PROGRAMING BASICS
• code or source code: The sequence of instructions in a program.
• syntax: The set of legal structures and commands that can be used in
a particular programming language.
• output: The messages printed to the user by a program.
• console: The text box onto which output is printed.
• Some source code editors pop up the console as an external window, and
others contain their own console window.

12/14/2023 Introduction to Programming 4


COMPILING AND INTERPRETING
• Many languages require you to compile (translate) your program into
a form that the machine understands.

• Python is instead directly interpreted into machine instructions.

12/14/2023 Introduction to Programming 5


INTEPRETER AND COMPILER

Source: https://www.tutorialsmate.com/2020/08/difference-between-compiler-and-interpreter.html
12/14/2023 Introduction to Programming 6
OBJECTS
• Programs manipulate data objects
• Objects have a type that defines the kinds of things programs can do
to them
• Ana is a human so she can walk, speak English, etc.
• Chewbacca is a wookie so he can walk, “mwaaarhrhh”, etc.
• objects are
• scalar (cannot be subdivided)
• non-scalar (have internal structure that can be accessed)

12/14/2023 Introduction to Programming 7


PROGRAMMING ENVIRONMENT
• A Programming Environment is the collection of tools used in the
development of software.
• In a general sense, a programming environment combines hardware
and software that allows a developer to build applications.
• Developers typically work in integrated development environments or
IDEs.
• These connect users with all the features necessary to write and test their
code correctly. Different IDEs will offer other capabilities and advantages.

Source: https://www.linkedin.com/pulse/chapter-1-programming-environment-parth-dobariya/
12/14/2023 Introduction to Programming 8
Introduction to Python
Lecturer: Vũ Đức Lý (Ph.D)

12/14/2023 Introduction to Programming with Python 9


WHAT IS PYTHON?
“Python is a high-level programming language, and its core design
philosophy is all about code readability and a syntax which allows
programmers to express concepts in a few lines of code.”
Designed by Guido van Rossum

12/14/2023 Introduction to Programming with Python 10


12/14/2023 Introduction to Programming with Python 11
PYTHON ADVANTAGES
• Readable: Intuitive and strict syntax
• Productive: saves a lot of code.
• Portable: For every operating system.
• Reloaded: It comes with many libraries.

12/14/2023 Introduction to Programming with Python 12


PYTHON DISADVANTAGES
• Speed: Python code is executed line by line, which causes it to slow
down.
• Memory Consumption: Python’s memory consumption is also high,
due to the flexibility of the data types.
• Runtime Errors: Errors only show up at runtime this is because the
language is dynamically typed.

12/14/2023 Introduction to Programming with Python 13


IS PYTHON EASY TO LEARN?
• Python is the easiest language, that is why Python is taught to
university students- to create interest in programming.
• Python is:
• Easy to learn- it has a smooth learning curve
• Easy to read- it is easy to read, understand, code
• Easy to write- Python’s syntax is like English language
• Easy to debug- it gives you full tracebacks

12/14/2023 Introduction to Programming with Python 14


WHAT IS PYTHON USED FOR?
• Web Development • ​Web Scraping
• Frameworks such as Django, Flask • Libraries such as Scrapy,
BeautifulSoup
• Data Analysis
• Libraries such as NumPy and • Computer Vision
Pandas • OpenCV library
• Data visualisation libraries like • Machine Learning
Matplotlib and Seaborn
• Libraries such as Scikit-Learn, NLTK
• Internet Of Things and TensorFlow.
• Raspberry Pi + Python • Game Development
• PyGame

12/14/2023 Introduction to Programming with Python 15


PYTHON PROGRAMS
• a program is a sequence of definitions and commands
• definitions evaluated
• commands executed by Python interpreter in a shell
• commands (statements) instruct interpreter to do something
• can be typed directly in a shell or stored in a file that is read into the
shell and evaluated
• I will give you a demo

12/14/2023 Introduction to Programming with Python 16


PYTHON REPL
• The Python standard shell, or REPL (Read-Eval-Print Loop), allows you
to run Python code interactively while working on a project or
learning the language.
• Available in every Python installation, so you can use it at any
moment.
• Allows you to test new ideas, explore and experiment with new tools
and libraries, refactor and debug your code, and try out examples.

12/14/2023 Introduction to Programming with Python 17


SETUP YOUR PROGRAMMING
ENVIRONMENT
• Choose an platform you want to program on (Linux or Windows or
Web)
• Choose an editor (Vim or Notepad)
• Install Python on the chosen OS
• You can also choose an IDE, for example Visual Studio Code

12/14/2023 Introduction to Programming with Python 18


SCALAR OBJECTS
• int – represent integers, ex. 5
• float – represent real numbers, ex. 3.27
• bool – represent Boolean values True and False
• NoneType – special and has one value, None
• can use type() to see the type of an object

12/14/2023 Introduction to Programming with Python 19


TYPE CONVERSIONS (CAST)
• can convert object of one type to another
• float(3) converts integer 3 to float 3.0
• int(3.9) truncates float 3.9 to integer 3

12/14/2023 Introduction to Programming with Python 20


PRINTING TO CONSOLE
• to show output from code to a user, use print command

12/14/2023 Introduction to Programming with Python 21


EXPRESSIONS
• combine objects and operators to form expressions
• an expression has a value, which has a type
• syntax for a simple expression
<object> <operator> <object>

12/14/2023 Introduction to Programming with Python 22


Source: https://slideplayer.com/slide/12755081/
12/14/2023 Introduction to Programming with Python 23
OPERATORS ON ints AND floats
• i+j  the sum
If both are ints, result is int
• i-j  the difference If either or both are floats, result is float
• i*j  the product
• i/j  division result is float

• i%j  the remainder when i is divided by j


• i**j  i to the power of j

12/14/2023 Introduction to Programming with Python 24


SIMPLE OPERATIONS
• parentheses used to tell Python to do these operations first
• operator precedence without parentheses
• **
• *
• /
• + and – executed left to right, as appear in expression

12/14/2023 Introduction to Programming with Python 25


BINDING VARIABLES AND VALUES
• equal sign is an assignment of a value to a variable name

• value stored in computer memory


• an assignment binds name to value
• retrieve value associated with name or variable by invoking the name,
by typing pi
12/14/2023 Introduction to Programming with Python 26
ABSTRACTING EXPRESSIONS
• Why give names to values of expressions?
• To reuse names instead of values
• Easier to change code later

12/14/2023 Introduction to Programming with Python 27


PROGRAMMING vs MATH
• In programming, you do not “solve for x”

12/14/2023 Introduction to Programming with Python 28


CHANGING BINDINGS
• can re-bind variable names using new assignment statements
• previous value may still stored in memory but lost the handle for it
• value for area does not change until you tell the computer to do the
calculation again

12/14/2023 Introduction to Programming with Python 29


STRINGS
• think of as a sequence of case sensitive characters
• letters, special characters, spaces, digits

12/14/2023 Introduction to Programming with Python 30


STRINGS
• Think of as a sequence of case sensitive characters
• letters, special characters, spaces, digits
• enclose in quotation marks or single quotes
hi = “hello there”
• concatenate strings
• name = “ana”
• greet = hi + name
• greeting = hi + “ “ + name
• do some operations on a string as defined in Python docs
silly = hi + “ ” + name * 3
• can compare strings with ==, >, < etc.
12/14/2023 Introduction to Programming with Python 31
COMPARISON OPERATORS ON int, float,
string
• i and j are variable names
• comparisons below evaluate to a Boolean
i>j
i >= j
i<j
i <= j
i == j  equality test, True if i is the same as j
i != j  inequality test, True if i not the same as j

12/14/2023 Introduction to Programming with Python 32


LOGIC OPERATORS ON bools
• a and b are variable names (with Boolean values)
• not a  True if a is False
False if a is True
• a and b  True if both are True
• a or b  True if either or both are True
A B A and B A or B
True True True True
True False False True
False True False True
False False False False

12/14/2023 Introduction to Programming with Python 33


COMPARISON EXAMPLE
pset_time = 15
sleep_time = 8
print(sleep_time > pset_time)
derive = True
drink = False
both = drink and
derive print(both)

12/14/2023 Introduction to Programming with Python 34


12/14/2023 Introduction to Programming with Python 35
CONTROL FLOW - BRANCHING

• <condition> has a value True or False


• evaluate expressions in that block if <condition> is True
12/14/2023 Introduction to Programming with Python 36
BLOCK OF CODE
• A block is a combination of all these statements.
• Block can be regarded as the grouping of statements for a specific
purpose.
• Most programming languages like C, C++, and Java use braces { } to
define a block of code.

12/14/2023 Introduction to Programming with Python 37


PYTHON INDENTATION
• Python indentation is a way of telling a Python interpreter that the
group of statements belongs to a particular block of code.
• Python uses indentation to highlight the blocks of code.
• Whitespace is used for indentation in Python.
• All statements with the same distance to the right belong to the same
block of code.
• If a block has to be more deeply nested, it is simply indented further
to the right.

12/14/2023 Introduction to Programming with Python 38


Tabs: Pros and Cons
• Tabs are a special character that represents a fixed amount of space,
usually equivalent to four or eight spaces.
• Using tabs for indentation can provide advantages such as saving
space, allowing for adjustability, and increasing accessibility.
• However, tabs also have some drawbacks, such as inconsistency and
compatibility issues when working with certain languages or
frameworks.
• Tabs can cause confusion when mixed with spaces, and some parsers
or compilers may interpret tabs differently than spaces.

12/14/2023 Introduction to Programming with Python 39


Spaces: Pros and Cons
• Tmost common way of creating indentation, by inserting a certain number of
space characters at the beginning of each line of code.
• Using spaces for indentation has some advantages, such as consistency and
compatibility with languages and frameworks that rely on indentation for syntax.
• Spaces can also cause problems, such as wasting space and being too rigid, as they
do not allow different programmers to adjust the indentation level according to
their preferences.
• spaces take up more space than tabs in the file, which can increase the file size and
affect performance
• spaces also require more keystrokes to insert or delete, which can be tedious and
time-consuming.

12/14/2023 Introduction to Programming with Python 40


TABS OR WHITESPACES
• Python uses 4 spaces as indentation by default. However, the number
of spaces is up to you, but a minimum of 1 space has to be used.
• Tabs should be used solely to remain consistent with code that is
already indented with tabs.
• A tab is stored differently than spaces in the code. Tabs can be seen as
a big “jump” in the text, while spaces are always 1 space each.
• Python disallows mixing tabs and spaces for indentation.

12/14/2023 Introduction to Programming with Python 41


PYTHON INDENTATION (CONT)
• Matters in Python
• How you denote blocks of code

12/14/2023 Introduction to Programming with Python 42


= vs ==

12/14/2023 Introduction to Programming with Python 43


CONTROL FLOW: while LOOPS
• In Python, a 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.
• All the statements indented by the same number of character spaces
after a programming construct are considered to be part of a single
block of code.
• Python uses indentation as its method of grouping statements.

12/14/2023 Introduction to Programming with Python 44


CONTROL FLOW: while LOOPS SYNTAX

• <condition> evaluates to a Boolean


• check <condition> again
• repeat until <condition> is False

12/14/2023 Introduction to Programming with Python 45


while LOOP EXAMPLE

12/14/2023 Introduction to Programming with Python 46


CONTROL FLOW: while and for LOOPS
• iterate through numbers in a sequence

12/14/2023 Introduction to Programming with Python 47


USING ELSE STATEMENT WITH while
LOOP
• The else clause is only executed when your while condition becomes
false.
• If you break out of the loop, or if an exception is raised, it won’t be
executed.
• Syntax of While Loop with else statement:

12/14/2023 Introduction to Programming with Python 48


USING ELSE STATEMENT WITH while
LOOP (CONT)
# Python program to illustrate
# combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello VGU")
else:
print("In Else Block")

12/14/2023 Introduction to Programming with Python 49


Infinite While Loop in Python
• If we want a block of code to execute infinite number of time, we can use the while
loop in Python to do so.
• Note: It is suggested not to use this type of loop as it is a never-ending infinite loop where the
condition is always true and you have to forcefully terminate the compiler.

# Python program to illustrate


# Single statement while block
count = 0
while (count == 0):
print("Hello VGU")

12/14/2023 Introduction to Programming with Python 50


CONTROL FLOW: for LOOPS
• For loops are used for sequential traversal. For example: traversing a
list or string or array etc.
• In Python, there is “for in” loop which is similar to for each loop in
other languages.

12/14/2023 Introduction to Programming with Python 51


CONTROL FLOW: for LOOPS

• each time through the loop, <variable> takes a value


• first time, <variable> starts at the smallest value
• next time, <variable> gets the prev value + 1
• etc.

12/14/2023 Introduction to Programming with Python 52


range(start,stop,step)
• default values are start = 0 and step = 1 and optional
• loop until value is stop - 1

12/14/2023 Introduction to Programming with Python 53


LOOPING THROUGH A STRING
• Even strings are iterable objects, they contain a
sequence of characters:
• Loop through the letters in the word “vgu":
for x in "vgu":
print(x)

12/14/2023 Introduction to Programming with Python 54


Loop Control Statements
• Loop control statements change execution from their normal
sequence.
• When execution leaves a scope, all automatic objects that were
created in that scope are destroyed.
• Python supports the following control statements.
• continue
• break
• pass

12/14/2023 Introduction to Programming with Python 55


Continue Statement
• the continue statement in Python returns the control to the beginning
of the loop.
# Prints all letters except 'v' and 'n'
for letter in 'vgu.edu.vn':
if letter == 'v' or letter == 'n':
continue
print('Current Letter :', letter)

12/14/2023 Introduction to Programming with Python 56


break STATEMENT
• immediately exits whatever loop it is in
• skips remaining expressions in code block
• exits only innermost loop!

12/14/2023 Introduction to Programming with Python 57


break STATEMENT

• what happens in this program?

12/14/2023 Introduction to Programming with Python 58


Pass Statement
• We use pass statement in Python to write empty loops. Pass is also
used for empty control statements, functions and classes.
# An empty loop
for letter in 'vgu.edu.vn':
pass
print('Last Letter :', letter)

12/14/2023 Introduction to Programming with Python 59


for VS while LOOPS

for loops while loops


• know number of iterations • unbounded number of iterations
• can end early via break • can end early via break
• uses a counter • can use a counter but must
• can rewrite a for loop using a initialize before loop and
while loop increment it inside loop
• may not be able to rewrite a
while loop using a for loop

12/14/2023 Introduction to Programming with Python 60


LIST COMPREHENSION
• List comprehension offers a shorter syntax when you want to create a
new list based on the values of an existing list.

12/14/2023 Introduction to Programming with Python 61


WITHOUT LIST COMPREHENSION
fruits = ["apple", "banana", "cherry", "kiwi",
"mango"]
newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

12/14/2023 Introduction to Programming with Python 62


WITH LIST COMPREHENSION
fruits = ["apple", "banana", "cherry", "kiwi",
"mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

12/14/2023 Introduction to Programming with Python 63


LIST COMPREHENSION SYNTAX
• newlist = [expression for item in iterable if condition == True]
• The return value is a new list, leaving the old list
unchanged.

12/14/2023 Introduction to Programming with Python 64


References
• https://sites.google.com/view/learn-python-data-science/home
• https://realpython.com/python-repl/

12/14/2023 Introduction to Programming with Python 65

You might also like