Вы находитесь на странице: 1из 51

Python Scripts

Ing. Ruben Cordova


Advanced Networks Research Lab.
Pontifical Catholic University of Peru

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

 High level language


 Intended to be straightforward for humans (read and write) and computers
(read and process)
 Reserved words: and, assert, del, except, not, or, return, try, etc.

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

 Python 2.7 vs 3.x


 Most visible difference: ‘print’ statement
 2.7: ‘print “Version 2.7”’
 2.7: ‘print(“Version 3”)’
 Some libraries (third-party support) only work on v2.7
 New features implemented in v3.x
 v3.x: where future is heading
 v2.7: far mode documentation available

6
Activity 1

 Check if Python is installed


 ‘which python’
 Use Python interpreter!
 Type ‘python’ on CLI
 Try and addition and print result
 To exit, type ‘quit()’

7
Introduction to Python

 What can I do with Python?


 Get data from “outside world” (keyboard, files, sensors)
 Display results of programs (file, screen, device like speaker)
 Sequential execution: one statement after another as in script
 Conditional execution
 Repeated execution
 Reuse code

8
Introduction to Python

 Kinds of errors we might encounter:


 Syntax (grammar) errors: easiest to find/fix
 Logic error: order of statements
 Semantic errors: conception of solution

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

 Use ‘type’ function to find out the type of value


 10
 ‘10’
 3.1416
 True
 true
 Values should be integer, string, float, boolean, and the last one shows an
error (not a reserved word, so python assumes is a variable name not define)

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

We will see them in when using Functions


(*) Defining complex number in Python: 3 + 4j
12
Python Programming: Variables

 Name that refers to a value (stored in memory)


 Assignment statement (=) creates variable and gives them values
 Activity 2 with variables

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

 Unit of code that Python Interpreter can execute


 Seen ‘print’ and assignment
 Script: sequence of 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’:

min = raw_input("Enter number of minutes: ")


int_min = int(min)
h = int_min / 60
m = int_min % 60
print "%dh%dmin" % (h,m)

 2 ways to execute it:


 ‘python min2hour.py’
 Add to the 1st line location of python interpreter: “#!/usr/bin/python”; then
execute as bash script: ‘./min2hour.py’
20
Python Programming: Expressions

 Combination of values, variables and/or operators


 Value by itself is expression (also variables)
 In interactive mode: interpreter evaluates and display results
 In script: expression by itself does not do anything

21
Python Programming: String operations

 ‘+’ operator: concatenation (only addition when used with strings)


 Example: Evaluate result of a 10 + 24 and ‘10’ + ’24’ in the python
interpreter’s interactive mode
 ‘python’
 1st expression: 34 (integer)
 2nd expression: 1024 (string)

22
Python Programming: Comments

 Explain in natural language what programs do


 # single line
 ‘’’ Multi
line
comment‘’’

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}: #If condition is true, then do something


do something
 Syntax of alternative execution:

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

 Write a script that divides 2 numbers. Under no circumstances the program


will show the exception if anything goes wrong. Additionally, show different
messages if division is by zero or one of the operands is not a number

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

print "Quotient: " + str(q)


print "Remaining: " + str(r)
except ValueError:
print "Dividend and/or divisor must be integers“
except ZeroDivisionError:
print "Dividend cannot be zero“
except:
print "An error has occurred"
29
Python programming: Functions

 Sequence of statements that perform a task


 When defining one, must specify its name and sequence of statements
 Function is called by name
 ‘type(32)’: integer 32 is called argument
 Functions “take” arguments and “return” a result
 Type: function
 Immutable variables

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

 Add new functions


 Syntax

def {function_name}({arg1, arg2,…}):


logic of function
return {value} # May not return anything – void functions
 Must be defined before using them

33
Python programming: Iterations

 while
 syntax

while {condition is true}:


do something
 for
 syntax

for {var} in {list}:


do something

34
Python programming: Iterations

 Can create infinite loops with ‘while’


 Exit with ‘break’ statement
 Can skip ‘for’ iterations
 With ‘continue’ statement

35
Activity 5

 Create an interactive script that have 3 options:


 1. Print system information (hostnamectl)
 2. Print date (date)
 3. Print RAM usage (free –h)
 9. Exit (only exit program if press this option)
 Tip: use library ‘os’

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

 Sequence (list) of characters


 Try:

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

 ‘in’ operator: check if sequence of character is present in another string


 Comparison operators work on strings
 Methods (functions of object)
 See available methods: dir(arg)
 See help of method: help({str}.capitalize)
 upper, lower, find (position of sequence of char), strip (remove white spaces), etc.
 Functions that begin with underscore:
https://shahriar.svbtle.com/underscores-in-python
 Format operator
 Construct strings with data in variables
 Format integers (%d), floating-point number (%g) and string (%s)
39
Python programming: Files

 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

 Open file: {handle} = open({relative/absolute_path_to_file}) # only read


 {handle} contains lines in file (iterate over it to see content*)
 use ‘rstrip’ to remove ‘new line’ character
 Read (content of) file: {var_name} = {handle}.read()* **
 Available all content of file
 Write in file
 {handle} = open(“{file_name}”,’w’) # opens with write permissions (if allowed)
 {handle}.write({var_with_content}) # use ‘\n’ to add new line, otherwise is overwritten
 Close file: {handle}.close()

* 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

 String (list of characters) methods


 {string}.split({delimeter}): split by {delimeter}
 {delimeter}.join({string_list}): join {string_list} elements, with {delimeter} between
them
 Example:

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

# Write down list of random numbers


hdl = open('num.txt', 'w')

for _ in range(20):
rdm_num = random.random()*1000
rdm_num = int(rdm_num)
hdl.write(str(rdm_num) + '\n')

hdl.close()

# Read content of 'num.txt‘


hdl = open('num.txt')
tmp_list = []

for i in hdl:
i = i.rstrip()
tmp_list.append(int(i))

# Sortand print list before and after sorting


print 'Before sorting:‘
print tmp_list
tmp_list.sort()
print 'After sorting:‘
print tmp_list

45
Python programming: Dictionaries

 Mapping between set of indices (called keys) and set of values


 Each key maps a value (key-value pair or item)
 Empty dictionary: {dict_name} = {}
 Methods
 {dict_name}.keys(): get list of keys
 {dict_name}.values(): get list of values

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

# Functions that state what to do when called from dictionary


def HostnameCTL():
os.system('hostnamectl')
return False

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

1. Charles Severance. Python for Informatics


http://www.pythonlearn.com/book_007.pdf
2. Python 2.7.14 documentation. The Python Standard Library
https://docs.python.org/2/library/stdtypes.html

51