Escolar Documentos
Profissional Documentos
Cultura Documentos
1
Outline
Introduction to Python
Python Programming
Variables, expressions and statements
Conditional execution
Functions
Iteration
Strings
Files
Lists
Dictionaries
Regular expressions
Automating common tasks on computer
2
Introduction to Python
3
Introduction to Python
Interpreted Compiled
Not translated to machine Translated to machine language
language using compiler
Interpreted by intermediate Executed directly by hardware
program (interpreter) (CPU)
Advantage: portability Advantage: faster than
interpreted
4
Introduction to Python
Use an interpreter
CPU understand machine language (tied to machine hardware)
High-level languages are portable across different type of hardware (use of
interpreter
Interpreter:
Interprets instructions on the fly
No need to pass entire program
5
Introduction to Python
6
Activity 1
7
Introduction to Python
8
Introduction to Python
9
Python Programming: Values and
Types
Value: data, usually to a variable
Built-in types of values:
Boolean (True or False)
Numeric: int (32 bits), long (unlimited presicion), float (dot decimal), complex
(real and imaginary parts)
Sequence: str, byte (seq int in range 0-255, 3.x), byte array (mutable bytes, 3.x),
list, tuple
Sets: set (unordered collection of unique objects), froze set (immutable set)
Mappings: dict (hashmaps)
None: similar to Null
10
Activity 2
11
Python Programming: Mutable and
Immutable Objects
Some immutable types Some mutable types
int, float, long, complex* byte array
str list
bytes set
tuple dict
frozen set
boolean
13
Python Programming: Variable names
and keywords
Names
Generally meaningful and document what the variables is used for
Arbitrary long
Alphanumeric characters (cannot start with number)
Underscore allowed
Good practice: begin variable name with lowercase
Try variable names 3char, email@ and class
14
Python Programming: Reserved
keywords
and exec or
as finally pass
assert for print
break from
raise
class global
return
continue if
def import
try
del in while
elif is with
else lambda yield
except not
15
Python Programming: Statements
16
Python Programming: Operators and
Operands
Operators: addition (+), subtraction(-), multiplication (*), division (/),
remaining(%) and exponentiation (**)
Operands: values the operator is applied
17
Python Programming: Order of
operations
Depends on rule of precedence
PEMDAS: Parenthesis, Exponentiation, Multiplication and Division, Addition
and Subtraction
Operators of same precedence: from left to right
Example:
3*1**3: 3 or 27?
6+4/2: 5 or 8?
5-3-1: 3 or 1?
18
Activity 3
Create a script that asks (‘raw_input()’) for a number of minutes and show
them in hour-and minute-format (60min == 1h0min)
Suggestion: use parsing
Two ways:
python + {script_name}
Include in script’s 1st line ‘#!{python_interpreter_path}’ (tell shell kind of
interpreter to run)
19
Activity 3: Solution
Script ‘min2hour.py’:
21
Python Programming: String operations
22
Python Programming: Comments
23
Python programming: Conditional
execution
Comparison operators
x != y: not equal
x > y: greater than
x < y: less than
x >= y: greater than or equal
x <= y: less than or equal
x is y: same as
x is not y: not the same as
Logical operators
and
or
not
* Non zero values interpreted as True (Python is flexible)
24
Python programming: Conditional
execution
Syntax of conditional statement:
if {condition}:
do something
else: #If condition is not true, then do another thing
do another thing
25
Python programming: Conditional
execution
Syntax of chained conditionals:
if {condition1}:
do thing1
elif {condition2}: #If previous condition is not true, then do thing2
do thing2
else: #If none of previous condition is true, then do thingN
do thingN
Can be nested
26
Python programming: Conditional
execution
‘try and except’ statement: to catch exceptions
Syntax
try:
do something
except: # In case there is an exception, do something else
do something else
Can specify type of exception (after except)
27
Activity 4
28
Activity 4: Solution
#!/usr/bin/python
ddo = raw_input("Dividend: ")
dor = raw_input("Divisor: ")
try:
ddo = int(ddo)
dor = int(dor)
q = ddo / dor
r = ddo % dor
30
Python programming: Functions
Built-in functions
int(arg): converts argument to integer (if could be done, otherwise complains)
float(arg): to floating-point numbers (if could)
str(arg): converts argument to string
len({list}): length of list
range({start},{max not included},{step}): creates in memory list
xrange({start},{max not included},{step}): sequence object that evaluates lazily*
Iterate longer without getting ‘MemoryError’
If stop iteration early, will not waste time creating whole list
Memory limit: available memory (increase using swap/code optimization, reduce upper
limit using ‘reduce’ module)
31
Python programming: Functions
‘math’ module
Provides most familiar mathematical functions
First import it, then use it,: ‘import math’
log10, sin, pi, etc.
Complete list: https://docs.python.org/2/library/math.html
32
Python programming: Functions
33
Python programming: Iterations
while
syntax
34
Python programming: Iterations
35
Activity 5
36
Activity 5: Solution
import os
while True:
print '[1] System information\n[2] Date\n[3] RAM usage\n[9] Exit‘
opt = raw_input('Enter an option: ')
if opt is '1':
os.system('hostnamectl')
elif opt is '2':
os.system('date')
elif opt is '3':
os.system('free -h')
elif opt is '9':
print 'Bye!‘
break
else:
print "Invalid option"
37
Python programming: Strings
name = “{Your_name}”
letter = name[0] # Extract element in position ‘0’ – See in lists
String slices:
Syntax:
var1 = “String”
varm1[m:n] # String from m-th character to the n-th, including first but not last
Strings are immutable
38
Python programming: Strings
Manipulation of files
When read/write a file, first open file (OS finds it and validates it exists)
If open is successful, OS return a file handle (not data contained in file)
Exception if file does not exist (can use try-except)
Use file handle to read/write data
Can open file with ‘w’ (write) permissions and then write any string
After writing a file, close it
Python closes all opened files when program finishes
40
Python programming: Files
* When iterating over handle or reading its content, offset is at last line. Use ‘seek({offset})’ to move
to an arbitrary line (0 for the beginning of file)
** Content of file (‘read()’) is a String (list of chars)
41
Python programming: Lists
Sequence of elements
Can be any type*
Lists are mutable
Empty list: {list_name} = []
Traverse it in iteration (for loop)
Operators:
‘+’: concatenate lists
‘*’: concatenate N times list with itself
Accept slices (same as strings)
Methods
append: add new element
sort: sort ascending; if ‘reverse’ parameter is true, sort descending
pop: delete element in specified position
remove: delete specified element
42
Python programming: Lists
word = 'W|E|L|C|O|M|E‘
tmp_list=word.split('|')
print tmp_list # output: ['W', 'E', 'L', 'C', 'O', 'M', 'E']
tmp_word = ‘-'.join(tmp_list)
print tmp_word # output: 'W-E-L-C-O-M-E'
43
Activity 6
Write down a sequence of integer numbers (in a file, each in a new line) and
print them in ascending order
44
Activity 6: Solution
import random
for _ in range(20):
rdm_num = random.random()*1000
rdm_num = int(rdm_num)
hdl.write(str(rdm_num) + '\n')
hdl.close()
for i in hdl:
i = i.rstrip()
tmp_list.append(int(i))
45
Python programming: Dictionaries
46
Activity 7
Python does not have a case/switch statement. Create one (or something
similar)
Tip: use functions and dictionaries
We will use Activity 5 scenario
47
Activity 7: Solution
import os
def Date():
os.system('date')
return False
def Free_RAM():
os.system('free -h')
return False
def Exit():
print 'Bye!‘
return True
48
Activity 7: Solution
#We use a dictionary to simulate behaviour of switch/case statement, content of each key is a Function
menu = {1: HostnameCTL, 2: Date, 3: Free_RAM, 9: Exit}
while 1:
print '[1] System information\n[2] Date\n[3] RAM usage\n[9] Exit‘
opt = raw_input('Enter an option: ')
try:
opt = int(opt)
# Option within dictionary, similar to choosing between switch/case elements
ans = menu[opt]()
if ans:
break
except KeyError:
print 'Invalid option\n‘
except ValueError:
print 'Option must be an integer number\n‘
except:
print 'An error occurred\n'
49
Python programming: Regular
expressions
Search and extract patterns in strings
Library ‘re’
Methods:
search({regular_exp}, {string_name}): match patterns
findall({regular_exp}, {string_name}): extract data from string
Regular expression patterns:
https://www.tutorialspoint.com/python/python_reg_expressions.htm
50
References
51