Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore AS_Computing_AS_supplement.pdf

AS_Computing_AS_supplement.pdf

Published by michael.doherty, 2015-03-20 17:12:23

Description: AS_Computing_AS_supplement.pdf

Keywords: none

Search

Read the Text Version

AS Programming in Python Compuing An unoicial supplement to the book by Kevin Bond and Sylvia Langield



Input, assignment and output  Variables The generally accepted convenion for naming variables in Python is to use lowercase_separated_by_underscores. To disinguish them, UpperCamelCase is used for class names, and CAPITALIZED_WITH_UNDERSCORES for constants.  The assignment statement To assign a value to a variable an assignment statement is used number1 = 7 sum = number1 + number2 count = count + 1 Modular arithmeic Modular division allows the whole number part of the answer (integer division) to be separated from the remainder (modulo division). Integer division whole_number_part = number1 // number2 Modulo operaion remainder = number1 % number2 Comments Comments are used to document code. There are two ways of adding comments. 1. Comments which may go over several lines “”” Comments go here “””

2. Single line comments # comments go here # and again # if you need more than one line  Input and output using a console applicaion Console applicaion Pyscripter is an example of an IDE that provides a framework for typing program statements. The code can be run directly from here. Input from the keyboard To allow the user to enter data at runime using the keyboard an input() funcion is used Number1 = input ( ) Output to the console To display a string without going to a new line

