Differences between revisions 1 and 2
Revision 1 as of 2024-12-04 14:47:41
Size: 12567
Editor: mark
Comment:
Revision 2 as of 2024-12-04 15:43:55
Size: 14733
Editor: mark
Comment:
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:
Line 4: Line 3:
 The aims of  this practical are two-fold: firstly to introduce you to the different  ways in which data is represented in python, and, in the second part  how to use python to manipulate data covering most of the material in  the previous lecture. This practical is not about modelling ''per se'', but the material here is an essential pre-requisite for the modelling practicals that follow. The aims of this practical are two-fold: firstly to introduce you to the different ways in which data is represented in python, and, in the second part how to use python to manipulate data covering most of the material in the previous lecture. This practical is not about modelling ''per se'', but the material here is an essential pre-requisite for the modelling practicals that follow.
Line 7: Line 6:
 Having  started ScrumPy, read the tutorial material below, and then replicate  the python examples in the ScrumPy command window (don't copy and  paste!).

It  is important that you understand what each of these examples is doing,  it's not enough to simply reproduce the ouptut shown here on your own  laptop screens! You should therefore test this by modifying some of  these examples - you should be able to correctly predict the effects of  these modifications, and if not then explain why not.

'''Note: '''In  the examples below we will be using python interactively. In this case  ">>>" represents the python prompt which tells you that  python is ready for you to type something, not something that you  should type.To do the excersises type in the text following the prompt  and fit the return key.
Having started !ScrumPy, read the tutorial material below, and then replicate the python examples in the !ScrumPy command window (don't copy and paste!).

It is important that you understand what each of these examples is doing, it's not enough to simply reproduce the ouptut shown here on your own laptop screens! You should therefore test this by modifying some of these examples - you should be able to correctly predict the effects of these modifications, and if not then explain why not.

'''Note: '''In the examples below we will be using python interactively. In this case ">>>" represents the python prompt which tells you that python is ready for you to type something, not something that you should type.To do the excersises type in the text following the prompt and fit the return key.
Line 14: Line 13:
 Data can be  as simple as a single digit, or as complex as a suite of genome  databases. Python comes with a number of relatively simple data-types,  but as we will see, these can be combined to build a python  representation of whatever it is that we are studying. The purpose of  ScrumPy is to define such collections of simple data-types in a defined  way (a ''data-structure'') particularly useful for metabolic  modelling, and routines that act upon them. We will start by examining  some of the common built-in types.The complete, official python  documentation can be found [[https://docs.python.org/3/library/stdtypes.html|here]], although you might find some of it a bit technical, and it goes beyond what is needed for this course. Data can be as simple as a single digit, or as complex as a suite of genome databases. Python comes with a number of relatively simple data-types, but as we will see, these can be combined to build a python representation of whatever it is that we are studying. The purpose of !ScrumPy is to define such collections of simple data-types in a defined way (a ''data-structure'') particularly useful for metabolic modelling, and routines that act upon them. We will start by examining some of the common built-in types.The complete, official python documentation can be found [[https://docs.python.org/3/library/stdtypes.html|here]], although you might find some of it a bit technical, and it goes beyond what is needed for this course.
Line 17: Line 16:
 Simply typing a value at the prompt causes it to be printed on the screen:

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
Simply typing a value at the prompt causes it to be printed on the screen:

{{{#!python
>>> "Hello"
'Hello'
Line 23: Line 24:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
Finally,  if we use the built in "print" function, this will also cause the  value to be printed on the screen. For some data the two methods may  result in a different represesentation of the same value:

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
{{{#!python

>>> Greet = "Hello"
>>> Greet
'Hello'

}}}
Finally, if we use the built in "print" function, this will also cause the value to be printed on the screen. For some data the two methods may result in a different represesentation of the same value:

{{{#!python
>>> print(Greet)
Hello
Line 32: Line 39:
Line 34: Line 40:
 Booleans  are used to indicate whether or not something is considered true, and  can take one of exactly two values, True or False, they can be  generated explicitly, or as the result of a comparison:

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
Booleans are used to indicate whether or not something is considered true, and can take one of exactly two values, True or False, they can be generated explicitly, or as the result of a comparison:

{{{#!python
>>> val=True
>>> val
True
>>> 3>=4
False
>>> val = 3==4
>>> val
False
Line 41: Line 55:
 Python has  three built in ways of defining numbers: integer, floating point and  complex numbers although are not relevant to this course.

'''Integers'''  are whole, or counting, numbers and can be either positive or  negative, they are represented as a sequence of digits which contains  no other characters. Floating-point, or real, numbers contain a  fractional component followng a decimal point. They can also be  represented using the "e" notation, common to many other languages  which represents "times 10 to the power of".

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
The common mathematical operators ({{{+,-,/,*}}}) work as expected, note that {{{x**y}}} means ''x''^y^.  Numbers can also be compared using the common == (is equal), != (is  not equal), < (is less than), <= (is less than or equal to), >  (is greater than) and >= (is greater than or equal to). Some of  these operators can also be used with other types of data.
Python has three built in ways of defining numbers: integer, floating point and complex numbers although are not relevant to this course.

'''Integers''' are whole, or counting, numbers and can be either positive or negative, they are represented as a sequence of digits which contains no other characters. Floating-point, or real, numbers contain a fractional component followng a decimal point. They can also be represented using the "e" notation, common to many other languages which represents "times 10 to the power of".

{{{#!python
>>> Count = 135
>>> Count
135
>>> Pi = 3.1415926
>>> Pi
3.1415926
>>> VeryBig = 1.1e16
>>> VeryBig
1.1e+16
>>> VerySmall = 1/VeryBig
>>> print(VerySmall)
9.090909090909091e-17

}}}
The common mathematical operators ({{{+,-,/,*}}}) work as expected, note that {{{x**y}}} means ''x''^y^. Numbers can also be compared using the common == (is equal), != (is not equal), < (is less than), <= (is less than or equal to), > (is greater than) and >= (is greater than or equal to). Some of these operators can also be used with other types of data.
Line 53: Line 79:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> 1+VerySmall >1
Line 58: Line 85:
 Strings are sequences of characters and used to represent arbitrary text.They  are found surrounded by quotation marks ( ' ) or double quotation marks (  " ).

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
<<Anchor(String)>>Strings are sequences of characters and used to represent arbitrary text.They are found surrounded by quotation marks ( ' ) or double quotation marks ( " ).

{{{#!python
>>> SomeString = 'Hello'
>>> print(SomeString)
Hello
Line 64: Line 94:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> SomeString = 'Hello'
>>> SomeString[0]
'H'
>>> SomeString[1]
'e'
>>> SomeString[-1]
'o'
Line 68: Line 105:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> SomeString = 'Hello'
>>> SomeString.upper() # this function returns a string which is identical to SomeString except that all of the characters are capitalized
'HELLO'
>>> SomeString.startswith('H') # this function returns 'True' if the first character in SomeString is an 'H' and False otherwise
True
>>> SomeString.startswith('a') # this function returns 'True' if the first character in SomeString is an 'a' and False otherwise
False
>>> SomeString.startswith('h') # this function returns 'True' if the first character in SomeString is an 'h' and False otherwise
False
>>> SomeString.endswith('o') # this function returns 'True' if the last character in SomeString is an 'o' and False otherwise
True
Line 71: Line 119:
 The type of each object defines what operations can be performed on it.  For example, the numeric data-types (like integers and floats) can  undergo numerical operations, such as subtraction and multiplication,  whilst strings cannot. <<Anchor(Types)>> The type of each object defines what operations can be performed on it. For example, the numeric data-types (like integers and floats) can undergo numerical operations, such as subtraction and multiplication, whilst strings cannot.
Line 75: Line 123:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
The print() function can be used to print different objects within the same text. This can be done by separating each object with a comma.

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
{{{#!python
>>> SomeString = 'Hello'
>>> SomeInteger = 5
>>> SomeFloat = 5.2548
>>> type(SomeString)
<class 'str'>
>>> type(SomeInteger)
<class 'int'>
>>> type(SomeFloat)
<class 'float'>
}}}
The print() function can be used to print different objects within the same text. This can be done by separating each object with a comma.

{{{#!python
>>> ChildName = 'Sam'
>>> ChildAge = 5
>>> print(ChildName, 'is', ChildAge, 'years-old')
Sam is 5 years-old
Line 82: Line 143:
 Lists and tuples are collections of items in which are stored in a specific  order and each item is associated with (indexed by) an integer. The  main difference between the two is that tuples are ''immutable'' -  once a tuple is created it cannot be changed, whereas lists can. For  these exercises we will mainly use lists. An empty list can be created  by assigning a pair of closed square brackets to a variable.

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
<<Anchor(List)>>Lists and tuples are collections of items in which are stored in a specific order and each item is associated with (indexed by) an integer. The main difference between the two is that tuples are ''immutable'' - once a tuple is created it cannot be changed, whereas lists can. For these exercises we will mainly use lists. An empty list can be created by assigning a pair of closed square brackets to a variable.

{{{#!python
>>> SomeList=[]
Line 88: Line 150:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> SomeList.append('string 1')
>>> SomeList
['string 1']
Line 92: Line 157:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> SomeList=['string 1']
>>> SomeList
['string 1']
Line 96: Line 164:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
 . '''Question:''' What is the item at SomeList[-2] ? SomeList[-4] ?
{{{#!python
>>> SomeList = ['string 1','string 2','string 3']
>>> SomeList[0]
'string 1'
>>> SomeList[1]
'string 2'
>>> SomeList[2]
'string 3'
>>> SomeList[-1]
'string 3'
}}}
 . '''Question:''' What is the item at !SomeList[-2] ? !SomeList[-4] ?
Line 103: Line 180:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>>SomeList[1:3]
['string 2', 'string 3']
Line 107: Line 186:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> SomeList.index('string 2')
1
Line 112: Line 193:
 [[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{  {{{#!python
>>> SomeList.remove('string 1')
>>> SomeList
['string 2', 'string 3']
Line 116: Line 200:
  . Lists can contain any objects, including other lists. These lists are referred to as ''nested'':

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
 . Lists can contain any objects, including other lists. These lists are referred to as ''nested'':

{{{#!python
>>> SomeList = ['string 1','string 2','string 3']
>>> nested = [1,2,3]
>>> SomeList.append(nested)
>>> SomeList
['string 1', 'string 2', 'string 3', [1, 2, 3]]
>>> SomeList[3]
[1, 2, 3]
>>> SomeList[3][0]
1
Line 125: Line 218:
 Tuples are  very similar to lists, but with one important difference: ince a tuple  is defined its contents cannot be changed, they are ''immutable. ''Tuples are created in a in the same way as lists, excet the round brackets "()", rather than square brackets "[ ]" are used.

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
Tuples are very similar to lists, but with one important difference: ince a tuple is defined its contents cannot be changed, they are ''immutable. ''Tuples are created in a in the same way as lists, excet the round brackets "()", rather than square brackets "[ ]" are used.

{{{#!python

>>> SomeTuple = ("Item 1", "Item 2", "Item 3")
Line 132: Line 227:
  . .  Conceptually, dictionaries are quite similar to lists and tuples in  that they contain collections of items, however, what makes them  distinct is the fact that instead of using integers to refer to items  (almost) anything can be used to refer to what is contained, this alos  means that, incontrast to lists and tuples there is no implicit order of  the items stored in a dictionary. The hace that we can use (almos)t  anything to refer to an item gives great flexibilty; dictionaries and  "dictianary-like" classes are used extensively in ScrumPy. Dictionaries  are created by specifying a sequence of key:value pairs inside a pair  of braces "{}":

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
 . <<Anchor(Dictionary)>>. Conceptually, dictionaries are quite similar to lists and tuples in that they contain collections of items, however, what makes them distinct is the fact that instead of using integers to refer to items (almost) anything can be used to refer to what is contained, this alos means that, incontrast to lists and tuples there is no implicit order of the items stored in a dictionary. The hace that we can use (almos)t anything to refer to an item gives great flexibilty; dictionaries and "dictianary-like" classes are used extensively in !ScrumPy. Dictionaries are created by specifying a sequence of key:value pairs inside a pair of braces "{}":

{{{#!python
>>> dict_1 = {'alfa':1,'beta':2} #create a dictionary
>>> print(dict_1)
{'beta': 2, 'alfa': 1}
>>> dict_1['alfa'] #access value '1' by key 'alfa'
1
>>> dict_1['gamma'] = 1 #add new key:value pair
>>> dict_1['alfa'] = 'a' #overwrite key:value pair
Line 140: Line 242:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> dict_1 = {'alfa':1,'beta':2} #define first dictionary
>>> dict_2 = {'gamma':1} #define second dictionary
>>> dict_1['nested'] = dict_2 #add dict_2 as value to key 'nested' in dict_1
>>> dict_1
{'beta': 2, 'alfa': 1, 'nested': {'gamma': 1}}
>>> dict_1['nested']['gamma'] #access key 'gamma' in nested dictionary
1
Line 143: Line 252:
Line 145: Line 253:
Line 147: Line 254:
 The {{{for}}} loop is used to iterate over an iterable object, e.g. a list. Depending on how the loop is formulated the loop variable will either be an item in the iterable object or an index.

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
<<Anchor(Loop)>>The {{{for}}} loop is used to iterate over an iterable object, e.g. a list. Depending on how the loop is formulated the loop variable will either be an item in the iterable object or an index.

{{{#!python
>>> a_list = ['a','b','c']
>>> for item in a_list: #iterating over the items
        print (item)
a
b
c
}}}
{{{#!python
>>> a_list = ['a','b','c']
>>> for i in range(len(a_list)): #iterating over indices
        print (a_list[i])

a
b
c
Line 158: Line 278:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
 . This implies that if the condition {{{i<len(a_list)}}} is never fulfilled the loop continues indefinitely, which it will. Loops can be combined with ''conditional'' statements, where a block of code is executed {{{if}}} a statement is true, {{{else}}} another block is executed. The {{{else}}} block is optional, but must be the last option and no statement may follow on the same line.

[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
{{{#!python
>>> a_list =
['a','b','c']
>>> i = 0 #assign value 0 to variable i
>>> while i<len(a_list): #as long as i is less than 3
        print (a_list
[i]) #print item at index i in a_list
        i += 1 #increment i
by 1

a
b
c

}}}
 . This implies that if the condition {{{i<len(a_list)}}} is never fulfilled the loop continues indefinitely, which it will. <<Anchor(Conditional)>>Loops can be combined with ''conditional'' statements, where a block of code is executed {{{if}}} a statement is true, {{{else}}} another block is executed. The {{{else}}} block is optional, but must be the last option and no statement may follow on the same line.

{{{#!python
>>> a_list =
['a',1,'c',2]
>>> for item in a_list
:
        if type(item)==type(str()): #chec
k if item is of string type
            print (item+' is a string')
        else: #if not
...
            print (str(item)+' is not a str
ing')

'a is a str
ing'
'1 is not a string'
'c is a string'
'
2 is not a string'
Line 166: Line 306:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> for item in a_list:

        if type(item)==type(str()):
            print (item+' is a string')
        elif type(item)==type(int()):
            print (str(item)+' is an int')
        else:
            print (str(item)+' is unkown')

'a is a string'
'1 is an int'
'c is a string'
'2 is an int'
Line 169: Line 322:
 '''Loops and Dictionaries''' '''Loops and Dictionaries'''
Line 173: Line 326:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
{{{#!python
>>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
>>> for key in dict_1: #iterate over the keys
        print (key)

alfa
beta
gamma
}}}
{{{#!python
>>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
>>> for key in dict_1: #iterate over the keys
        print ('the key', key, 'has value', dict_1[key]) # this print statement executes if either key.endsswith('a') is True or if key.startswith('b') is True or both are True

the key alfa has value 1
the key beta has value 2
the key gamma has value 3
Line 181: Line 348:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{ {{{#!python
>>> string_1 = 'alfa'
>>> string_1.startswith('a') # this function returns 'True' if string_1 starts with an 'a' and False otherwise
True
>>> string_1.startswith('b')
False
>>> string_1.startswith('A')
False
Line 185: Line 359:
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
[[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2#|Toggle line numbers]] {{{
}}}
None: Meetings/Nottingham2022/Prac2 (last edited 2024-09-10 14:18:21 by [[https://mudshark.brookes.ac.uk/trunil|trunil]])

   * [[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2?action=edit&editor=text|Edit (Text)]]
 * [[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2?action=edit&editor=gui|Edit (GUI)]]
 * [[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2?action=info|Info]]
 * [[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2?action=quicklink|Add Link]]
 * [[https://mudshark.brookes.ac.uk/Meetings/Nottingham2022/Prac2?action=AttachFile|Attachments]]
 *

 *

 * [[http://moinmo.in/|MoinMoin Powered]]
 * [[http://moinmo.in/Python|Python Powered]]
 * [[http://moinmo.in/GPL|GPL licensed]]
 * [[http://validator.w3.org/check?uri=referer|Valid HTML 4.01]]
{{{#!python
>>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
>>> for key in dict_1: #iterate over the keys
        if key.startswith('a'):
            print (key) # this print statement executes if key.startswith('a') is True

alfa
}}}
{{{#!python
>>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
>>> for key in dict_1: #iterate over the keys
        if key.startswith('a') or key.startswith('b'):
            print ('the key', key, 'has value', dict_1[key]) # this print statement executes if either key.endsswith('a') is True or if key.startswith('b') is True or both are True

the key alfa has value 1
the key beta has value 2
}}}

Practical 2: Common Python Data Structures and Functions

Introduction/Aims of this practical

The aims of this practical are two-fold: firstly to introduce you to the different ways in which data is represented in python, and, in the second part how to use python to manipulate data covering most of the material in the previous lecture. This practical is not about modelling per se, but the material here is an essential pre-requisite for the modelling practicals that follow.

Instructions

Having started ScrumPy, read the tutorial material below, and then replicate the python examples in the ScrumPy command window (don't copy and paste!).

It is important that you understand what each of these examples is doing, it's not enough to simply reproduce the ouptut shown here on your own laptop screens! You should therefore test this by modifying some of these examples - you should be able to correctly predict the effects of these modifications, and if not then explain why not.

Note: In the examples below we will be using python interactively. In this case ">>>" represents the python prompt which tells you that python is ready for you to type something, not something that you should type.To do the excersises type in the text following the prompt and fit the return key.

Part 1: How data is represented in Python

Data can be as simple as a single digit, or as complex as a suite of genome databases. Python comes with a number of relatively simple data-types, but as we will see, these can be combined to build a python representation of whatever it is that we are studying. The purpose of ScrumPy is to define such collections of simple data-types in a defined way (a data-structure) particularly useful for metabolic modelling, and routines that act upon them. We will start by examining some of the common built-in types.The complete, official python documentation can be found here, although you might find some of it a bit technical, and it goes beyond what is needed for this course.

Viewing data

Simply typing a value at the prompt causes it to be printed on the screen:

   1 >>> "Hello"
   2 'Hello'

if we assign a value to a variable, then typing the variable name will cause the value of the variable to be printed:

   1 >>> Greet = "Hello"
   2 >>> Greet
   3 'Hello'

Finally, if we use the built in "print" function, this will also cause the value to be printed on the screen. For some data the two methods may result in a different represesentation of the same value:

   1 >>> print(Greet)
   2 Hello

Question: What is the difference between the two ways in which Greet is represented?

Primitive Data Types

Boolean

Booleans are used to indicate whether or not something is considered true, and can take one of exactly two values, True or False, they can be generated explicitly, or as the result of a comparison:

   1 >>> val=True
   2 >>> val
   3 True
   4 >>> 3>=4
   5 False
   6 >>> val = 3==4
   7 >>> val
   8 False

Question: Explain line 6 in the example above.

Numbers

Python has three built in ways of defining numbers: integer, floating point and complex numbers although are not relevant to this course.

Integers are whole, or counting, numbers and can be either positive or negative, they are represented as a sequence of digits which contains no other characters. Floating-point, or real, numbers contain a fractional component followng a decimal point. They can also be represented using the "e" notation, common to many other languages which represents "times 10 to the power of".

   1 >>> Count = 135
   2 >>> Count
   3 135
   4 >>> Pi = 3.1415926
   5 >>> Pi
   6 3.1415926
   7 >>> VeryBig = 1.1e16
   8 >>> VeryBig
   9 1.1e+16
  10 >>> VerySmall = 1/VeryBig
  11 >>> print(VerySmall)
  12 9.090909090909091e-17

The common mathematical operators (+,-,/,*) work as expected, note that x**y means xy. Numbers can also be compared using the common == (is equal), != (is not equal), < (is less than), <= (is less than or equal to), > (is greater than) and >= (is greater than or equal to). Some of these operators can also be used with other types of data.

Question:

Consider the expression:

   1 >>> 1+VerySmall >1

Explain (to yourself) the syntax of this. What type will the expression evaluate to? What value do you expect? Now try it out.

Strings

Strings are sequences of characters and used to represent arbitrary text.They are found surrounded by quotation marks ( ' ) or double quotation marks ( " ).

   1 >>> SomeString = 'Hello'
   2 >>> print(SomeString)
   3 Hello

The characters stored in the sequence are indexed by integers:

   1 >>> SomeString = 'Hello'
   2 >>> SomeString[0]
   3 'H'
   4 >>> SomeString[1]
   5 'e'
   6 >>> SomeString[-1]
   7 'o'

Common operations involving strings include the .upper(), .startswith(), and endswith() methods:

   1 >>> SomeString = 'Hello'
   2 >>> SomeString.upper() # this function returns a string which is identical to SomeString except that all of the characters are capitalized
   3 'HELLO'
   4 >>> SomeString.startswith('H') # this function returns 'True' if the first character in SomeString is an 'H' and False otherwise
   5 True
   6 >>> SomeString.startswith('a') # this function returns 'True'  if the first character in SomeString is an 'a' and False otherwise
   7 False
   8 >>> SomeString.startswith('h') # this function returns 'True' if the first character in SomeString is an 'h' and False otherwise
   9 False
  10 >>> SomeString.endswith('o') # this function returns 'True' if the last character in SomeString is an 'o' and False otherwise
  11 True

The type() function

The type of each object defines what operations can be performed on it. For example, the numeric data-types (like integers and floats) can undergo numerical operations, such as subtraction and multiplication, whilst strings cannot.

The type() function returns the type of an object:

   1 >>> SomeString = 'Hello'
   2 >>> SomeInteger = 5
   3 >>> SomeFloat = 5.2548
   4 >>> type(SomeString)
   5 <class 'str'>
   6 >>> type(SomeInteger)
   7 <class 'int'>
   8 >>> type(SomeFloat)
   9 <class 'float'>

The print() function can be used to print different objects within the same text. This can be done by separating each object with a comma.

   1 >>> ChildName = 'Sam'
   2 >>> ChildAge = 5
   3 >>> print(ChildName, 'is', ChildAge, 'years-old')
   4 Sam  is  5 years-old

Lists (and tuples)

Lists and tuples are collections of items in which are stored in a specific order and each item is associated with (indexed by) an integer. The main difference between the two is that tuples are immutable - once a tuple is created it cannot be changed, whereas lists can. For these exercises we will mainly use lists. An empty list can be created by assigning a pair of closed square brackets to a variable.

   1 >>> SomeList=[]
  • Items can be appended to a list by using the append() method.

   1 >>> SomeList.append('string 1')
   2 >>> SomeList
   3 ['string 1']
  • A list can also be created and populated in one go.

   1 >>> SomeList=['string 1']
   2 >>> SomeList
   3 ['string 1']

Or:

   1 >>> SomeList = ['string 1','string 2','string 3']
   2 >>> SomeList[0]
   3 'string 1'
   4 >>> SomeList[1]
   5 'string 2'
   6 >>> SomeList[2]
   7 'string 3'
   8 >>> SomeList[-1]
   9 'string 3'
  • Question: What is the item at SomeList[-2] ? SomeList[-4] ?

  • Indexing can be used to create a copy of part of a subset of a list, a process known as slicing.

   1 >>>SomeList[1:3]
   2 ['string 2', 'string 3']
  • The index of a known item can be retrieved using the index() method.

   1 >>> SomeList.index('string 2')
   2 1
  • .
    • Items can be removed from a list using the remove() method.

       1 >>> SomeList.remove('string 1')
       2 >>> SomeList
       3 ['string 2', 'string 3']
    

Nested lists:

  • Lists can contain any objects, including other lists. These lists are referred to as nested:

   1 >>> SomeList = ['string 1','string 2','string 3']
   2 >>> nested = [1,2,3]
   3 >>> SomeList.append(nested)
   4 >>> SomeList
   5 ['string 1', 'string 2', 'string 3', [1, 2, 3]]
   6 >>> SomeList[3]
   7 [1, 2, 3]
   8 >>> SomeList[3][0]
   9 1

Note the syntax of line 8 above.

Question: Explain the syntax of line 8 - how many ways are there to specify the item with the value of 3 using this notation?

Tuples

Tuples are very similar to lists, but with one important difference: ince a tuple is defined its contents cannot be changed, they are immutable. Tuples are created in a in the same way as lists, excet the round brackets "()", rather than square brackets "[ ]" are used.

   1 >>> SomeTuple = ("Item 1", "Item 2", "Item 3")

Exercise: Repeat the previous list examples with the tuple. What works and what doesnt? Explain.

Dictionaries

  • . Conceptually, dictionaries are quite similar to lists and tuples in that they contain collections of items, however, what makes them distinct is the fact that instead of using integers to refer to items (almost) anything can be used to refer to what is contained, this alos means that, incontrast to lists and tuples there is no implicit order of the items stored in a dictionary. The hace that we can use (almos)t anything to refer to an item gives great flexibilty; dictionaries and "dictianary-like" classes are used extensively in ScrumPy. Dictionaries are created by specifying a sequence of key:value pairs inside a pair of braces "{}":

   1 >>> dict_1 = {'alfa':1,'beta':2}  #create a dictionary
   2 >>>  print(dict_1)
   3 {'beta': 2, 'alfa': 1}
   4 >>> dict_1['alfa']                #access value '1' by key 'alfa'
   5 1
   6 >>> dict_1['gamma'] = 1          #add new key:value pair
   7 >>> dict_1['alfa'] = 'a'         #overwrite key:value pair
  • As with lists, dictionaries can be nested.

   1 >>> dict_1 = {'alfa':1,'beta':2} #define first dictionary
   2 >>> dict_2 = {'gamma':1}         #define second dictionary
   3 >>> dict_1['nested'] = dict_2    #add dict_2 as value to key 'nested' in dict_1
   4 >>> dict_1
   5 {'beta': 2, 'alfa': 1, 'nested': {'gamma': 1}}
   6 >>> dict_1['nested']['gamma']    #access key 'gamma' in nested dictionary
   7 1

Part 2: Loops and conditionals

Repetition

For loops

The for loop is used to iterate over an iterable object, e.g. a list. Depending on how the loop is formulated the loop variable will either be an item in the iterable object or an index.

   1 >>> a_list = ['a','b','c']
   2 >>> for item in a_list:       #iterating over the items
   3         print (item)
   4 a
   5 b
   6 c

   1 >>> a_list = ['a','b','c']
   2 >>> for i in range(len(a_list)):   #iterating over indices
   3         print (a_list[i])
   4 
   5 a
   6 b
   7 c
  • While loops
  • while loops continue repeating as long as some condition (the loop invariant) evaluates as True.

   1 >>> a_list = ['a','b','c']
   2 >>> i = 0                  #assign value 0 to variable i
   3 >>> while i<len(a_list):   #as long as i is less than 3
   4         print (a_list[i])  #print item at index i in a_list
   5         i += 1             #increment i by 1
   6 
   7 a
   8 b
   9 c
  • This implies that if the condition i<len(a_list) is never fulfilled the loop continues indefinitely, which it will. Loops can be combined with conditional statements, where a block of code is executed if a statement is true, else another block is executed. The else block is optional, but must be the last option and no statement may follow on the same line.

   1 >>> a_list = ['a',1,'c',2]
   2 >>> for item in a_list:
   3         if type(item)==type(str()):  #check if item is of string type
   4             print (item+' is a string')
   5         else:                        #if not...
   6             print (str(item)+' is not a string')
   7 
   8 'a is a string'
   9 '1 is not a string'
  10 'c is a string'
  11 '2 is not a string'
  • If several options are possible the elif statement can be used.

   1 >>> for item in a_list:
   2 
   3         if type(item)==type(str()):
   4             print (item+' is a string')
   5         elif type(item)==type(int()):
   6             print (str(item)+' is an int')
   7         else:
   8             print (str(item)+' is unkown')
   9 
  10 'a is a string'
  11 '1 is an int'
  12 'c is a string'
  13 '2 is an int'

Part 3: Some more examples

Loops and Dictionaries

Dictionaries can be iterated over in a similar way to how we can iterate through the items of a list.

   1 >>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
   2 >>> for key in dict_1:       #iterate over the keys
   3         print (key)
   4 
   5 alfa
   6 beta
   7 gamma

   1 >>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
   2 >>> for key in dict_1:       #iterate over the keys
   3         print ('the key', key, 'has value', dict_1[key]) # this print statement executes if either key.endsswith('a') is True or if key.startswith('b') is True or both are True
   4 
   5 the key alfa has value 1
   6 the key beta has value 2
   7 the key gamma has value 3

Filtering strings

Sometimes we might want to select strings that have certain attributes. Recall the .startswith() function:

   1 >>> string_1 = 'alfa'
   2 >>> string_1.startswith('a') # this function returns 'True' if string_1 starts with an 'a' and False otherwise
   3 True
   4 >>> string_1.startswith('b')
   5 False
   6 >>> string_1.startswith('A')
   7 False

This function, along with an if statement, can be used to specify which keys of a dictionary are printed.

   1 >>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
   2 >>> for key in dict_1:       #iterate over the keys
   3         if key.startswith('a'):
   4             print (key) # this print statement executes if key.startswith('a') is True
   5 
   6 alfa

   1 >>> dict_1 = {'alfa':1,'beta':2, 'gamma':3} #define a dictionary
   2 >>> for key in dict_1:       #iterate over the keys
   3         if key.startswith('a') or key.startswith('b'):
   4             print ('the key', key, 'has value', dict_1[key]) # this print statement executes if either key.endsswith('a') is True or if key.startswith('b') is True or both are True
   5 
   6 the key alfa has value 1
   7 the key beta has value 2

None: Meetings/Nottingham2024/Prac2 (last edited 2024-12-04 15:43:55 by mark)