0% found this document useful (0 votes)
6 views32 pages

Python Variables and Data Structures: Answers For Energy

The document provides an overview of Python's intrinsic types, including numbers, collections, and their examples. It explains dynamic typing, type conversions, and object methods, as well as string operations and list methods. Additionally, it covers type checking and converting sequences into lists or tuples, along with sequence-related functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views32 pages

Python Variables and Data Structures: Answers For Energy

The document provides an overview of Python's intrinsic types, including numbers, collections, and their examples. It explains dynamic typing, type conversions, and object methods, as well as string operations and list methods. Additionally, it covers type checking and converting sequences into lists or tuples, along with sequence-related functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Answers for energy.

Python Variables and Data


Structures
© 2015 Siemens Industry Inc. All rights reserved.
Intrinsic Types

Numbers Collections

Integers float Sequences Mappings


complex
int
Immutable Mutable dict
long

2015 Siemens Industry, Inc., Siemens Power Technologies


str list
bool
tuple

International (Siemens PTI)


Page 2-9 Siemens Power Academy TD-NA PSSE - Python Course
Intrinsic Types - Examples

Python has several built-in types

Description Type Example


Integer Int, long 5
Float float 3.141592654
Complex complex 1.23 + 4.56j
String str 'power flow'

2015 Siemens Industry, Inc., Siemens Power Technologies


Boolean bool True, False
Tuple tuple (8, 'load', 4.78)
List list ['brn', 'area', 99, 3.78]
Dictionary dict {'bus' :101, 107:1.15}

International (Siemens PTI)


None NoneType None

Note: You can create your own classes of objects as well, or extend intrinsic types

Page 2-10 Siemens Power Academy TD-NA PSSE - Python Course


Dynamic Typing in Python

Variables do not need to be declared in Python!


a = 2
b = 17.6
c = 'This is a string'
d = c # c and d point to same object !
d = copy.deepcopy(c) # c and d are now different objects!
# (needs import copy before))

2015 Siemens Industry, Inc., Siemens Power Technologies


Variables are simply names which refer to objects.
Names: a b c d

International (Siemens PTI)


Objects: 2 17.6 'This is a string'
(integer) (floating point) (string)

Page 2-11 Siemens Power Academy TD-NA PSSE - Python Course


Python Expression Operators

Math + - * / % **

Assignment = += -= *= /= %= **=

Comparison == != >= <= > <

2015 Siemens Industry, Inc., Siemens Power Technologies


Logical and or not

Identity is is not

International (Siemens PTI)


Containment in not in

Page 2-12 Siemens Power Academy TD-NA PSSE - Python Course


Type Conversions

Functions exist to convert between types:

a = 5
b = 7
c = a * b # c = 35
d = float(a) * b # d = 35.0
e = float(a * b) # e = 35.0

2015 Siemens Industry, Inc., Siemens Power Technologies


f = float(a / b) # f = 0.0
g = float(a) / float(b) # g = 0.714 ...

But not all conversions are possible:

International (Siemens PTI)


u = int('test') # Error
ValueError: invalid literal for int()

Page 2-13 Siemens Power Academy TD-NA PSSE - Python Course


Object Type Checking – type() and isinstance() functions

type() returns object's type (class) (Refer: type_checks.py)

>>> a = 5
>>> type(a)
<type 'int'>
>>> c = 2 + 5j
>>> type(c)
<type 'complex'>

2015 Siemens Industry, Inc., Siemens Power Technologies


>>>

isinstance() is usually the better function to use and tells if object is


an instance of a given class or of a class derived from that class
>>> a = 5

International (Siemens PTI)


>>> b = isinstance(a,int) # returns True
>>> b = isinstance(a,float) # returns False

Page 2-14 Siemens Power Academy TD-NA PSSE - Python Course


Object Attributes and Methods

In Python, everything is an object


Objects have methods and attributes
Examples: complex and string objects

a = 5 + 7j # A complex number
r = a.real # Get the real part
i = a.imag # Get the imaginary part

2015 Siemens Industry, Inc., Siemens Power Technologies


s = 'bus 101' # A string object
t = s.upper() # t = 'BUS 101'

Note: In PSS®E, MW and MVAR are often returned as a complex pq;


