justenoughpython_221218_175001
justenoughpython_221218_175001
CUHK-BME
JUST ENOUGH PYTHON
DR. ALEX NG
alex@gorex.com.hk
How to write your Python code?
1.Jupyter Notebook
2. Script
3. Visual Studio Code
4. PyCharm
5. CoLab
PYTHON BASIC SYNTAX
3
#!/usr/bin/python3
Comments start with #
# first.py
Empty lines are ignored
print ("Hello World! 我是陳大文")
Prints out a line of text
Non-empty line should start at column 1, except in a suite
4
Indentation
• Indenting
– ; is a delimiter not a terminator in Python
– Python statement is terminated by return
– Indenting is to identify a suite
• Python does not use { } to enclose multi-line
statements
• Indentation in the same suite must be exactly
the same
–if and else are two different suites
5
Even though you may use different indentation for a
cluster of suites, you are highly recommended to use
the SAME indentation for the whole cluster.
6
Beware of nested if indentations
7
One more
space here
8
About indentation
• Use SPACE instead of TAB
– As you cannot tell the difference between 8
spaces and tab
– Very difficult to debug as you do not see anything
wrong visually
– Some Python editors will auto-convert tab to
spaces
• Convention is 4 spaces
• Use an editor that will do auto-indentation
9
There are various data types in Python. Some
of the important types are listed below:
10
Data type checking
Output
11
Type conversion
• Integer, Float, Complex computation will do
auto type conversion
• You may explicitly change type by the
functions
int(), float(), complex(), str()
12
1.Numbers Data Type
1.Numbers Data Type 2.List Data Type
3.Tuple Data Type
4.Strings Data Type
Integer, floating-point numbers, and complex 5.Set Data Type
numbers under the category of Python numbers. 6.Dictionary Data Type
Output
13
1.Numbers Data Type
2.List Data Type 2.List Data Type
3.Tuple Data Type
4.Strings Data Type
5.Set Data Type
List data types hold different types 6.Dictionary Data Type
of data. it does not need to be of the
same type. The items stored in the
list are separated with a comma (,)
and enclosed within square brackets
[]
Output
14
List methods
15
16
17
18
19
Other useful operations
20
1.Numbers Data Type
3.Tuple Data Type 2.List Data Type
3.Tuple Data Type
4.Strings Data Type
A tuples data type is alike to list data type. only 5.Set Data Type
6.Dictionary Data Type
one difference, once tuples created can not be
changed/modify.
The items of the tuple are separated with a
comma (,) and enclosed in parentheses ().
Output
21
22
23
24
We cannot change the elements in a tuple. It means that
we cannot delete or remove items from a tuple.
25
Tuple methods
26
1.Numbers Data Type
4.String Data Type 2.List Data Type
3.Tuple Data Type
4.Strings Data Type
A string is a sequence of characters in 5.Set Data Type
6.Dictionary Data Type
Python. In python, Strings are either
enclosed with single quotes, double,
and triple quotes.
Output
27
String Operators
• + on string is concatenation
• You may do * on string
( “ab” * 3 -> “ababab” )
• % on string is the format operator
– (to be covered)
• To remove leading spaces from a string, use
the strip function
endswith( substring[, start[, end]] ) Returns 1 if the string ends with substring. Returns 0
otherwise. If argument start is specified, searching begins
at that index. If argument end is specified, the method
searches through the slice start:end.
expandtabs( [tabsize] ) Returns a new string in which all tabs are replaced by
spaces. Optional argument tabsize specifies the number of
space characters that replace a tab character. The default
value is 8.
29
More strings methods
find( substring[, start[, end]] ) Returns the lowest index at which substring occurs in the
string; returns –1 if the string does not contain substring.
If argument start is specified, searching begins at that
index. If argument end is specified, the method searches
through the slice start:end.
index( substring[, start[, end]] ) Performs the same operation as find, but raises a
ValueError exception if the string does not contain
substring.
isalnum() Returns 1 if the string contains only alphanumeric characters
(i.e., numbers and letters); otherwise, returns 0.
30
join( sequence ) Returns a string that concatenates the strings in sequence using the
original string as the separator between concatenated strings.
replace( old, new[, maximum ] ) Returns a new string in which all occurrences of old in the original
string are replaced with new. Optional argument maximum indicates the
maximum number of replacements to perform.
rfind( substring[, start[, end]] ) Returns the highest index value in which substring occurs in the string
or –1 if the string does not contain substring. If argument start is
specified, searching begins at that index. If argument end is specified,
the method searches the slice start:end.
rindex( substring[, start[, end]] ) Performs the same operation as rfind, but raises a ValueError
exception if the string does not contain substring.
31
split( [separator] ) Returns a list of substrings created by splitting the original string at each
separator. If optional argument separator is omitted or None, the string
is separated by any sequence of whitespace, effectively returning a list of
words.
splitlines( [keepbreaks] ) Returns a list of substrings created by splitting the original string at each
newline character. If optional argument keepbreaks is 1, the substrings in
the returned list retain the newline character.
startswith( substring[, start[, end]] ) Returns 1 if the string starts with substring; otherwise, returns 0. If
argument start is specified, searching begins at that index. If argument
end is specified, the method searches through the slice start:end.
strip() Returns a new string in which all leading and trailing whitespace is
removed.
swapcase() Returns a new string in which uppercase characters are converted to
lowercase characters and lower-case characters are converted to
uppercase characters.
title() Returns a new string in which the first character of each word in the
string is the only uppercase character in the word.
translate( table[, delete ] ) Translates the original string to a new string. The translation is performed
by first deleting any characters in optional argument delete, then by
replacing each character c in the original string with the value table[
ord( c ) ].
32
1.Numbers Data Type
2.List Data Type
Set data types hold unordered 3.Tuple Data Type
collection of unique items. The 4.Strings Data Type
5.Set Data Type
items stored in the set data types 6.Dictionary Data Type
are separated with a comma (,) and
enclosed within square brackets { }.
Output
33
Add elements
34
Delete elements
35
Set Operations - Union
36
Set Operations - Intersection
37
Set Operations - Difference
38
39
1.Numbers Data Type
Dictionary data types is held data in 2.List Data Type
3.Tuple Data Type
key and value pairs. 4.Strings Data Type
5.Set Data Type
A dictionary data type does not 6.Dictionary Data Type
allow duplicate keys in collection.
But the values can be duplicate
Output
40
Changing and Adding Dictionary elements
41
Removing
elements
from Dictionary
42
Iterating Through a Dictionary
43
44
CONTROL FLOW
45
Control flow (if, for, while - only)
• No switch
• No repeat-until
• No do-while
• No label-break
• No label-continue
• No goto
1.If
2.If … else
47
1.If
2.For
3.While
Nested if statements
48
1.If
2.For
3.While
49
1.If
2.For
range() function 3.While
50
1.If
2.For
3.While
51
1.If
2.For
python for loop with else, The ‘else’ block executes 3.While
only when the loop has completed all the
iterations.
52
1.If
Python while Loop 2.For
3.While
53
While with a break
# Using the break statement to drop out of a loop
total = 0 # sum of grades
gradeCounter = 0 # number of grades entered
A forever loop
while True:
grade = input( "Enter grade, -1 to end: " )
grade = int( grade )
# exit loop if user inputs -1 If the user enters –1
if grade == -1: then the loop ends
break
total += grade
gradeCounter += 1
# termination phase
if gradeCounter != 0:
average = total / gradeCounter
print ("Class average is", average)
else:
print ("No grades were entered“) 54
Continue will skip rest of the loop
• 1 # continue example
• 2 # Using the continue statement in a for/in structure.
• 3
• 4 for x in range( 1, 11 ):
• 5 The loop will continue if the
• 6 if x == 5: value equals 5
• 7 continue
• 8 The value 5 will never be
output but all the others will
• 9 print (x, end=" " )
• 10
• 11 print ( "\nUsed continue to skip printing the value 5")
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
55
Mini-while.py
Mini-Exercise
lst=[10, 99, 98, 85, 45, 59, 65, 66, 76, 12, 35, 13, 100, 80,
95]
56
OPERATORS
57
1. Arithmetic
2.Comparison
3.Logical
58
1. Arithmetic
Modulus % 2.Comparison
3.Logical
Division /
Exponentiation **
59
1. Arithmetic
2.Comparison
3.Logical
60
1. Arithmetic
2.Comparison
Python has three logical 3.Logical
operators:
- and
- or
- not
61
FUNCTIONS
62
1.Simple function
2.With arguments
3.With multiple arguments
4.With default arguments
5.Return a value
6.Return multiple values
What is a function
A function is a named code block that performs a job
or returns a value.
Simple Function (no arguments/no return values)
def my_func():
print("Hello! Hope you're doing well")
my_func()
# Output
Hello! Hope you're doing well
63
1.Simple function
Function with arguments 2.With arguments
3.With multiple arguments
4.With default arguments
1. positional arguments 5.Return a value
6.Return multiple values
def my_func(name,place):
print(f"Hello {name}! Are you from {place}?")
my_func("Jane","Paris")
# Output
Hello Jane! Are you from Paris?
2. keyword arguments
my_func(place="Hawaii",name="Robert")
# Output
Hello Robert! Are you from Hawaii?
64
1.Simple function
Function that Returns a Value 2.With arguments
3.With multiple arguments
4.With default arguments
5.Return a value
6.Return multiple values
def volume_of_cuboid(length,breadth,height):
return length*breadth*height
volume = volume_of_cuboid(5.5,20,6)
print(f"Volume of the cuboid is {volume} cubic units")
# Output
Volume of the cuboid is 660.0 cubic units
65
1.Simple function
2.With arguments
Function that Returns Multiple Values 3.With multiple arguments
4.With default arguments
5.Return a value
def cube(side): 6.Return multiple values
volume = side **3
surface_area = 6 * (side**2)
return volume, surface_area
returned_values = cube(8)
print(returned_values)
# Output
(512, 384)
unpack the tuple and store the values in two different variables.
volume, area = cube(6.5)
print(f"Volume of the cube is {volume} cubic units and the total surface
area is {area} sq. units")
# Outputs
Volume of the cube is 274.625 cubic units and the total surface area is
253.5 sq. units 66
What is a module?
If you create a single Python file to perform some tasks, that’s called a script.
If you create a Python file to store functions, classes, and other definitions,
that’s called a module. We use modules by importing from them, using the
Python import statement.
Import a module
Module function
Specific function
Short form
67
Why do you need Python modules?
68
pricing.py
main.py
69
1.alias
70
3.rename a specific function
4.import everything
71
What will happen? What is the result? 72
OS module in python
• You may perform ALL OS functions using Python
(like start a program, kill a program, find the
environment variables, etc) in
Linux/Unix/MacOSx
• However, MOST of the OS module functions
DOES NOT work on Microsoft Windows
• Reason: Python make calls to POSIX like
functions and MS windows is NOT POSIX
compatible
• However, some file OS functions like
renaming files, deleting files may work on MS
Windows
73
OS functions that SHOULD work on
Microsoft
• os.rename
• os.remove (which is alias of os.unlink)
• os.mkdir
• os.chdir
• os.getcwd
• os.rmdir
74
OS File functions Expect Linux file system.
os.access(path, mode) os.chdir(path) os.chflags(path, flags)
os.chmod(path, mode) os.chown(path, uid, gid) os.chroot(path)
os.close(fd) os.closerange(fd_low, fd_high) os.dup(fd) os.dup2(fd, fd2)
os.fchdir(fd) os.fchmod(fd, mode) os.fchown(fd, uid, gid) os.fdatasync(fd)
os.fdopen(fd[, mode[, bufsize]]) os.fpathconf(fd, name) os.fstat(fd)
os.fstatvfs(fd) os.fstatvfs(fd) os.ftruncate(fd, length) os.getcwd()
os.getcwdu() os.isatty(fd) os.lchflags(path, flags) os.lchmod(path, mode)
os.lchown(path, uid, gid) os.link(src, dst) os.listdir(path)
os.lseek(fd, pos, how) os.lstat(path) os.major(device) os.major(device)
os.makedirs(path[, mode]) os.minor(device) os.mkdir(path[, mode])
os.mkfifo(path[, mode]) os.mknod(filename[, mode=0600, device])
os.open(file, flags[, mode]) os.openpty() os.pathconf(path, name)
os.pipe() os.popen(command[, mode[, bufsize]]) os.read(fd, n)
os.readlink(path) os.remove(path) os.removedirs(path)
os.rename(src, dst) os.renames(old, new) os.rmdir(path) os.stat(path)
os.stat_float_times([newvalue]) os.statvfs(path) os.symlink(src, dst)
os.tcgetpgrp(fd) os.tcsetpgrp(fd, pg) os.tempnam([dir[, prefix]])
os.tmpfile() os.tmpnam() os.ttyname(fd) os.unlink(path)
os.utime(path, times)
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
os.write(fd, str) Read python manual for details
75
EXCEPTION HANDLING
76
Because the program abruptly terminates on
encountering an exception, it may cause
damage to system resources, such as files.
Hence, the exceptions should be properly
handled so that an abrupt termination of the
program is prevented.
77
78
You can specify the error type
79
80
81
Case1
Case2
82
Case3
83
Raise an Exception
It causes an exception to be generated explicitly.
84
Exception
• Cannot print an error message in an object’s
method, otherwise it may corrupt the display
• Need some way to tell the caller something
go wrong
• Exception
– special event during program execution
• Python creates traceback objects when it
encounters exceptions
85
86
87
Python Exception Hierarchy
Python exceptions
Exception
SystemExit
StopIteration
StandardError
KeyboardInterrupt
ImportError
EnvironmentError
IOError
OSError
WindowsError (Note: Defined on Windows platforms only)
EOFError
RuntimeError
NotImplementedError
NameError
UnboundLocalError
AttributeError
SyntaxError
IndentationError
TabError
TypeError
AssertionError
88
Python Exception Hierarchy
LookupError
IndexError
KeyError
ArithmeticError
OverflowError
ZeroDivisionError
FloatingPointError
ValueError
UnicodeError
ReferenceError
SystemError
MemoryError
Warning
UserWarning
DeprecationWarning
SyntaxWarning
OverflowWarning
RuntimeWarning
89
FILE IO
90
Files
1.Open a file
2.Read or write (perform operation)
3.Close the file
91
92
Closing Files
93
94
Readline()
95
Writing to Files
96
File Open Mode
Mode Description
"a" Writes all output to the end of the file. If the
indicated file does not exist, it is created.
"r" Opens a file for input. If the file does not exist, an
IOError exception is raised.
"r+" Opens a file for input and output. If the file does
not exist, causes an IOError exception.
"w" Opens a file for output. If the file exists, it is
truncated. If the file does not exist, one is created.
"w+" Opens a file for input and output. If the file exists,
it is truncated. If the file does not exist, one is
created.
"ab", Opens a file for binary (i.e., non-text) input or
"rb", output. [Note: These modes are supported only on
"r+b", the Windows and Macintosh platforms.]
"wb",
"w+b"
File-open modes.
97
File Object Methods
Method Description
close() Closes the file object.
fileno() Returns an integer that is the file’s file descriptor (i.e., the
number the operating system uses to maintain information about
the file).
flush() Flushes the file’s buffer. A buffer contains the information to
be written to or read from a file. Flushing the buffer performs the
read or write operation.
98
More methods
Method Description
tell() Returns the file’s current position.
truncate( [size] ) Truncates data in the file. If size is not specified, all data is deleted. If size
is specified, the file is truncated to contain at most size bytes.
99
1.Numbers Data Type 1.If 1.Simple function
2.List Data Type 2.For 2.With arguments
3.Tuple Data Type 3.While 3.With multiple arguments
4.Strings Data Type 4.With default arguments
5.Set Data Type 5.Return a value
6.Dictionary Data 6.Return multiple values
Type
1. Arithmetic 1.Module
2.Comparison 2.Exception
3.Logical 3.File IO
100