Introduction to Python Programming
Introduction to Python Programming
Python
What
What
• Programming language
• Open-source
• Interpreted
• High-level
• General-purpose
• Code readability
• Object Oriented Programming
What
What
Source
Why
• Easy
• Flexible
• Readability
• Projects
• Jobs
Why: Easy
• Syntax
• Natural
• Intuitive
• Python:
print("Hello world.")
• Java:
public class Test {
public static void main(String args[]) {
[Link]("Hello world.");
}
}
Why: Flexible
• Script
• Backend
• Machine Learning, Deep Learning
• Apps
• Mobile
• Desktop
• Web
Why: Readability
• Indents ftw!
• Line breaks ftw!
Why: Projects
• Full list
• Browser
• Youtube-dl
• Music Player
• Video Editor
• Bittorent client
• Text Editor
Why: Jobs!1!!
Why: Jobs!1!!
Why: Jobs!1!!
Why: Jobs!1!!
Why
Why NOT?
Get started
Python
• Python
• Python 2.x: discontinued
• Python 3.x
• Download
• conda:
• isolate environments
• install packages
• miniconda: minimal installer for conda
• anaconda: miniconda + bunch of pre-installed packages
IDE
• Full fledged IDEs
• PyCharm
• Visual Studio Code
Jupyter Notebook
• Written in Python
• Fork of IPython
• Open-source Web app
• live code
• equations
• Computational output - visualizations
• explanatory text
Jupyter Notebook
• Main components
• IPython
• ØMQ
• Tornado (web server)
• jQuery
• Bootstrap (front-end framework)
• MathJax
Jupyter Notebook
• Install
• pip
Expressions
Interactive vs Script
• Interactive
• Type command
• Execute
• Wait for response
• Script
• All-in-one long sequences of statements
• python [Link]
• Shebang #! works
Constants
• What
• Fixed values
• Value does not change over time
• Examples
• Numeric constants
• String constants
• Single quotes '
• Double quotes "
• Why: everywhere
Constants
• How
>>> print(123)
123
>>> print(98.6)
98.6
>>> print('Hello world')
Hello world
Variables
• What
• Named place in the memory to store data
• Access it later using name
• Modifiable at runtime
Variables
• Examples
• Good: spam, eggs, spam23, _speed
• Bad: 23spam, #sign, var.12
• Different: spam, Spam, SPAM
Variables
• Reserved words
and del for is raise assert elif
from lambda return break else
global not try class except if or while
continue exec import pass
yield def finally in print
Statements
• Numeric expression
• + Addition
• - Subtraction
• * Multiplication
• / Division
• ** Power
• % Remainder
Statements
• Numeric expression
>>> x = 2
>>> x = x + 2
>>> print(x) >>> j = 23
4 >>> k = j % 5
>>> y = 440 * 12 >>> print(k)
>>> print(y) 3
5280 >>> print(4 ** 3)
>>> z = y / 1000 64
>>> print(z)
5
Statements
Data Types
What
Type Examples
Integer 0, 12, 5, -5
Float 4.5, 3.99, 0.1
String “Hi”, “Hello”, “Hi there!”"
Boolean True, False
List [ “hi”, “there”, “you” ]
Tuple (4, 2, 7, 3)
What: Boolean
• bool
• 2 possible values: True, False
What: Integer
• int
• Unbounded.
>>> i=10**100
>>> type(i)
<class 'int'>
>>> i
1000000000000000000000000000000000000000000000000000000
What: Float
• float
• Digits and Exponents
>>> 2.5
>>> 2e4
>>> 0.00001
>>> 1000020000300004
What: Strings
• str
• Series of Unicode characters
• Character: String of length 1
• Enclosed by a pair of single or double quotes
• Multiline: triple quote
• '''
• """
>>> s="""This is
... a Multiline string
... for example"""
>>> s
'This is \na Multiline string \nfor example'
The Python Language Tran Giang Son, [Link]@[Link] 17 / 66
Expressions Data Types Conditions Functions Collections Loops Practice!
Dynamically typing
Number Conversion
Number Conversion
>>> sval = '123'
>>> type(sval)
<class 'str'>
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module
TypeError: can only concatenate str
• Also works with >>> ival = int(sval)
>>> type(ival)
strings!
<class 'int'>
>>> print(ival + 1)
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "<stdin>", line 1, in <module
The Python Language ValueError: invalid literal for
Tran Giang Son, [Link]@[Link] 20 /int(
66
Expressions Data Types Conditions Functions Collections Loops Practice!
String Operators
String Operators
• Substring: string[index:end:step]
• index, end
• >=0: start from beginning of string
• <: start from end of string
• Can be omitted
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 |
+---+---+---+---+---+---+
|-6 |-5 |-4 |-3 |-2 |-1 |
+---+---+---+---+---+---+
• step: How many letters to skip
The Python Language Tran Giang Son, [Link]@[Link] 22 / 66
Expressions Data Types Conditions Functions Collections Loops Practice!
String Operators
• string[index:end:step]
>>> s = "Advanced Programming with Python"
>>> s[:20]
>>> s[9] 'Advanced Programming'
'P' >>> s[9:]
>>> s[9:20] 'Programming with Python'
'Programming' >>> s[-6:-4]
>>> s[9:20:2] 'Py'
'Pormig' >>> s[-6:]
'Python'
String Formats
Comments
Comments
>>> s = "USTH"
>>> # print("nobody cares")
>>> print(s)
USTH
Conditions
Indentation Rules
• Increase indent after an if statement or for statement (after :
)
• Equivalent to C, Java’s {
Indentation Rules
if - else
x = 5
if x < 10:
print('Smaller than 10')
else:
print('Bigger than 10')
print('End')
Nested if - else
x = 5
if x < 10:
print('Smaller than 10')
if x > 5:
print(' Still bigger than 5')
else:
print('Bigger than 10')
print('End')
if - else - if - else
x = 21
if x < 10:
print('Smaller than 10')
elif x < 20:
print('Smaller than 20')
else:
print('Bigger than 20')
print('End')
Functions
How
• Definition
• Function Name
• Parentheses
• Arguments
def function_name(arguments):
"""docstring"""
statement1
statement2
...
• Call
function_name("a value")
Examples
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet("Emmanuel Macron")
Examples
Collections
What
Set
Sequences
• Ordered collection of items
• Can have duplications
• Positioned access
• Slicing similar to strings
• seq[start:end:step]
• Implementations
• list
• tuple
• range
• Others:
• str
•
The Python Language Tran Giang Son, [Link]@[Link] 41 / 66
Expressions Data Types Conditions Functions Collections Loops Practice!
Lists
• Mutable sequence
• Values can be changed later
Lists
Lists
Lists
Lists
>>> names
['ICT', 'I See Tea', 'Ict']
Lists
>>> names
['ICT', 'I See Tea', 'Ict']
• = replaces bunch of values
>>> names[1:3] = [ "Icy Tea", "I See Tea" ]
>>> names
['ICT', 'Icy Tea', 'I See Tea']
Lists
>>> names
['ICT', 'I See Tea', 'Ict']
• = replaces bunch of values
>>> names[1:3] = [ "Icy Tea", "I See Tea" ]
>>> names
['ICT', 'Icy Tea', 'I See Tea']
• += append elements at middle, same as .insert()
>>> names[1:1] += [ "Ice City" ]
>>> names
['ICT', 'Ice City', 'Icy Tea', 'I See Tea']
Lists
>>> names
['ICT', 'Ice City', 'Icy Tea', 'I See Tea']
Lists
>>> names
['ICT', 'Ice City', 'Icy Tea', 'I See Tea']
• sort() elements
>>> [Link]()
>>> names
['I See Tea', 'ICT', 'Ice City', 'Icy Tea']
Lists
>>> names
['ICT', 'Ice City', 'Icy Tea', 'I See Tea']
• sort() elements
>>> [Link]()
>>> names
['I See Tea', 'ICT', 'Ice City', 'Icy Tea']
• del delete elements
>>> del names[1]
>>> names
['I See Tea', 'Ice City', 'Icy Tea']
Lists
>>> names
['I See Tea', 'Ice City', 'Icy Tea']
Lists
>>> names
['I See Tea', 'Ice City', 'Icy Tea']
• .remove() occurrences
>>> [Link]("Icy Tea")
>>> names
['Ice City', 'I See Tea']
Range
Range
Tuples
• Immutable sequence
• Contain any type of element.
• A very common use of tuples is a simple representation of
pairs
• Positition (x, y)
• Size (w, h)
• ...
Tuples
Maps
• Key/value pairs
• Key must be unique
• Similar to JSON objects
• Unordered, mutable
• Implemented by dict
Maps
• Initialization
info = {"name": "USTH", "age": 10, \
"depts": [ "ict", "ged"] }
• Key operations
• in, not in: check key presence
>>> max(info)
'name'
Maps: Operations
>>> info["name"]
'USTH'
• Value operations >>> info["age"] = 11
• d[k]: get value by key >>> info["age"]
• d[k] = v: set value to
11
key
• del d[k] remove key >>> del info["depts"]
from dict >>> info
>>> info
{'name': 'USTH', 'age': 11}
Maps: Methods
Maps: Methods
>>> info = {"name": "USTH", "age": 10, \
"depts": [ "ict", "ged"] }
>>> [Link]("name")
'USTH'
>>> [Link]("address", "Earth")
'Earth'
>>> [Link]("depts")
['ict', 'ged']
>>> [Link]()
dict_keys(['name', 'age'])
>>> [Link]()
dict_values(['USTH', 10])
>>> [Link]()
dict_items([('name', 'USTH'), ('age', 10)])
Loops
What
What
5
n = 5
4
while n > 0 :
3
print(n)
2
n = n – 1
1
print('Blastoff!')
Blastoff!
break
continue
range()
x = range(5)
print(x)
[0, 1, 2, 3, 4]
• range()
• built-in function
• returns sequence of x = range(3, 7)
numbers in a range print(x)
• Very useful in “for” loops [3, 4, 5, 6]
• 1, 2, or 3 arguments
x = range(10, 1, -2)
print(x)
[10, 8, 6, 4, 2]
range()
• for statement
• Iterates over the members of a sequence in order
• Executes the block each time
for i in <collection>
<loop body>
• Examples
n = 5
while n > 0: for n in range(5, 0, -1):
print(n) print(n)
n = n – 1 print('Blastoff!')
print('Blastoff!')
Practice!
• Listing functions:
• List courses
• List students
• Show student marks for a given course
OOP in Python
Review
Questions!?!!!1
1
Or exam?!
OOP in Python Tran Giang Son, [Link]@[Link] 3 / 34
Review Object and Class Inheritance Polymorphism Encapsulation
Questions!?!!!
Questions!?!!!
Questions!?!!!
• What is inheritance?
• What is an inheritance hierarchy?
• What is a subclass? A superclass?
• What are the advantages of using inheritance?
• What is the difference between an is-a and a has-a
relationships?
Questions!?!!!
• What is polymorphism?
• What are overriding and overloading? Are they the same?
Give examples.
• What does the keyword super mean? When is it used?
• What does the keyword protected mean? When is it used,
and what does it do?
• What is meant by the static and dynamic types of a
variable?
Questions!?!!!
Previously, on PW #1
• Functions
• Input functions:
• Input number of students in a class
• Input student information: id, name, DoB
• Input number of courses
• Input course information: id, name
• Select a course, input marks for student in this course
• Listing functions:
• List courses
• List students
• Show student marks for a given course
Why
• Easier to manage
• Close to real-world management
Why
Object-Oriented Programming
Procedural Programming • Variables and related
• Variables and related
functions are bound
functions are separated
together
• Programs is divided into
• Programs are divided into
functions
objects
How
• Define a class
class <ClassName>
• Define a method
def <methodName>([args])
• Define a constructor
def __init__([args])
• Create an object from class
<obj> = <ClassName>([args])
• self: current object
How
class Person:
def print(self):
print("Name:", [Link])
print("Age:", [Link])
How
How
2
Hence its name is __lt__
OOP in Python Tran Giang Son, [Link]@[Link] 16 / 34
Review Object and Class Inheritance Polymorphism Encapsulation
How
def __str__(self):
return f"My name is {[Link]}. I am {[Link]}."
def describe(self):
print("Name:", [Link])
print("Age:", [Link])
def __str__(self):
return f"My name is {[Link]}. I am {[Link]}."
$ ./[Link]
Inheritance
Defining Inheritance
class President(Person):
def set_term(self, term):
print(f"Setting term to {term}")
[Link] = term
Defining Inheritance
Checking inheritance
Checking inheritance
$ ./[Link]
Multiple Inheritance
class Employee:
def work(self):
print("I should be paid...")
Multiple Inheritance
Polymorphism
Method overrides
• A superclass’s method can be overridden, simply by deffing
the same method name in the subclass
• A superclass instance can be accessed using super() in the
subclass
class Person:
# already defined before...
def work(self):
super().work() # from Employee
OOP in Python Tran Giang Son, [Link]@[Link] 28 / 34
Review Object and Class Inheritance Polymorphism Encapsulation
Method overrides
Encapsulation
• public by default
• No specified keyword
• Use underscore prefixes
• name: public
• _name: protected
• __name: private
def _get_salary(self):
return self.__salary
def work(self):
if self.__salary == 0:
print("I should be paid...")
else:
print("I am well paid!")
$ ./[Link]
Macron is now President
Setting term to 25
Name: Emmanuel Macron
Age: 43
President is well paid!
Macron salary is 1000
Traceback (most recent call last):
File ".../[Link]", line 59, in <module>
print(f"Macron's salary is {macron.__salary}")
AttributeError: 'President' object has no attribute '__salary'
Intro
Modules
What
What
Why
• Modularity
• Reusability
• Shareibility
• Maintainability
• Aliasing
• from <module> import <func/class/const> as <alias>
• Use <alias>
Packages
What
Why
How
How
How
Practice!
Reviews
Files
What
Why
Why
• RAM is volatile
• Variables are lost after process finishes
• File is persistent
• Data is saved
How
1. Open a file
2. Read or write
3. Close the file
• open(fileName, mode)
• fileName: what file
• mode: what operations
• returns a File object representing an opened file
Mode Meaning
r Reading (default)
w Writing. Creates or clears a file.
x Exclusive creation. Fails if file exists.
a Appending. Creates if file does not exist.
t Opens in text mode. (default)
b Opens in binary mode.
+ Opens a file for updating (rw)
How: Read/write
How: Read/write
• Text files
• .readline(): reads until a new line.
• There’s a \n at the end of file
How: Buffering
• Buffer: in-memory cache of file content
• Speeding up IO accesses1
• Reading/writing blocks is faster than individual bytes
1
Even stdout. . .
Files and Directories Tran Giang Son, [Link]@[Link] 12 / 33
Files Directories Practice!
How: Buffering
How: Extras
• Exceptions
• Temporary files
• Compression
• Objects
• Module tempfile
import [Link]
• pickle module
• [Link](obj, f): save object obj into
already-opened-for-binary-write file f
• obj = [Link](f): load object from
already-opened-for-binary-read file f
Directories
What
What
• Hierachical structure
• A bunch of files
• A bunch of sub-directories
Why
How
How
>>> import os
>>> e=[Link](".")
>>> [f for f in e]
[<DirEntry '0. [Link]'>, \
<DirEntry '1. course [Link]'>, \
<DirEntry '2. [Link]'>, \
<DirEntry '3. [Link]'>, \
<DirEntry '4. [Link]'>, \
<DirEntry '5. [Link]'>]
>>> [Link]("figs/intro")
Practice!
Multi Processing
Review
Review
• Process
• Scheduling
• IO Redirection
Process
• What is process?
• Process vs program?
Process
• Process is a program in execution state
Process
• Process is a program in execution state (active)
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process
• Process is a program in execution state (active)
• Why process?
• Program is passive
• No execution → what’s running?
Process States
waiting
interrupt
admitted exit
new ready running terminated
scheduled
Process States
waiting
interrupt
admitted exit
new ready running terminated
scheduled
Process Creation
Process Creation
$ pstree -A
init-+-acpid
|-cron
|-daemon---mpt-statusd---sleep
|-dbus-daemon
|-dovecot-+-anvil
| |-config
| `-log
|-master-+-pickup
| |-qmgr
| `-tlsmgr
|-mysqld_safe---mysqld---23*[{mysqld}]
|-php5-fpm---2*[php5-fpm]
|-proftpd
|-screen---bash---python2---{python2}
|-sshd-+-sshd---sshd---bash---pstree
| `-sshd---sshd
|-udevd---2*[udevd]
`-znc---{znc}
Multi Processing Tran Giang Son, [Link]@[Link] 8 / 39
Review Processes Practice!
fork()
exec() exit()
child
• fork()
• Perfectly «clone» current process to a new process
• fork()
• Perfectly «clone» current process to a new process
• Open files
• Register states
• Memory allocations
• Except process id
• Who’s who?
• Parent?
• Child?
• fork()
• Perfectly «clone» current process to a new process
• Open files
• Register states
• Memory allocations
• Except process id
• Who’s who?
• Parent?
• Child?
pid_t fork(void);
$ ./dofork
Main before fork()
I am parent after fork(), child is 2378
I am child after fork()
Multi Processing Tran Giang Son, [Link]@[Link] 13 / 39
Review Processes Practice!
• exec()
• Load an executable binary to replace current process image
• A family of functions.
• Ask man
int execl(...);
int execle(...);
int execlp(...);
int execv(...);
int execvp(const char *file, char *const argv[]);
int execvP(...);
• exec() example
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Going to launch ps -ef\n");
char *args[]= { "/bin/ps", "-ef" , NULL};
execvp("/bin/ps", args);
return 0;
}
Scheduling
Scheduling
Scheduling
Scheduling
Executing
Executing
Interrupt
reload state from PCB0
Executing
Multi Processing Tran Giang Son, [Link]@[Link] 19 / 39
Review Processes Practice!
Scheduler
• Knowns
• List of processes
• Process states
• Accounting information
Scheduler
• Knowns
• List of processes
• Process states
• Accounting information
• Constraints
• Process priority (if any)
• Processes have scheduling priority
• Indicates the importance of each process
• Higher priority: more likely to be scheduled
Scheduler
• Problems
• P1: What processes to run next?
Scheduler
• Problems
• P1: What processes to run next?
• P2: How long should it run?
Scheduler
Scheduler
Scheduler
IO Redirection
esc
F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12
~
`
!
1
@
2
#
3
$
4
%
5
^
6
&
7
*
8
(
9
)
0
_
-
+
= delete
stdin (0) Process stdout (1)
{ } |
Q W E R T Y U I O P [ ] \
tab
: enter
“
caps lock
A S D F G H J K L ; ‘ return
< > ?
Z X C V B N M , . /
shift shift
alt ⌘ ⌘ alt
stderr (2)
IO Redirection
esc
F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12
~
`
!
1
@
2
#
3
$
4
%
5
^
6
&
7
*
8
(
9
)
0
_
-
+
= delete
stdin (0) Process stdout (1) file
{ } |
Q W E R T Y U I O P [ ] \
tab
: enter
“
caps lock
A S D F G H J K L ; ‘ return
< > ?
Z X C V B N M , . /
shift shift
alt ⌘ ⌘ alt
stderr (2)
IO Redirection
stderr (2)
IO Redirection
stderr (2)
IO Redirection
file stdin (0) Process 1 stdout (1) stdin (0) Process 2 stdout (1) file
Processes
Modules
• os
• subprocess
Task
• Create a process
• Run and wait for finish
• Run in background
• Run with timeout
• IO redirection
• Redirect input
• Redirect output
• Redirect with pipe
• Terminate
• Get return code
os module
• os module is deprecated in Python 3
• This is for references only.
Task How
subprocess module
Task How
Practice!
Multithreading
Review
Remind PCB
Remind PCB
• Single-threaded process
• Default
• Only one thread per process
Single-threaded process
max
stack
free memory
• Single stack
• Single text section (code)
• Single data section (global data) heap
• Single heap (dynamic allocation)
data
text
0
Multi-threaded process
Multi-threaded process
code data file descs
heap
Multi-threaded process
• Same goals
• Same goals
• Do several things at the same time
• Same goals
• Do several things at the same time
• Increase CPU utilization
• Same goals
• Do several things at the same time
• Increase CPU utilization
• Increase responsiveness
• Same goals
• Do several things at the same time
• Increase CPU utilization
• Increase responsiveness
• Same goals
• Do several things at the same time
• Increase CPU utilization
• Increase responsiveness
• Same goals
• Do several things at the same time
• Increase CPU utilization
• Increase responsiveness
Why?
• Responsiveness
• Performance
• Resource Sharing
• Scalability
Responsiveness
Responsiveness
Responsiveness
Responsiveness
Performance
Resource Sharing
Scalability
• Complication
1
Image courtesy of Toni Miu’s blog
Multithreading Tran Giang Son, [Link]@[Link] 16 / 38
Review Multithreading Practice!
2
Image courtesy of Toni Miu’s blog
Multithreading Tran Giang Son, [Link]@[Link] 17 / 38
Review Multithreading Practice!
Multithreading
Python threading
3
e.g. numpy uses native libraries, so no GIL problem
Multithreading Tran Giang Son, [Link]@[Link] 20 / 38
Review Multithreading Practice!
Python threading
• Why GIL?
• Memory management
• Reference counting
• Garbage collector
• Simplification of thread-safety
• Only 1 mutex on the intepreter
• No multiple mutexes on each object
• No deadlock
Python threading
• Why GIL?
• Memory management
• Reference counting
• Garbage collector
• Simplification of thread-safety
• Only 1 mutex on the intepreter
• No multiple mutexes on each object
• No deadlock
Python threading
• Removing GIL?
• Slower single-threaded performance
• 1 mutex per object reference. . .
• Potential deadlocks
• Less compatbility
How?
• 2 «How» questions:
How?
• 2 «How» questions:
• Q1: How does thread achieve concurrency?
How?
• 2 «How» questions:
• Q1: How does thread achieve concurrency?
• Q2: How to use thread?
single core T1 T2 T3 T4 T5 T1 T2 T3 …
time
core 0 T1 T5 T4 T3 T2 T1 T5 T4 …
core 1 T2 T1 T5 T4 T3 T2 T1 T5 …
core 2 T3 T2 T1 T5 T4 T3 T2 T1 …
core 3 T4 T3 T2 T1 T5 T4 T3 T2 …
time
def run(self):
[Link](self.__sleepTime)
print(f"Finished sleeping {self.__sleepTime}s")
class BackgroundThread([Link]):
def __init__(self, sleepTime):
[Link].__init__(self)
self.__sleepTime = sleepTime
def run(self):
[Link](self.__sleepTime)
print(f"Finished sleeping {self.__sleepTime}s")
backgroundThread = BackgroundThread(10)
[Link]() # note no args here
[Link]()
print("Finished main thread")
Multithreading Tran Giang Son, [Link]@[Link] 33 / 38
Review Multithreading Practice!
How: Extras
t = [Link](target=threadFunction, args=(10,))
[Link]()
How: Extras
How: Extras
lock = [Link]()
[Link]()
# do something dangerous here
[Link]()
with lock:
# do something dangerous here
print("Dangerous function")
Practice!
GUI Toolkit
GUI
What
• GUI
• Graphical User Interface
• Interactive with graphical components
• Windows, scrollbars, buttons, textboxes,
• Sexy (?)
• CLI
• Command Line Interface
• Writing commands in terminal
• Wait for response from system
• Old school, boring (?)
CLI vs GUI
Why
Toolkits
Included? Yes No No No
Cross platform Yes Yes Yes Yes
Backend Tcl/Tk Qt OpenGL wxWidgets
Tkinter
• Simplicity
• TODO: image of student
• Flexibility
management system here
• Focusing on new comers
Tkinter
• Window
• Widgets
• Layout
• Window event loop
Tkinter: Widgets
• Everything is widget
• Frame
• Label
• Buttons
• Entry
• Check Button
• Radio Button
• List Box
• ComboBox
• Menu
• ...
• Important attributes
• Dimension: width = 400, height =
300
• Background color: bg = "green"
• Label
• Show texts
• [Link](window, text = "This is a Label")
def onClick():
[Link](message="Button 1 clicked")
entry = [Link](window)
[Link](-1, "Entry for text input")
• Checkbutton
• Checkboxes
• 2 states: check and uncheck
• [Link](window, text = "Checkbutton option
1")
Output:
[Link](window).grid(
column = 1, row = 0, sticky = [Link], padx = 3, pady = 3, columnspan = 4)
[Link](window).grid(
column = 1, row = 1, sticky = [Link], padx = 3, pady = 3, columnspan = 4)
• A blocking method
• Handles input, output events
• [Link]()
Practice!
>>> import [Link] as plt >>> [Link](x,y,ls='solid') >>> [Link](ticks=range(1,5), Manually set x-ticks
>>> [Link](x,y,ls='--') ticklabels=[3,100,-12,"foo"])
Figure >>>
>>>
[Link](x,y,'--',x**2,y**2,'-.')
[Link](lines,color='r',linewidth=4.0)
>>> ax.tick_params(axis='y', Make y-ticks longer and go in and out
direction='inout',
>>> fig = [Link]() length=10)
>>> fig2 = [Link](figsize=[Link](2.0)) Text & Annotations
Subplot Spacing
Axes >>> [Link](1, >>> fig3.subplots_adjust(wspace=0.5, Adjust the spacing between subplots
-2.1, hspace=0.3,
All plotting is done with respect to an Axes. In most cases, a 'Example Graph', left=0.125,
subplot will fit your needs. A subplot is an axes on a grid system.
style='italic') right=0.9,
>>> [Link]("Sine", top=0.9,
>>> fig.add_axes() xy=(8, 0), bottom=0.1)
>>> ax1 = fig.add_subplot(221) # row-col-num xycoords='data', >>> fig.tight_layout() Fit subplot(s) in to the figure area
xytext=(10.5, 0),
>>> ax3 = fig.add_subplot(212) textcoords='data', Axis Spines
>>> fig3, axes = [Link](nrows=2,ncols=2) arrowprops=dict(arrowstyle="->", >>> [Link]['top'].set_visible(False) Make the top axis line for a plot invisible
>>> fig4, axes2 = [Link](ncols=3) connectionstyle="arc3"),) >>> [Link]['bottom'].set_position(('outward',10)) Move the bottom axis line outward
L I STS len(my_set) - Returns the number of objects in now - wks4 - Return a datetime object
[Link](3) - Returns the fourth item from l and my_set (or, the number of unique values from l) representing the time 4 weeks prior to now
deletes it from the list a in my_set - Returns True if the value a exists in newyear_2020 = [Link](year=2020,
[Link](x) - Removes the first item in l that is my_set month=12, day=31) - Assign a datetime
equal to x object representing December 25, 2020 to
[Link]() - Reverses the order of the items in l REGULAR EXPRESSIONS newyear_2020
l[1::2] - Returns every second item from l, import re - Import the Regular Expressions module newyear_2020.strftime("%A, %b %d, %Y")
commencing from the 1st item [Link]("abc",s) - Returns a match object if - Returns "Thursday, Dec 31, 2020"
l[-5:] - Returns the last 5 items from l specific axis the regex "abc" is found in s, otherwise None [Link]('Dec 31, 2020',"%b
[Link]("abc","xyz",s) - Returns a string where %d, %Y") - Return a datetime object
ST R I N G S all instances matching regex "abc" are replaced representing December 31, 2020
[Link]() - Returns a lowercase version of s by "xyz"
[Link]() - Returns s with the first letter of every RANDOM
word capitalized L I ST C O M P R E H E N S I O N import random - Import the random module
"23".zfill(4) - Returns "0023" by left-filling the A one-line expression of a for loop [Link]() - Returns a random float
string with 0’s to make it’s length 4. [i ** 2 for i in range(10)] - Returns a list of between 0.0 and 1.0
[Link]() - Returns a list by splitting the the squares of values from 0 to 9 [Link](0,10) - Returns a random
string on any newline characters. [[Link]() for s in l_strings] - Returns the integer between 0 and 10
Python strings share some common methods with lists list l_strings, with each item having had the [Link](l) - Returns a random item from
s[:5] - Returns the first 5 characters of s .lower() method applied the list l
"fri" + "end" - Returns "friend" [i for i in l_floats if i < 0.5] - Returns
"end" in s - Returns True if the substring "end" the items from l_floats that are less than 0.5 COUNTER
is found in s from collections import Counter - Import the
F U N C T I O N S F O R LO O P I N G Counter class
RANGE for i, value in enumerate(l): c = Counter(l) - Assign a Counter (dict-like)
Range objects are useful for creating sequences of print("The value of item {} is {}". object with the counts of each unique item from
integers for looping. format(i,value)) l, to c
range(5) - Returns a sequence from 0 to 4 - Iterate over the list l, printing the index location c.most_common(3) - Return the 3 most common
range(2000,2018) - Returns a sequence from 2000 of each item and its value items from l
to 2017 for one, two in zip(l_one,l_two):
range(0,11,2) - Returns a sequence from 0 to 10, print("one: {}, two: {}".format(one,two)) T RY/ E XC E P T
with each item incrementing by 2 - Iterate over two lists, l_one and l_two and print Catch and deal with Errors
range(0,-10,-1) - Returns a sequence from 0 to -9 each value l_ints = [1, 2, 3, "", 5] - Assign a list of
list(range(5)) - Returns a list from 0 to 4 while x < 10: integers with one missing value to l_ints
x += 1 l_floats = []
DICTIONARIES - Run the code in the body of the loop until the for i in l_ints:
max(d, key=[Link]) - Return the key that value of x is no longer less than 10 try:
corresponds to the largest value in d l_floats.append(float(i))
min(d, key=[Link]) - Return the key that DAT E T I M E except:
corresponds to the smallest value in d import datetime as dt - Import the datetime l_floats.append(i)
module - Convert each value of l_ints to a float, catching
S E TS now = [Link]() - Assign datetime and handling ValueError: could not convert
my_set = set(l) - Return a set object containing object representing the current time to now string to float: where values are missing.
the unique values from l wks4 = [Link](weeks=4)
- Assign a timedelta object representing a
timespan of 4 weeks to wks4