which can be accessed this way: p=pq.real and q=pq.imag.

International (Siemens PTI)


Page 2-15 Siemens Power Academy TD-NA PSSE - Python Course
Python Strings

There are multiple ways to declare a string literal in Python

# single quotes: # triple single quotes:


s = 'A string' t = '''A string'''
u = '''This is
# double quotes:
a multi-line string'''

2015 Siemens Industry, Inc., Siemens Power Technologies


s = "A string"

# double and single quotes: # triple double quotes:


s = "A 'string'" t = """A string"""
u = """This is

International (Siemens PTI)


a multi-line string"""

Page 2-16 Siemens Power Academy TD-NA PSSE - Python Course


Some String Operations

Concatenation ("addition"):

s = 'abcd' + 'efgh' # s = 'abcdefgh'


t = 'bus ' + str(576132) # t = 'bus 576132'

Replication ("multiplication"):

u = '-' * 10 # u = '----------'

2015 Siemens Industry, Inc., Siemens Power Technologies


Indexing:

x = s[1] # x = 'b'

International (Siemens PTI)


Slicing:

y = s[2:5] # y = 'cde'

Page 2-17 Siemens Power Academy TD-NA PSSE - Python Course


Some String Methods

Python strings have many methods:

s.isupper() s.lower() s.strip(charstring)


s.islower() s.upper() s.replace(charstring)
s.isalpha() s.swapcase() s.center(10)
s.isdigit() s.title() s.split(separator)
s.isalnum() s.find(substring) s.join(listofstrings)
s.index(substring) s.format(variables)

Examples

2015 Siemens Industry, Inc., Siemens Power Technologies


'abcxyz'.find('xyz') # 3
' abcxyz '.strip() # 'abcxyz'
'{0} + {1} = {2}'.format(2, 3, 5) # '2 + 3 = 5'

International (Siemens PTI)


For a complete list, use the help function (help(str) ) or go to
python.org (https: //docs.python.org/3/library)

Refer: string_methods.py
Page 2-18 Siemens Power Academy TD-NA PSSE - Python Course
Adding Comments

A hash character (#) and anything following it is taken to be a


comment.

# this entire line is a comment


area = 17 # this comment follows some code

2015 Siemens Industry, Inc., Siemens Power Technologies


A hash character appearing in a quoted string is not interpreted as a
comment.

print('This # is not a comment') # but this is

International (Siemens PTI)


Page 2-19 Siemens Power Academy TD-NA PSSE - Python Course
Commenting with Strings

A python string does not have to be assigned to a variable

'This unassigned string is treated as a comment.'

'''This multi-line unassigned string might contain


commented-out code or a long section of documentation
for a module, function, or class. '''

2015 Siemens Industry, Inc., Siemens Power Technologies


1. Can be used to "comment out" long sections of code
2. Also used for documenting the code (via the help()function)
3. The created strings will be garbage-collected and not affect
memory

International (Siemens PTI)


Page 2-20 Siemens Power Academy TD-NA PSSE - Python Course
tuple

A python tuple is an "ordered sequence" of things.


Defined with commas and/or parentheses.
Contents of a tuple cannot change

tup1 = () # an empty tuple, doesn't need a comma


tup2 = (55,) # comma is important, without comma integer
tup3 = (5, 8, 'with parentheses' , 628.7)
tup4 = 5, 8, 'no parentheses' , 628.7
tup5 = (a, [1, 2, 3], 'AREA' , (7, 8, 9.1))

2015 Siemens Industry, Inc., Siemens Power Technologies


tup6 = (x, y, z) # packing
(a, b, c) = tup6 # unpacking
(a, b, c) = (x, y, z) # implicit unpacking/repacking

Functions can return multiple values as a tuple of values:

International (Siemens PTI)


rtple = psspy.busint(bus, 'AREA')
ierr, bus_area = psspy.busint(bus, 'AREA')
ierr, (number,) = psspy.abusint(string='NUMBER') # note length-1 tuple
ierr, (base, pu) = psspy.abusreal(string=['BASE', 'PU'])

Page 2-21 Siemens Power Academy TD-NA PSSE - Python Course


list

A python list is an "ordered sequence" of things.


Defined with [square brackets] and commas,
The contents of a list can be change

lst1 = [] # an empty list


lst2 = [5] # length 1
lst3 = [5, 8, 'with parentheses', 628.7] # mixed types
lst4 = [a, [1, 2, 3], 'AREA' , (7, 8, 9.1)] # nested

2015 Siemens Industry, Inc., Siemens Power Technologies


lists are mutable (can be modified):

a = [1, 2, 3] # a = [1, 2, 3] (init)

International (Siemens PTI)


a.append(4) # a = [1, 2, 3, 4] (append)
a.insert(0, 99) # a = [99, 1, 2, 3, 4] (insert)
a[0] = 77 # a = [77, 1, 2, 3, 4] (set)
del a[0] # a = [1, 2, 3, 4] (delete)

Page 2-22 Siemens Power Academy TD-NA PSSE - Python Course


list Methods and Operators

x = [3, 2, 3, 4]

x.append(7) # x = [3, 2, 3, 4, 7]
x.insert(0, 8) # x = [8, 3, 2, 3, 4, 7]
x.extend([5, 6]) # x = [8, 3, 2, 3, 4, 7, 5, 6]
x.remove(3) # x = [8, 2, 3, 4, 7, 5, 6]
Y = x.pop(4) # x = [8, 2, 3, 4, 5, 6] # returns y = 7
x.sort() # x = [2, 3, 4, 5, 6, 8] # in place!

2015 Siemens Industry, Inc., Siemens Power Technologies


x.reverse() # x = [8, 6, 5, 4, 3, 2] # in place!
c = x.count(3) # returns c = 1
i = x.index(4) # returns i =3

x + [9, 10] # x = [8, 6, 5, 4, 3, 2, 9, 10] (concat)

International (Siemens PTI)


x = x[:2] # x = [8, 6] (slice)
x * 3 # x = [8, 6, 8, 6, 8, 6] (replicate)
8 in x # True (in operator)
del x[4:] # x = [8, 6, 8] (delete slice)

Page 2-23 Siemens Power Academy TD-NA PSSE - Python Course


list Methods and Operators (cont.)

Difference between remove, del and pop :

x = [5, 2, 3, 4, 3, 0]

x.remove(3) # removes the first “3” in the list


# x = [5, 2, 4, 3, 0]

del x[1] # removed 2nd list item

2015 Siemens Industry, Inc., Siemens Power Technologies


# x = [5, 4, 3, 0]

a = x.pop(2) # returns 3rd list item and remove from list


# x = [5, 4, 0] and a = 3

International (Siemens PTI)


Page 2-24 Siemens Power Academy TD-NA PSSE - Python Course
Type checking with list and tuple

These names can be used for type checking

with the type() function

if type(x) == list:
# do something
elif type(x) == tuple:

2015 Siemens Industry, Inc., Siemens Power Technologies


# do something

Note: type checking is typically unpythonic

International (Siemens PTI)


Page 2-25 Siemens Power Academy TD-NA PSSE - Python Course
Converting a Sequence into a list or tuple

list() returns a list given a sequence.

x = list((1, 2, 3, 4, 5)) # x is [1, 2, 3, 4, 5]

y = list('abcd') # y is ['a', 'b', 'c', 'd']

tuple() returns a tuple given a sequence.

2015 Siemens Industry, Inc., Siemens Power Technologies


x = tuple([1, 2, 3, 4, 5]) # x is (1, 2, 3, 4, 5)

y = tuple('abcd') # y is ('a', 'b', 'c', 'd')

International (Siemens PTI)


Note: strings are sequences

Page 2-26 Siemens Power Academy TD-NA PSSE - Python Course


Sequence-related Python Functions

y = (3, 2, -3, 4, 0)

len(y) # Returns 5
min(y) # Returns -3
max(y) # Returns 4
sum(y) # Returns 6
sorted(y) # y = [-3, 0, 2, 3, 4]

2015 Siemens Industry, Inc., Siemens Power Technologies


reversed(y) # Returns an iterator in revered order
any(y) # True (have non-zeros/Trues)
all(y) # False (not all non-zero/True)

International (Siemens PTI)


Page 2-27 Siemens Power Academy TD-NA PSSE - Python Course
Converting a Sequence into a String

str() also returns a string given a sequence


…but may not do what you want or expect

x = str([1, 2, 3]) # x is '[1, 2, 3]'


y = str((1, 2, 3)) # y is '(1, 2, 3)'
z = str(['a', 'b', 'c']) # z is "['a', 'b', 'c']"

2015 Siemens Industry, Inc., Siemens Power Technologies


What you probably want: to specify a “joiner” string and use its
join() method to join a list of strings

s = '-'.join(['a', 'b', 'c']) # s = 'a-b-c'

International (Siemens PTI)


Page 2-28 Siemens Power Academy TD-NA PSSE - Python Course
Indexing in Sequences

Indexing is accomplished using square brackets.


Indexing starts at 0.

0 1 2 positive (from beginning)


-3 -2 -1 negative (from end)
x = [222, 111, 333]

Retrieval

2015 Siemens Industry, Inc., Siemens Power Technologies


print(x[1]) # prints 111
print(x [-1]) # prints 333

Assignment

International (Siemens PTI)


x [0] = 444 # Change element 0
x [-2] = 555 # Change element 1
print(x) # prints [444, 555, 333]

Page 2-29 Siemens Power Academy TD-NA PSSE - Python Course


Slicing a Sequence

Slice indices: start, stop, and an optional step.


Slicing selects up to, but not including, the stop index.
0 1 2 3 4
-5 -4 -3 -2 -1
x = ['Arthur', 'D.W.', 'Buster', 'Muffy', 'Francine']

print(x[1:2]) # ['D.W. ']


print(x[2:4]) # ['Buster', 'Muffy ']

2015 Siemens Industry, Inc., Siemens Power Technologies


print(x[:3]) # ['Arthur', 'D.W.', 'Buster ']
print(x[2:]) # ['Buster', 'Muffy', 'Francine ']
print(x[-3:]) # ['Buster', 'Muffy', 'Francine ']
print(x[1:-1:2]) # ['D.W.', 'Muffy ']
print(x[::-2]) # ['Francine', 'Buster', 'Arthur ']

International (Siemens PTI)


y = x[:] # creates a new list (copy)
z = x # doesn't create a new list (reference)

Page 2-30 Siemens Power Academy TD-NA PSSE - Python Course


Python Exercise 1: String Slicing

Given the string:

s = ‘Insert a number ## here!’


# 0 1 2
# 012345678901234567890123

use slicing to insert the integer ‘12’ at string positions 16-17

2015 Siemens Industry, Inc., Siemens Power Technologies


s1 = s[:16] + str(12) + s[18:]

International (Siemens PTI)


Page 2-31 Siemens Power Academy TD-NA PSSE - Python Course
Python Exercise 2: String Slicing

Given the string:

'[NUC-A 21.600]'

use slicing or string methods to:


a) Retrieve the bus name
b) Retrieve the bus kV base (string) and convert it to float

