Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Lab 1:
- # Task 1
- # TODO: type solution here
- print("I am learning Python")
- # Task 2
- # TODO: type solution here
- answer = 3 + 5
- print(answer)
- # Task 3
- # TODO: type solution here
- print("My first python code")
- variable1 = 46*2
- variable2 = 3+5
- print(variable1)
- print(variable2)
- print("everything works")
- # Lab 2:
- # Task 1
- # TODO: type solution here
- x=7
- print(x+5)
- print((x+5)*3)
- print(x+5*3)
- # why are the last two different?
- # because of order of operations
- #add your own!
- # Task 2
- # TODO: type solution here
- print(2<5)
- print(2<=2)
- print(2!=5)
- print(2==2)# 2 equals signs checks equality of something one equals sign is an assignment operator
- #try printing 2=2
- #delete the # to uncomment and test it
- #print(2=2)
- #add your own!
- print(5>2)
- # Task 3
- # TODO: type solution here
- print("CS" + "1026")
- print("CS" + " "+ "1026")
- print("CS "+"1026")
- #notice the space differences
- #add your own!
- print("hi " + "there")
- # Task 4
- # TODO: type solution here
- #lets try some simple formatting
- name= "Sterling Archer"
- age = 36
- #two ways of formatting strings
- # the first is called interpolation in this case %s represents a string and is the first element
- # %d represents an integer and is the second element in the list
- print("%s %d" % (name, age))
- # the second calls a format function it replaces the {} with the variables in the format function in order
- print("{} {}".format(name,age))
- #add your own!
- day = "Friday"
- month = "November"
- year = 2015
- print("{}, {}, {}".format(day, month, year))
- # Task 5
- # TODO: type solution here
- x =7
- print(x)
- y =x+5
- print("x is {} and y is {}".format(x,y))
- x=x+5
- #note the value changes when we do the statement above
- print("x is now {}".format(x))
- y= x+5
- # if we repeat the second print what will we get?
- print("x is {} and y is {}".format(x,y))
- #add your own!
- a = 10
- b = a + 5
- print("a is {} and b is {}".format(a, b))
- a = a + 10
- b = a + 5
- print("a is {} and b is {}".format(a, b))
- # Task 6
- # TODO: type solution here
- #we assign some variables and check an expression note how we checked the expression with format
- x = -1
- y =0
- print("is it true that x<= y?")
- print("It's {} !".format((x<=y)))
- a= 2.5
- b=5
- # notice how these two print statements give different results why is that?
- print(a*b)
- print(int(a *b))
- print("She said, hey there")
- #note how you can use escape sequences to format your strings as well
- print("She said,\n hey there")
- #add your own!
- c = 3.3
- d = 2
- print("The answer is \n{}".format(int(c * d)))
- # Task 7
- # TODO: type solution here
- #note how to get input from the keyboard
- celsius = float(input("Please type the Celsius value in"))
- # notice how we had to cast celsius to float try removing the float cast and seeing what happens
- #note 1.8 is 9/5
- #fDegrees stores the Fahrenheit value
- fDegrees= (celsius * 1.8 )+ 32
- print(fDegrees)
- # when you take a value from input it is a string value by default therefore you must convert it to whatever
- # other value you may use if need be
- # Task 8
- # TODO: type solution here
- fahrenheit = float(input("Please enter the temperature in fahrenheit - "))
- celsius = (fahrenheit - 32) * 5/9
- print(celsius)
- # Lab 3:
- # Task 1
- # TODO: type solution here
- x=5
- #is x > 5?
- if x > 5:
- print("X is larger than 5")
- else:
- print("X is smaller than or equal to 5")
- # Task 2
- # TODO: type solution here
- a=12
- b=7
- t =True
- c='e'
- print((a > 0) == (b > 0))
- print(('a' > c) != ('E' != c))
- print((a % b != 0) and (b * 2 > a))
- print((t or not(a > b)) and t)
- # Task 3
- # TODO: type solution here
- from datetime import datetime
- hour = datetime.now().hour
- if hour == 12:
- timeOfDay = "Morning"
- elif hour > 12 and hour <= 18:
- timeOfDay = "Afternoon"
- else:
- timeOfDay = " Evening"
- print("Good {}, world".format(timeOfDay))
- # Lab 4:
- # Task 1
- # TODO: type solution here
- count = 1
- while count <= 10:
- print(count)
- count = count + 1
- #two statements in the loop
- # Task 2
- # TODO: type solution here
- #place your code here
- for i in range (1, 11, 2):
- print(i)
- # Task 3
- # TODO: type solution here
- #place outer loop here
- for i in range (5):
- for x in range(1,11):
- print(x)
- # Task 4 *May not be right*
- # TODO: type solution here
- from random import randint
- name = input("please enter your name")
- # place your code here
- i = 0
- while i in range (20):
- print("test")
- i = i + 1
- if i % 2:
- rando = randint(1,10)
- print(rando)
- if i % 3:
- print(name)
- # Lab 5:
- # Task 1
- # TODO: type solution here
- def addNumbers(a,b):
- add = a + b
- return add
- print(addNumbers(3,5))
- # Task 2
- # TODO: type solution here
- #write your function here
- def factorial(a):
- if a == 0:
- return 1
- else:
- return a * factorial(a - 1)
- print(factorial(5))
- print(factorial(7))
- print(factorial(9))
- # Task 3
- # TODO: type solution here
- # place helloWorld() here
- def helloWorld():
- print("Hello World")
- # place helloWorldNTimes here
- def helloWorldNTimes(n):
- while n != 0:
- helloWorld()
- n = n - 1
- def main():
- helloWorldNTimes(7)
- main()
- # Task 4
- # TODO: type solution here
- #place your function here
- def isMultiple(i):
- if not i % 7:
- return i
- else:
- return -1
- def checkMultiples():
- for i in range(1,100):
- cur = isMultiple(i)
- if cur != -1:
- print(cur)
- checkMultiples()
- print(7 % (7 * 15))
- # Lab 6
- # Task 1, 2, 3 are giving errors so are not included.
- # Task 4
- # TODO: type solution here
- def zFirst(words):
- result =[]
- result2 =[]
- for word in words:
- if word.lower()[0] == 'z':
- result.append(word)
- else:
- result2.append(word)
- result.sort()
- result2.sort()
- return result + result2
- words=["hello","good","nice","as","at","baseball","absorb","sword","a","tall","so","bored","silver","hi"
- ,"pool","we","I","am","seven","Do","you","want","ants","because","that's","how","you","get","zebra","zealot","Zaire"]
- print(zFirst(words))
- # Lab 7:
- # Guess I dont have this on either sorry.
- # Lab 8:
- # Task 1
- # TODO: type solution here
- try:
- f=open("thefile.file","r")
- line in f.readline()
- except IOError:
- print("Error, file not found.")
- # Task 2
- # Not checking *
- # TODO: type solution here
- count = 0
- for i in range(10):
- # count += 1
- try:
- try:
- print(7/i)
- finally:
- if i == 9:
- print(i)
- except ZeroDivisionError as exception:
- print("Error, ", str(exception))
- # Task 3
- # TODO: type solution here
- values =[1,2,3,4,5,"hello",6,7,8,9,"10"]
- for cur in values:
- if type(cur) == str:
- raise TypeError("This is a string!")
- else:
- print("the value is :", (cur))
- # Lab 9:
- # Task 1
- episode4 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Greedo","Kenobi"}
- episode5 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Tauntaun","Yoda","Lando"}
- episode6 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Palpatine","Ackbar","Jabba","Rancor","Boba"}
- # code for union under here call your set unEps
- unEps = episode4.union(episode5, episode6)
- print(len(unEps))
- # Task 2
- episode4 = {"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Greedo","Kenobi"}
- episode5={"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Tauntaun","Yoda","Lando"}
- episode6={"Luke","Leia","Han","Chewie","C3PO","R2-D2","Vader","Palpatine","Ackbar","Jabba","Rancor","Boba","Yoda"}
- #code to create intersection of 4 and 5 then take episode 6 and difference that with the intersection of 4 and 5
- episode45 = episode4.intersection(episode5)
- final = episode6.difference(episode45)
- print(len(final))
- # Task 3
- sentence ="I had such a horrible day. It was awful so bad sigh. It could not have been worse but actually though "\
- +"such a terrible horrible awful bad day."
- makeItHappy ={"horrible":"amazing","bad":"good","awful":"awesome","worse":"better","terrible":"great"}
- sentence = sentence.split()
- print(sentence)
- for i in range(len(sentence)):
- if sentence[i] in makeItHappy:
- sentence[i]=makeItHappy[sentence[i]]
- newString = ""
- for word in sentence:
- newString = newString+" "+word
- print(newString)
- # Task 4
- # name = ["Stirling","Lana","Cyril","Pam","Ray","Cheryl"]
- alias = ["Duchess","Truckasaurus","Chet","Cookie Monster","Gilles de Rais","Cherlene"]
- newdict = {}
- for i in range(len(name)):
- newdict[name[i]] = alias[i]
- for bbhbh in sorted(newdict):
- print(bbhbh,":", newdict[bbhbh])
- # Task 5
- import math
- #check if number is prime not overly efficient
- def prime(n):
- if n==1 or n==0:
- return False
- for x in range(2,int(math.sqrt(n)+1)):
- if n%x == 0:
- return False
- return True
- #place your code here
- import math
- #check if number is prime not overly efficient
- def prime(n):
- if n==1 or n==0:
- return False
- for x in range(2,int(math.sqrt(n)+1)):
- if n%x == 0:
- return False
- return True
- dict ={}
- dict['even']={x for x in range(0,100) if x %2 ==0}
- dict['odd']={x for x in range(0,100) if x %2 ==1}
- dict['three']={x for x in range(0,100) if x %3 ==0}
- dict['five']= {x for x in range(0,100) if x %5 ==0}
- dict['prime']={x for x in range(0,100) if prime(x)}
- print(dict)
- # Lab 10:
- # Task 1
- # TODO: type solution here
- class Banana:
- bananaID =0
- def __init__(self):
- Banana.bananaID+=1
- self._ID = Banana.bananaID
- def __str__(self):
- return "This banana has an id of "+ str(self._ID)
- b1 = Banana()
- b2 = Banana()
- print(b1)
- print(b2)
- # Task 2
- # TODO: type solution here
- class Dinosaur:
- def __init__(self):
- self._type = ""
- def setType(self, type):
- self._type = type
- def getType(self):
- return self._type
- d1= Dinosaur()
- d2= Dinosaur()
- d3 = Dinosaur()
- d1.setType("T-Rex")
- d2.setType("Velociraptor")
- d3.setType("Stegosaurus")
- print(d1.getType(),d2.getType(),d3.getType())
- # Task 3
- # TODO: type solution here
- class Coffee:
- def __init__(self):
- self._coffee = ""
- def __add__(self, other):
- if isinstance(other,Cream):
- return "Yum"
- class Cream:
- def __init__(self):
- self._cream = ""
- coffee = Coffee()
- cream= Cream()
- print(coffee+cream)
- # Lab 11:
- # Task 1
- # TODO: type solution here
- class Fruit:
- def __init__(self):
- self.shape = ""
- self.colour = ""
- def canBePhone(self):
- return "fruits can't be phones..."
- class Banana(Fruit):
- def __init__(self):
- super().__init__()
- def canBePhone(self):
- return "Ring ring ring ring ring ring ring banana phone\nBeep-boo-ba-boo-doo-ba-doop"
- banana = Banana()
- strawberry = Fruit()
- print(banana.canBePhone())
- print(strawberry.canBePhone())
- # Task 2
- # TODO: type solution here
- class Bicycle:
- def __init__(self):
- self._gear = 0
- self._cadence = 0
- self._speed = 0
- def setGear(self, gear):
- self._gear = gear
- def setCadence(self, cadence):
- self._cadence = cadence
- def setSpeed(self, speed):
- self._speed = speed
- def getGear(self):
- return self._gear
- def getCadence(self):
- return self._cadence
- def getSpeed(self):
- return self._speed
- def applyBrake(self, brake):
- self._speed = self._speed - brake
- return self._speed
- def speedUp(self, acceleration):
- self._speed = self._speed + acceleration
- return self._speed
- class MountainBike(Bicycle):
- def __init__(self):
- super().__init__()
- self._height = 0
- def setHeight(self):
- self._height = height
- def getHeight(self):
- return self._height
- b1 = Bicycle()
- b1.setSpeed(100)
- b1.applyBrake(8)
- mb1 = MountainBike()
- mb1.setSpeed(100)
- mb1.speedUp(20)
- print(b1.getSpeed())
- print(mb1.getSpeed())
- # Task 3
- # TODO: type solution here
- class Pet:
- def __init__(self):
- self.name = ""
- self.species = ""
- class Dog(Pet):
- def __init__(self):
- super().__init__()
- self.doesDogChaseCats = False
- def setChaseCats(self,chase):
- self.doesDogChaseCats=chase
- def chaseCats(self):
- return self.doesDogChaseCats
- class Cat(Pet):
- def __init__(self):
- super().__init__()
- self.doesCatHateDog = False
- def setHatesDogs(self, hate):
- self.doesCatHateDog = hate
- def hatesDogs(self):
- return self.doesCatHateDog
- dog=Dog()
- dog.setChaseCats(False)
- cat = Cat()
- cat.setHatesDogs(True)
- print(cat.doesCatHateDog)
- print(dog.doesDogChaseCats)
- # Task 4
- # Don't have task 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement