KHÓA ĐÀO TẠO TÍNH TOÁN ỔN ĐỊNH VÀ ỨNG DỤNG TRÊN PHẦN MỀM PSSE CHO KỸ SƯ HỆ THỐNG ĐIỆN (Ngôn ngữ lập trình Python và ứng dụng trên Phần mềm PSSE): • Basic Syntax• Variables• Control Flow Tools• BuiltIn Functions and Methods• UserDefined Functions• Files and Directories
Trang 1A Division of Global Power
POWER SYSTEM STABILITY CALCULATION TRAINING
D 13 I t d ti t P th Day 13 - Introduction to Python
December 4, 2013 Prepared by: Mohamed El Chehaly
Trang 2OUTLINE OUTLINE
• Basic Syntax
• Variables
• Control Flow Tools
• Built-In Functions and Methods
• User-Defined Functions
• Files and Directories
Trang 3BASIC SYNTAX eBook for You
Trang 4Introduction
Easy to learn, powerful programming tool
Efficient high level data structures
Simple but effective approach to
object-oriented programming
Programs in Python much shorter than
equivalent C C++ or Java programs:
Complex operations can be expressed in a single
statement
Statement grouping is done by indentation instead
of beginning and ending brackets
Trang 5Introduction
the interpreter and you do not need to
the interpreter and you do not need to
compile your program before executing it
Python prompt and interact with the
Object-oriented: Python supports style or
technique of programming that
encapsulates code within Objects
beginner programmers
Trang 6Python Basic Syntax
Python Basic Syntax
Interactive mode programming
Open IDLE (Python GUI)
Trang 7Python Basic Syntax
Python Basic Syntax
Interactive mode programming
Write the following
Write the following
print “Hello; Python!”
Trang 8Python Basic Syntax
Python Basic Syntax
Script mode programming
Open new window
Open new window
Trang 9Python Basic Syntax
Python Basic Syntax
Script mode programming
Write the following
Write the following
print “Hello, Python!”
Trang 10Python Basic Syntax
Python Basic Syntax
Script mode programming
Save as “Hello Python py”
Save as “Hello Python.py”
Run module
Trang 11 No punctuation characters such as @,$,%
Trang 12Python Identifiers
Python Identifiers
Python is case sensitive (name and Name)
Convention for Python
Class names start with an uppercase letter
Starting an identifier with a single leading
Starting an identifier with a single leading
underscore “_” indicates that the identifier is
private
Starting an identifier with two leading underscores
“ ”indicates a strongly private identifier
If the identifier also ends with two trailing
If the identifier also ends with two trailing
underscores, the identifier is a language-defined
special name
Trang 14Lines and Indentation
Lines and Indentation
Blocks of code for class and function
definitions or flow control denoted by line
definitions or flow control denoted by line
indentation
No use of braces “{ }”
No use of braces { }
Test the following code
Test the following code
Trang 15Multi Line Statements
Multi-Line Statements
Statements in Python typically end with a
new line
Continuation on next line allowed with “\”
Statements contained within [ ], { } and ( )
do not need to use the line continuation
character
Trang 16Quotation in Python
Quotation in Python
Python accepts single (‘), double (“) and
triple (‘’’ or “””) quotes to denote string
The same types of quote should start and
end the string
The triple quotes can be used to span the
Trang 17Comments in Python
Comments in Python
A hash sign “#” that is not inside a string
lateral begins a comment
All characters after the # and up to the
physical line end are part of the comment
A line can be commented by ALT+3 and
t d b ALT+4
Trang 18Waiting for the User
Waiting for the User
The following line of the program displays
the prompt “Press the enter key to exist.”
The program will wait for the user to
press the Enter key
Here “\n\n” are being used to create two
new lines before displaying the actual line
This is a nice trick to keep a console
window open until the user is done with an
window open until the user is done with an
application
Trang 19VARIABLES eBook for You
Trang 20Standard Data Type
Standard Data Type
Trang 21Assigning Values to Variables
Assigning Values to Variables
Python variables do not have to be
explicitly declared
The declaration happens automatically
when you assign a value to a variable
Trang 22Numbers
Python supports four different numerical
types
int: signed integers
octal and hexadecimal)
float: floating point real values
complex: complex numbers
Numbers with different base can be
represented
Binary: start with 0B or 0b
Octal: start with 0O or 0o
Hexadecimal: start with 0x or 0X
Trang 24>>>print str1*2 # Prints string two times
Hello World! Hello World!
>>> print str1 + "TEST" # Prints concatenated string
Hello World!TEST
Trang 25Lists
Most versatile of Python’s compound data
types
A list contains items separated by
commas and enclosed within square
commas and enclosed within square
brackets “[ ]”
All the items belonging to a list can be of
All the items belonging to a list can be of
different data type
The values stored in a list can be
The values stored in a list can be
accessed using the slice operator “[ ]”
with indexes starting at 0 in the beginning
of the list
Trang 26>>> print list1 [1:3] # Prints elements starting from 2 nd till 3 rd
>>> print list1 [1:3] # Prints elements starting from 2 nd till 3 rd
>>>print list1 + tinylist # Prints concatenated lists
>>>print list1 + tinylist # Prints concatenated lists
[ ‘abcd’, 786, 2.23, ‘john’, 70.2, 123, 'john‘]
Trang 27Tuples
A tuple is another sequence data type that
is similar to the list
A tuple contains items separated by
commas and enclosed within parentheses
commas and enclosed within parentheses
“( )”
The main difference between lists and
The main difference between lists and
tuples is that the elements and the size of
the list can be changed while tuples
cannot be updated
Trang 28Dictionaries
Kind of hash table type
Consist of key-value pairs
A dictionary key can be almost any Python
type but are usually numbers or strings
Values can be an arbitrary values
Dictionaries are enclosed by curly braces
“{ }” and values can be accessed using
Trang 29Dictionaries
Example
>>> dict1 = { ‘name’: ‘john’ ‘code’: 6734 ‘dept’: ‘sales’ }
>>> print dict1 # Prints complete dictio nary
{'dept': 'sales', 'code': 6734, 'name': 'john'}
>>>print dict1[‘name’] # Prints value for ‘name’ key
>>>print dict1[ name ] # Prints value for name key
john
>>> print dict1.keys() # Prints all the keys
['dept' 'code' 'name']
>>>print dict1.values() # Prints all the values
['sales', 6734, 'john']
>>> dict2 = {}
>>> dict2[‘one’] = “This is one”
>>> dict2[2] = “This is two”
>>>print dict2[‘one’]
>>>print dict2[2]
Trang 30CONTROL FLOW TOOLS eBook for You
Trang 32Operators
Python arithmetic operators
Trang 33Operators
Python arithmetic operators
Trang 37Operators
Python logical operators
a=True and b=True
Trang 38Operators
Python membership operators
Trang 39Decision Making
Decision Making
Decision making structures require that
the programmer specify one or more
the programmer specify one or more
conditions to be evaluated or tested by the
program
If the condition is true, the program will
Optionally, other statements may be
executed if the condition is false
Python programming language assumes
any non-zero and non-null values as true
Trang 41Decision Making
Decision Making
IF statements
Write the following code and test it
Trang 43Decision Making
Decision Making
IF…ELSE statements
Write the following code and test it
Trang 44Decision Making
Decision Making
ELIF statements
Write the following code and test it
Trang 45Decision Making
Decision Making
Nested IF statements
Write the following code and test it
Trang 46Loops
Needed when a block of statements needs
to be executed several times
Trang 47Loops
While loop statements
Block repeatedly executed as long as the given
Block repeatedly executed as long as the given
condition is true
Trang 49Loops
For loop statements
Block repeatedly executed for a defined number
Block repeatedly executed for a defined number
of times
Trang 51Loops
Break statements
Terminates the current loop and resumes
Terminates the current loop and resumes
execution at the next statement
Trang 53Loops
Continue statements
Returns the control to the beginning of the while
Returns the control to the beginning of the while
loop
Trang 55BUILT-IN FUNCTIONS AND
BUILT-IN FUNCTIONS AND
METHODS
Trang 56Number Functions
Number Functions
Mathematical functions (import math)
Trang 57Number Functions
Number Functions
Trigonometric functions (import math)
Mathematical constants (import math)
Trang 59String Functions and Methods
String Functions and Methods
Trang 60String Functions and Methods
String Functions and Methods
Trang 61String Functions and Methods
String Functions and Methods
Trang 62String Functions and Methods
String Functions and Methods
Trang 63List Functions
List Functions
Trang 64List Methods
List Methods
Trang 65USER-DEFINED FUNCTIONS eBook for You
Trang 66Definition
A function is a block of organized,
reusable code that is used to perform a
reusable code that is used to perform a
single, related action
Functions provide better modularity and a
Functions provide better modularity and a
high degree of code reusing
Python gives many built-in functions like
Python gives many built in functions like
print()
Programmers can create their own
Programmers can create their own
functions
Trang 67Defining a Function
Defining a Function
Simple rules to define a function
Function blocks begin with the keyword def
followed by the function name and parentheses
“()”
Any input parameters or arguments should be
placed within these parentheses
The first statement of a function can be an
optional statement – the documentation string or
docstring
The code block within every functions starts with a
colon “:” and is indented
Trang 68Defining a Function
Defining a Function
Example
Simplest form of a Python function
Trang 69Calling a Function
Calling a Function
Once the basic structure of a function is
finalized you can execute it by calling it
finalized, you can execute it by calling it
from another function or from the Python
prompt
Trang 70Pass by Reference
Pass by Reference
All parameters are passed by reference
Trang 71Function Arguments
Function Arguments
You can call a function by using the
following types of formal arguments
Trang 72Function Arguments
Function Arguments
Required arguments
Arguments passed to a function in the correct
Arguments passed to a function in the correct
order
Trang 73Function Arguments
Function Arguments
Keyword arguments
When you use keyword arguments in a function
When you use keyword arguments in a function
call, the caller identifies the arguments by the
parameter name
Trang 74Function Arguments
Function Arguments
Default arguments
Argument that assumes a default value if a value
Argument that assumes a default value if a value
is not provided in the function call
Trang 75Function Arguments
Function Arguments
Variable-length arguments
You may need to process a function for more
You may need to process a function for more
arguments than you specified while defining the
function
Trang 76Function Arguments
Function Arguments
Return statement
The return statement exists a function optionally
The return statement exists a function, optionally
passing back an expression
Trang 77FILES AND DIRECTORIES eBook for You
Trang 78Reading Keyboard Input
Reading Keyboard Input
Python provides two built-in functions to
read a line of text from standard input
read a line of text from standard input
which by default comes from the keyboard
raw_input
input
Trang 79Reading Keyboard Input
Reading Keyboard Input
The raw_input function
This function reads one line from standard input
and returns it as a string
It removes the trailing newline
Trang 80Reading Keyboard Input
Reading Keyboard Input
The input function
Trang 81Opening and Closing Files
Opening and Closing Files
The open function
Before you can read or write a file, you have to
open it using Python’s built-in open() function
S t
Syntax
file name: string value that contains the name of
file_name: string value that contains the name of
the file that you want to access
access_mode: determines the mode in which the
file has to be opened
Trang 82Opening and Closing Files
Opening and Closing Files
The open function
The access_mode
Trang 83Opening and Closing Files
Opening and Closing Files
The file object attributes
Once a file is opened and you have one file object
you can get various information related to that file
Trang 84The Module OS
The Module OS
Python “os” module provides methods
that help you perform file-processing
operations, such as renaming and deleting
fil
files
Renaming and deleting files
rename(): takes two arguments, the current
filename and the new filename
remove(): to delete files by supplying the name of
remove(): to delete files by supplying the name of
the file to be deleted as the argument
Trang 85 chdir(): to change the current directory
getcwd(): to display the current directory
rmdir(): to delete the directory Before removing a
rmdir(): to delete the directory Before removing a
directory, all the contents in it should be removed
Trang 86QUESTIONS?
Trang 87partners WE CARE is integral to the way we perform on a daily
b i It i b th ibilit d f ti f ti d basis It is both a responsibility and a source of satisfaction and pride by providing such important standards to all we do.
WE CARE about the health and safety of our employees, of those who work under our care, and
of the people our projects serve.
WE CARE about our employees, their personal growth, career development and general
well-WE CARE about our employees, their personal growth, career development and general well
being.
WE CARE about the communities where we live and work and their sustainable development, and we commit to
fulfilling our responsibilities as a global citizen.
fulfilling our responsibilities as a global citizen.
WE CARE about the environment and about conducting our business in an environmentally responsible manner.
WE CARE about the quality of our work.