2015 Siemens Industry, Inc., Siemens Power Technologies


Indexing clarification: Python indexing starts with 0

International (Siemens PTI)


The 1st character is character number 0.
Character number 9 is the 10th character.

Page 2-32 Siemens Power Academy TD-NA PSSE - Python Course


Python Exceptions

Python raises an "exception" when there is an error.

x = 13.3 / 0.0 # ZeroDivisionError

The traceback shows where and what:

Traceback (most recent call last):

2015 Siemens Industry, Inc., Siemens Power Technologies


File "<pyshell#12>", line 1, in -toplevel-
x= 13.3/0.0
ZeroDivisionError: float division

This traceback message is useful for debugging code.

International (Siemens PTI)


We will learn to handle (intercept) exceptions later.
For now, we rely on the default handler's message.

Page 2-33 Siemens Power Academy TD-NA PSSE - Python Course


Dictionaries

A python dictionary maps keys to values (objects)


Defined by {braces}
Contents can change, but are unordered
Dictionaries are easier and more useful than you think

dict0 = {} # an empty dictionary


dict1 = {'abc':13, 'xyz':25}

2015 Siemens Industry, Inc., Siemens Power Technologies


A key can be any immutable object.
(Must be hashable (able to map) too.)

dict2 = {'N':7, (200, 310, '1'):'N.Sub', 100:3.0}

International (Siemens PTI)


dict2 ['N'] # 7
dict2 [100] # 3.0
dict2 [(200, 310, '1')] # 'N.Sub'

