Skip to content

Instantly share code, notes, and snippets.

@popey456963
Created March 4, 2016 09:58
Show Gist options
  • Save popey456963/76c3a5b42ff1698b0fce to your computer and use it in GitHub Desktop.
Save popey456963/76c3a5b42ff1698b0fce to your computer and use it in GitHub Desktop.
Chapter 2 Modifications
One-dimensional arrays
topScore = 0

for i in x:
    if i > topScore:
        topScore = i

print(topScore)

Zero length list

x = []

Fields, records and structures

Surname, ID, Course, College = "Grant", "5129", "Comp Sci", "Warwick"

class recordStructure():
    def __init__(self, field1, field2, field3):
        self.surname = Surname
        self.id = ID
        self.course = Course
        self.college = College

File systems

fileName = "./text.txt"

with open(fileName, "r") as f:
    for line in f.readlines():
        print(line)

Writing to a file

fileName = "./text.txt"

with open(fileName, "w") as f:
    for i in range(1,5):
        inputString = input()
        f.write(inputString)

Reading binary files

with open("myfile", "rb") as f:
    try:
        byte = file.read(1)
        while byte != "":
            # Code for processing byte
            byte = file.read(1)
    except:
        pass

Writing binary files:

with open("binaryFile.bin", "wb") as f:
    for value in binary:
        f.write('value', b)

Dictionary

dictionary = {}
dictionary["Computer"] = 1
dictionary["I"] = 2
dictionary["Love"] = 3
dictionary["Science"] = 4

Dictionary

print(dictionary.get("science", "valuenot found"))
if "science" in dictionary:
    print(dictionary["science"])
else:
    print("value not found")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment