The code and notes from today’s Programming the Pi Session.
Covers an introduction to data types and some of the things we can do with them.
(Note: you can get a sneak peak at part 2 here)
# Variables # Assigment Operators x = 1 print(x) x += 1 print(x) # x += 1 is equivalent to x = x + 1 # You can use any of the Arithmetic operators in this way # Types # ===== # Integers x = 5 y = 2000 z = -123 # Floats r = 0.5 t = 3.14159265359 s = -2.567 ''' -------------------- Arithmetic Operators -------------------- + (addition) - (subtraction) * (multiplication) / (division) % (modulus aka remainder) ** (exponent aka powers ) // (floor division aka rounded down) ''' z = x * y print(z) # Strings myString = 'Hello World' print(myString) # len() gets the length of the string print(len(myString)) print(myString[1]) print(myString[0]) # we can use ranges print(myString[0:5]) # no second number runs to the end of the range print(myString[5:]) # Lists numbers = [1, 2, 3, 4, 5] # we can get the number of items in a list with len() print(len(numbers)) print(numbers) #You can pull out a specific list item by index print(numbers[0]) # We can overide list values by index numbers[0] = 0 print(numbers) moreNumbers = [6, 7, 8, 9, 10] # use + to join two lists allNumbers = numbers + moreNumbers print(allNumbers) allNumbers.sort() print(allNumbers) allNumbers.reverse() print(allNumbers) writtenNumbers = ['One', 'Two', 'Three', 'Four', 'Five'] print(writtenNumbers) writtenNumbers.sort() print(writtenNumbers) # Dictionaries # Key Value data type faveColours = {'Rob': 'Blue', 'Dave': 'Red', 'Jane': 'Orange'} print(faveColours) print(faveColours['Rob']) faveColours['Rob'] = 'Purple' print(faveColours['Rob']) # Tuples tupleNumbers = 1, 2, 3, 4, 5 print(tupleNumbers) # tupleNumbers[0] = 0 <<< This WILL ERROR # Tuples are IMMUTABLE # Once set they cannot be changed! # BUT they can be converted into lists! listNumbers = list(tupleNumbers) listNumbers[0] = 0 # Nesting Lists, Dictionaries allRoutes = [1, 4, 5, 7, 15] # we can nest lists (and Tuples) within dictionaries or other lists busRoutes = {'Town': allRoutes, 'Trinity': 4, 'Airport': 15} print(busRoutes) print (busRoutes['Town']) print (busRoutes['Airport']) #we can nest dictionaries within ditionaries usefulInfo = {'Width': '9 miles', 'Length': '5 miles', 'Buses': busRoutes} print(usefulInfo) print(usefulInfo['Buses']) # And we can pull out nested items using multiple keys: print(usefulInfo['Buses']['Town'])