Page 2-34 Siemens Power Academy TD-NA PSSE - Python Course


Examples of Dictionaries

# Bus voltage look-up table # Binary to decimal


# busnum:voltage # lookup-table
# (bits):value
busvolts = { 101 : 1.036,
151 : 0.988, bits2bytes = { (0,0,0) : 0,
154 : 1.063 } (0,0,1) : 1,
(0,1,0) : 2,
print busvolts [101] # Get (0,1,1) : 3,

2015 Siemens Industry, Inc., Siemens Power Technologies


(1,0,0) : 4,
busvolts [151] = 0.95 # Set (1,0,1) : 5,
(1,1,0) : 6,
busvolts [152] = 1.01 # Add new (1,1,1) : 7 }

International (Siemens PTI)


del busvolts [154] # Delete digit = bits2bytes [(1,0,1)]

Page 2-35 Siemens Power Academy TD-NA PSSE - Python Course


Ordered Dictionaries

A python dictionary that remembers insertion order, i.e., the order of


the key:value pairs added to this dictionary

How to create ordered dictionary? Ordinary dictionary:

>>> import collections >>> d2 = {}


>>> d1 = collections.OrderedDict() >>> d2[1] = 1
>>> d1[1] = 1 >>> d2[2] = 2
>>> d1[2] = 2 >>> d2[11] = 11
>>> d1[11] = 11 >>> d2[12] = 12

2015 Siemens Industry, Inc., Siemens Power Technologies


>>> d1[12] = 12 >>> d2[3] = 3
>>> d1[3] = 3 >>> d2[4] = 4
>>> d1[4] = 4 >>> d2
>>> d1 {1: 1, 2: 2, 3: 3, 4: 4,
OrderedDict([(1, 1), (2, 2), (11, 11), 11: 11, 12: 12}

International (Siemens PTI)


(12, 12), (3, 3), (4, 4)]) >>> d2.keys()
>>> d1.keys() [1, 2, 3, 4, 11, 12]
[1, 2, 11, 12, 3, 4]

Page 2-36 Siemens Power Academy TD-NA PSSE - Python Course


Dictionary Methods

Commonly-used methods of dictionaries:

busnames = {101:'abc' ,102:'pqr' ,103:'xyz'}

k = busnames.keys() # [103, 101, 102]


# not necessarily the same order!
v = busnames.values() # ['pqr', 'abc', 'xyz']
pairs = busnames.items() # [(103, 'xyz'),
# (101, 'abc'),

2015 Siemens Industry, Inc., Siemens Power Technologies


# (102, 'pqr')]

for k, v in busnames.iteritems():# returns an iterator


print k, v

International (Siemens PTI)


h = busnames.has_key(102) # True
h = 102 in busnames # True

Refer: lists_tuples_dictionaries.py

Page 2-37 Siemens Power Academy TD-NA PSSE - Python Course


True/False Value Testing

Most built-in objects can be tested for True/False status,


for use in an conditional expression (if, while)
or as operand of a Boolean operation (and, or, not)

The following values evaluate to False:

None
False

2015 Siemens Industry, Inc., Siemens Power Technologies


zero of any numeric type, for example: 0, 0L, 0.0, 0j
any empty sequence, for example: '', (), []
any empty mapping, for example: {}

To check, use the bool() function, e.g. bool('hello')

International (Siemens PTI)


Page 2-38 Siemens Power Academy TD-NA PSSE - Python Course
Python Programming: Line-continuation Character

Line-continuation character:
x = variable1 * variable2 + variable3 \
+ variable4 + a + lot + of + other \
+ variables inside * this / run-on \
* equation

x = (variable1 * variable2 + variable3 +


variable4 + a + lot + of + other +
variables inside * this / run-on * Better

2015 Siemens Industry, Inc., Siemens Power Technologies


equation)

Rarely needed and discouraged (hard to read). Python already


handles multi-line statements code enclosed by:
(Parentheses) tuples, function arguments, grouping

International (Siemens PTI)


[Brackets] lists, array indexing
{Braces} dictionaries
'''Triple-quotes ''' multi-line strings

Page 2-39 Siemens Power Academy TD-NA PSSE - Python Course

You might also like