print (“Hello World” , end=\"\") Here the “end = “”” parameter in the print instrucion changes the last character printed from being a line break to a null. To display the contents of a variable without going to a new line print (number1, end=\"\") To display a string and then move the output stream to a new line print (“Hello World” ) To display the output of a variable and then move the output stream to a new line print (number1) To move the output stream to a new line print () A simple console applicaion Python modules can be writen as a simple list of statements without having a main procedure. However wriing them in the form shown below allows them to be imported into other modules without being run automaically. The code only runs automaically if the module is executed directly or the main() procedure is called ater having been imported. def main(): print (\"Hello World\") input (\"Press ENTER to continue...\") if __name__ == '__main__': main() Combining strings and contents of variables into one output stream print (number1, “ + “, number2, “ = “ , sum)

Declaring and using variables Python variables do not have to be explicitly declared to reserve memory space. The declaraion happens automaically a value is assigned to a variable. max = 5 # An integer assignment A console applicaion using variables number1 = int(input(\"First Number? \")) number2 = int(input(\"Second Number? \")) total = number1 + number2 average = total / 2 print(\"Their sum is \", total) print(\"Their average is \", average) input (\"Press ENTER to continue...\")

Data types  Constant deiniions Python does not have any paricular language construct for declaring constants, so they are typically declared as just variables names with all capital leters. PI = 3.14159265 # PI is automatically declared a floating point number  Built-in data types Python has fewer built-in data types than other languages Integers and bytes Integer -2,147,483,648 to 2,147,483,648 There is no equivalent in python to the byte integer data type common in other languages. If a bigger whole number is required than available using the integer data type, python has the long integer Real numbers There is only one built in data type for real numbers Float double-precision loaing-point number However the decimal module provides support for fast correctly-rounded decimal loaing point arithmeic. It ofers several advantages over the loat datatype. Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representaions in binary loaing point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary loaing point. The exactness carries over into arithmeic. In decimal loaing point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary loaing point, the result is 5.5511151231257827e-017. While near to zero, the diferences prevent

reliable equality tesing and diferences can accumulate. For this reason, decimal is preferred in accouning applicaions which have strict equality invariants. from decimal import * getcontext().prec = 6 print(Decimal(1) / Decimal(7)) Characters and strings There is no separate character type in python; a character is represented by a string of one item. There are three ways you can declare a string in Python: single quotes ('), double quotes (\"), and triple quotes (\"\"\"). In all cases, you start and end the string with your chosen string declaraion. You can concatenate strings using the + operator “Hello” + “World” Square brackets can be used along with the index or indices to slice a string in order to obtain individual characters string1 = \"Hello World\" character2 = string1[1] print(character2) Python starts couning from 0 Boolean data Built-in type bool Example inished = False Date and ime data In python the dateime module supplies classes for manipulaing dates and imes in both simple and complex ways. import datetime

today = datetime.date.today() print (\"Current date using date.today method of datetime object:\") print (str(today)) tomorrow = today + datetime.timedelta(1) print (\"Tomorrow's date and time using timedelta method of datetime object:\") print (str(tomorrow) ) date_string = \"1/1/1989\" date_of_birth = datetime.datetime.strptime (date_string, \"%d/%m/%Y\") print (\"Convert a string to a datetime type:\") print(\"Date String: \", date_string, \" Date of birth: \",date_of_birth)  User-deined data types Record types Python does not have a type like struct in C or record in Pascal, but it can be easily implemented with a class. class TBook (object): def __init__(self, title=None, isbn=None, price=None, year_of_publication=None): self.title = title self.isbn = isbn self.price = price self.year_of_publication =

year_of_publication book = TBook() book.title = \"A-Level Computing\" Array types Python does not have any paricular language construct for declaring arrays. The declaraion happens automaically a value is assigned to a variable. Arrays in Python can contain any data type, including other arrays. list = [] def get_data(): for i in range(10): list.append(input()) def output_data(): for i in range(10): print(list[i]) get_data() output_data() input (\"Press ENTER to continue...\") NB A more eicient method of cycling through all the elements in an array would be for item in list; print(item) Enumerated types Python versions before 3.4 do not support enumerated types out of the box. One way to get around this is to deine a variables with values based on a range of numbers. These values can be contained in a class which represents the type.

class TDay(): sun = 0 mon = 1 tue = 2 wed = 3 thur = 4 fri = 5 sat = 6 x = TDay.wed y = TDay.sun print(\"Wednesday = \", x) print(\"Sunday = \", y) Sub-range types In Python there isn't a data type that limits values to a speciied range. However there are workarounds such as the one below for restricing values to capital leters. initial = \"s\" capital_letter = initial.upper() Sets Python has a set data type just like Pascal set1 = set([1, 7, 13, 22, 23, 46]) set2 = set([2, 22, 26, 32, 37, 47]) # Union set3 = set1 | set2

print (set3) # Intersection set4 = set1 & set2 print (set4) # Difference set5 = set1 - set2 print (set5) # Membership - test whether set1 contains 1 if 1 in set1: print(\"set1 contains 1\") # Sort set in order set3 = sorted(set3) print (set3) # Add items to set set1.add(49) print (set1) Logical bitwise operators Python uses the same notaion for bitwise operators as C# c = ~ a c= a & b c = a | b c = a ^ b Two's Complement binary for Negaive Integers: Negaive numbers are writen with a leading one instead of a leading zero. So if you are using only 8 bits for your twos-complement numbers, then you treat paterns from \"00000000\" to \"01111111\" as the whole numbers from 0 to 127, and reserve \"1xxxxxxx\" for wriing negaive numbers. A negaive

number, -x, is writen using the bit patern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1). So -1 is complement(1 - 1) = complement(0) = \"11111111\", and -10 is complement(10 - 1) = complement (9) = complement(\"00001001\") = \"11110110\". This means that negaive numbers go all the way down to -128 (\"10000000\"). Of course, Python doesn't use 8-bit numbers. It USED to use however many bits were naive to your machine, but since that was non-portable, it has recently switched to using an INFINITE number of bits. Thus the number -5 is treated by bitwise operators as if it were writen \"...1111111111111111111011\".

Selecion  Boolean Expressions Relaional operators Equal to == Less than < Greater than > Not equal to != Less than or equal to <= Greater than or equal to >= Boolean operators Number equal 1 number = = 1 Number not equal to 1 number ! = 1 Age 17 or under age <=17 Age 17 or more but less (age >= 17) and (age < 25) Age under 21 or over 65 (age < 21) and (age > 65) Age not under 17 not (age < 17)

 Simple if statements if x > 3: y = 6 if d < 24: z = z + 2 w = w - 3  If-Then-Else statements if x > 3: y = 6 else: y = 9 if d < 24: z = z + 2 w = w - 3 else: z = z — 2 w = w + 3  Nested If statements if ch.isupper(): print(“uppercase letter”) elif ch.islower(): print(“lowercase letter”) elif ch.isnumeric(): print(“numeral”) else: print(“not alphanumeric”)

 Case Statements Python does not have a switch-case statement like other languages. It would be possible to use a series of if-elif statements. However an alternaive ap- proach is to use dicionaries def case_4(): z = z + 1 def case_5(): z = z—1 w = w—2 def case_6(): z = 6 switch = {4 : case_4, 5 : case_5, 6 : case_6 } switch [4]()

Repeiion  Execuing a loop a speciic number of imes count = 1 while count <= 5: print (\"line \", count) count = count + 1  Execuing a loop for each element in an array firstnames = [\"Jack\", \"Chris\", \"Tom\"] for name in firstnames: print(\"Hello \", name)  Execuing a loop at least once while True: name = input (\"Enter a name, X to finish\") if name == \"X\": break  Execuing a loop under certain condiions while name != “X”: name = input (“Enter a name, X to finish”)

Procedures and Funcions  Built-in Funcions Arithmeic funcions y = round (x) import math y = math.trunc(x) String handling funcions l = len (s) p = s.index(substr) substr = s [p, p+l] From string to integer int ( ) From integer to string str ( ) From string to loat float ( ) From loat to string str ( ) From string to dateime datetime.datetime.strptime (date_string, \"%d/%m/%Y\" ) From dateime to string .strftime(\"%d/%m/%Y\")  Declaring and calling a funcion def indentifier (parameterlist): statement 1 statement 2 . .

statement X return value def factorial (n): product = 1 for count in range(1, n+1): product = product * count return product number = int(input(\"Type in a number between 1 and 10: \")) answer = factorial (number) print(answer)  Declaring and calling a procedure def indentifier (parameterlist): statement 1 statement 2 . . statement X

def inputdata(): global number1, number2 number1 = int(input(\"First Number? \")) number2 = int(input(\"Second Number? \")) def calculateresults(): global sum, average sum = number1 + number2 average = sum / 2 def outputresults(): print(\"Their sum is \", sum) print(\"Their average is \", average) def keepconsoleopen(): input() inputdata() calculateresults() outputresults() keepconsoleopen()

Procedure and funcion parameters Calling by reference Remember that arguments are passed by assignment in Python. Since assign- ment just creates references to objects, there’s no alias between an argu- ment name in the caller and callee, and so no call-by-reference per se. How- ever the desired efect can be achieved as follows def swap (a, b): temp = a a = b b = temp return a, b number1 = 5 number2 = 7 print(\"First: \", number1, \", Second: \", num- ber2) number1, number2, = swap (number1, number2) print(\"First: \", number1, \", Second: \", num- ber2) input()

Calling by value def increment(n): n = n + 1 print(n) number = 7 increment (number) print(number) How to use the built-in random number generator import random x = random.randint(1,6)

Arrays Python doesn’t have a naive array data structure, but it has the list which is much more general and can be used as a mulidimensional array quite easily. # An array can be initialised in one statement # The index starts at zero name = [\"Fred\", \"Jack\", \"Chris\", \"Ali\"] # Individual elements are accessed by the index enclosed in [] print (name[0]) # Alternatively array elements can be assigned one at a time name[0] = \"Fred\" name [1] = \"Jack\" name[2] = \"Chris\" name[3] = \"Ali\" # This loop accessed the array elements in or- der for index in range(4): print(name[index]) # If the number of array elements isn't known for index in range(len(name)): print(name[index]) # This loop accessed the array elements in re- verse order for index in reversed(range(4)): print(name[index]) for index in name[::-1]: print(index)

Dimension Because lists in Python are dynamic they don’t have to be dimensioned. The downside of this is that you can’t make an assignment to an element that doesn’t already exist. Therefore whilst the following general array idiom might work in other lan- guages it doesn’t work in Python mylist = [] for i in range(10): mylist[i] = 1 One soluion would be to use the append method to add elements one at a ime. mylist = [] for i in range(10): mylist.append[1] Alternaively it is fairly easy to do the same job as a dimension statement using a “comprehension”. A comprehension is roughly speaking just an ex- pression that speciies a sequence of values. For example to create the list equivalent of a 10 element array you could write: mylist = [0 for i in range(10)] Following this you have a ten-element list and you can write mylist [i] = something as long as I < 10

 Two Dimension Arrays # The two-dimensional equivalent of the dimen- sion statement using comprehensions # i iterates through rows and j iterates through columns distance = [[0 for j in range(3)] for i in range(3)] distance[1][2] = 144  Arrays of Records # Declare the structure (class) date type class tstudent (): def __init__ (self, name=None, marks=None): self.name = name self.marks = marks # Initialise a list of objects (records) student = [tstudent() for i in range (4)] student[0].name = \"Fred\" student[0].marks = 67 for index in range(4): print (student[index].name, student [index].marks)

Text iles and iles of records  Text Files Text iles can be opened in a range of modes . r read only w write only - NOTE, this destroys any previous version of the file! r+ read AND write a append mode (will write only after the existing data) w+ write AND read (will create the ile if it doesn't exist) Wriing to a text ile filename = \"C:/test1.txt\" # Open file for writing currentfile = open(filename,\"w\") for count in range(1,6): # Read string from keyboard prompt = \"Input line number \" + str(count) + \": \" textstring = input(prompt) # Write string to file currentfile.write(textstring + \"\n\") # Close file currentfile.close()

Reading text from a ile filename = \"C:/test1.txt\" # Open file for reading currentfile = open(filename,\"r\") # Iterate line by line through file for line in currentfile: # Display line of text print(line) #close the file currentfile.close() An alternaive method of reading text from a ile, more akin to the EOF com- mand used in other languages would be while True: line = currentfile.readline() if not line: break print(line)  CSV Files Python has a module that can deal with CSV iles directly however if you wish to create a CSV ile more simply, you can create a new text ile. textstring = name + “,” + street + “.” + town currentfile.write(textstring + \"\n\")

 Wriing to a binary ile # Complex data can be stored in a file using the pickle module import pickle # Define data structure class TBook (object): def __init__(self, title=None, isbn=None, price=None, year_of_publication=None): self.title = title self.isbn = isbn self.price = price self.year_of_publication = year_of_publication # Path for file filename = \"C:/test1.txt\" # Open file for reading currentfile = open(filename,\"wb\") # Create an instance of the class book = TBook() answer = \"y\" # Loop through the creation of repeated in- stances of the class while answer.lower() == \"y\" :

book.isbn = input(\"ISBN: \") book.title = input (\"Title: \") book.price = input (\"Price: \") book.year_of_publication = input (\"Year Of Publication: \") pickle.dump(book, currentfile, pick- le.HIGHEST_PROTOCOL) answer = input(\"Do you want to add another record? (y/n) \") # Close the file currentfile.close()  Reading from a binary ile import pickle # Define data structure class TBook (object): def __init__(self, title=None, isbn=None, price=None, year_of_publication=None): self.title = title self.isbn = isbn self.price = price self.year_of_publication = year_of_publication

# Path for file filename = \"C:/test1.txt\" # Open file for reading currentfile = open(filename,\"rb\") # Create an instance for the class book = TBook() eof = False # Loop through instances of class while not eof: try: book = pickle.load(currentfile) print(\"ISBN: \", book.isbn) print(\"Title: \", book.title) print(\"Price: \", book.price) print(\"Year of Publication:\", book.year_of_publication) except EOFError: eof = True # Close the file currentfile.close()




Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook