Python Data Types and Variables Overview

comssa fop revision final n.w
1 / 42
Embed
Share

Learn about Python data types and variables, including integers, floats, strings, and booleans. Understand how Python dynamically assigns data types and the flexibility it offers. Master using variables as numbers in calculations.

  • Python Basics
  • Data Types
  • Variables
  • Programming

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. ComSSA FOP Revision (Final) 31/05/23

  2. Acknowledgement of Country We at ComSSA would like to acknowledge the traditional owners of the land on which Curtin University Perth is located, the Whadjuk people of the Nyungar Nation. We pay our respects to Nyungar elders, past, present and emerging, and acknowledge their wisdom and guidance in our teaching environments.

  3. Icebreaker Which topic do you know least about? Move to the table which has that sign on it. If there s too many people at one table, negotiate with your class mates who knows enough to go to a different table. Lists, Dicts, Regex Arrays, Grids, Plotting Functions/Exceptions Objects, Classes, Methods Bash Scripting, Automation

  4. Session 1 and 2 Slides In week 3, we covered some basics such as the parts of a Python program, for loops, if statements and a few other things. In week 8, we covered strings, lists, arrays and objects. For those who weren t here, we have provided those slides on #fop-revision in the Discord channel. We will only briefly cover these things today.

  5. The exam Datatypes and data handling Arrays, grids and plotting Functions and structured data Scripting and automation Objects and sharing

  6. Variables and Data Types Python has four basic data types: int Integers Whole numbers 7, 55, 32000 float Floats Real numbers 256.0, 35.768 str Strings Any text or characters Rats are cool boolean Boolean True or False True, False

  7. Variables and Data Types Python is unusual because: You don t need to declare variables (though may have to initialise them) Python can work out which type a variable should be (Dynamic typing) is a string is an int is a float, and can be a real number if you work hard is a boolean. name = "ComSSA" year = 2022 myFOPGrade = 97.5 ratsRock = True

  8. Variables and Data Types If a variable is an int or float, it is a number. This means you can use it like a number anywhere a number is used!

  9. Strings A string is a series of characters they could be letters, numbers, or something else entirely. In Python we use double quotes (" ") to note something is a string. myString = "Welcome to the ComSSA FOP Revision Session!" You CAN use a single quote e.g. 'hello', but they re less flexible. Never mix them.

  10. Strings and Slicing If you want to get a single character in a string, you must count from zero. For example, the 2nd character is myString[1]. To get substrings, use the following: start:stop:step Start: index of the character it starts on (Default = 0) Stop: index of the character AFTER the last one you want to include (Default = end) Step: how much you want it to jump each time (Default = 1)

  11. Strings and Slicing Start: First character Stop: The character AFTER the last one you want to include Step: The jump between characters

  12. Lists A structure which can hold any type of item Is composed of elements myString = "Welcome to the ComSSA FOP Revision Session!" myList = myString.split(" ") ["Welcome", "to", "the", "ComSSA", "FOP", "Revision", "Session!"]

  13. List Comprehensions If we have to do something many times, a list comprehension may help. evens = [] for i in numList: if i % 2 == 0: evens.append(i) evens = [i for i in numList if i % 2 == 0]

  14. List Comprehensions If we have to do something many times, a list comprehension may help. evens = [] for i in numList: if i % 2 == 0: evens.append(i) evens = [i for i in numList if i % 2 == 0] This reads a bit more like English. The new list is i, where i is a set of items in numList, but only those which are even numbers.

  15. Dictionaries If you want to know the meaning of a word, you look up the dictionary. Python / pa n/ a high-level, general- purpose programming language. Key, which we use to perform look-up Value, which the look-up returns

  16. Dictionaries Dictionaries: Map from keys to values Are unordered just a set of pairs Are very fast Have immutable keys they can t be changed myDict = {} myDict["thisKey"] = 1 # creates a new key with value 1 myDict["thisKey"] = 2 # overwrites value of thisKey with 2 for d in myDict: print(d)

  17. Activity 1 Data Types and Data Handling Get the names of people at your table (or your online room) and make a list called names containing them. Find comprehensions that achieve the following: Finding all the multiples of 5 up to 50 (i.e. 5, 10, 15, ... , 45, 50) Multiplying all numbers in a list by 2. (Can use [1, 1, 5, 2] to test it) Returning all words in a list where the second letter is "e" or "E" Counting the number of items in a list whose value is 2017, 2020 or 2023. Make a dictionary which uses your student number as the key and your name as the value.

  18. Solution 1 Data Types and Data Handling names = ["Andrew", "Sauban", "Franco", "Nick"] Finding all the multiples of 5 up to 50 (i.e. 5, 10, 15, ... , 45, 50) [i*5 for i in range(1, 11)] or [i for i in range(5, 55, 5)] (start, stop, step) Multiplying all numbers in a list by 2. (Can use [1, 1, 5, 2] to test it) [i*2 for i in myList] Returning all words in a list where the second letter is "e" or "E [word for word in wordList if word[1].lower() == "e"] Counting the number of items in a list whose value is 2017, 2020 or 2023. len([a for a in list if a in [2017, 2020, 2023]) students = {} students[21054321] = "John Smith"

  19. Regular Expressions Building blocks \d a digit \d+ a number \w a letter \w+ a word \s whitespace These work like a while loop. e.g. Keep adding digits until first non-digit character found \d{4} 4 digits \d+\w? a number then optional character Combining \w+\s\w+ word, space, word | means or e.g. \w+|\w+\d+ = word OR word + number Note: Highly simplified syntax for helping those who are stuck. If you re following the lectures or another reliable source and it works, use that!

  20. Arrays Arrays hold an ordered sequence of values. Unlike lists: All of the elements must be the same type for example, all ints, or all strings. Once you create it, you can only change the size by creating a new array and copying the elements from one to the other. Slicing also works on arrays.

  21. Arrays - Multidimensional 0,0 0,1 0,2 1,0 1,1 1,2 Multidimensional arrays are a lot like normal arrays. The differences: Double brackets important Declaring: myArray = np.zeros(100) my3DArray = np.zeros((100, 100, 100)) myArray = np.array([1, 2, 3]) my2DArray = np.array([[1, 2], [3, 4]]) Accessing: myArray[2, :, :] myArray[:, :5, :] # means all rows, all columns, 2nd table # means all rows up to 4, all columns, all tables

  22. Arrays - Multidimensional To loop through multidimensional arrays, we need multiple loops: for row in range(len(myArray[:, 0])): for column in range(len(myArray[0, :])): print("Value at [", row, column, "] is: , \ myArray[row, column]) Note myArray[row, column] can also be written myArray[row][column]

  23. Grids Von Neumann (2 iterations) Grids set new values for each square based on the former value combined with those of surrounding squares. Original Moore (2 iterations)

  24. Plotting Matplotlib works by building up a buffer of things to show, kind of like a storyboard for an animation. It then presses play when you run plt.show() (This should usually only run at the very end, as it empties the buffer) For a lot of things you should define axes and work on these (As we ve seen in Prac Test 2 and 3, and the assignment).

  25. Plotting 0, 1 0, 0 What do you think this code does? fig, axs = plt.subplots((2, 2)) axs[0, 0].set_xlim(0, 36) axs[0, 0].set_ylim(0, 36) axs[0, 0].set_facecolor( black ) axs[0, 0].set_title( The void. ) axs[1, 1].set_facecolor( blue ) axs[1, 1].plot([0,0], [35,35], white ) 1, 1 1, 0 plt.show()

  26. Files Reading and writing to files is essential to programming. Usually, you will be working with CSV (Comma Separated Value) text files, which look something like this: 20908070,Joe Bloggs,COMP1005,85.0 20807060,John Smith,NPSC1003,60.0 20607080,Tess Jones,STAT1005,80.0

  27. Files Two ways to open files for reading: 1. with open("file.csv") as f: lines = f.readlines() 2. f = open("file.csv") lines = f.readlines() f.close()

  28. Files Once we have the data, we need to process it. readlines() creates a list of lines in the file (just long strings, they look meaningful to us but mean nothing to Python). To start processing them, we need to split them up. For example: itemslist = [] # creates empty list for line in lines: a = line.split(",") itemslist.append(a[0]) # split "a,b" into ["a","b"] # adds to our list

  29. Functions Functions are a great way of making our code more efficient. Instead of having to do the same thing multiple times with only slightly different options, we can do it once, then call it multiple times. Not only shorter, but a lot easier to understand.

  30. Functions A typical function looks like this: Inputs from outside def sum_of_squares(a, b): output = (a * a) + (b * b) return output Output sent to outside It would be called in code like this: myNum = sum_of_squares(3, 5)

  31. Functions Understanding scope is important! Variables inside a function mean nothing outside of it. In the last example, if you did print(output) in the main code, it would have an error. Likewise, if you tried to do something with mynum inside the function, it would not work (or if it somehow did, it may behave unpredictably). And see how 3 in the main code became a in the function, and 5 became b ?

  32. Scripts and Automation We have spent most of the unit learning Python in a Linux environment, while using some Linux commands to help us. But we can also: Group Linux commands into scripts Introduce some extra features variables, for loops etc

  33. Scripts and Automation Parameter sweeps: Base: Python code which can take command line arguments (sys.argv) Driver: Bash script which generates values to send to Python code Execute the driver This runs the Python code Which ideally outputs to files > ./driver.sh p1 p2 p3 parameters

  34. Objects An object is a instance of a class. Classes have attributes. This room has a building number, a room number, and the number of people it is allowed to hold. A cat or dog has a breed, a name and a date of birth. A student has a student ID number and a name.

  35. Objects An object is a instance of a class. Classes also have methods. Methods are functions that belong to classes. They do stuff. What are some methods a Cat class might have? (Not technical at all think of an actual cat)

  36. Objects Do you remember earlier in programming, when you had to put round brackets at the end of some things? print( myString.upper() ) myList.append(5) f.readlines() plt.show() e.g. You were using a method! And if you didn t have to use the brackets, you were accessing a variable. lights[i,j].colour e.g.

  37. Objects Creating a class is easy. We need an __init__ method to initialise the class variables. class Car: def __init__ (self, model, colour, numberplate, kms): self.model = model self.colour = colour self.numberplate = numberplate self.kms = kms Class variables Just normal variables! def display(self): print ("I am a", self.colour, self.model , \ "with numberplate", self.numberplate )

  38. Objects You ll get used to this self thing it appears everywhere. It refers to the particular object created by the class. class Car: def __init__ (self, model, colour, numberplate, kms): self.model = model self.colour = colour self.numberplate = numberplate self.kms = kms def display(self): print ("I am a", self.colour, self.model , \ "with numberplate", self.numberplate )

  39. Objects All methods have self as their first parameter. So for example: def walk(self, start, end, shoes): We would call this method like this: self.walk( B314 , Library , hiking boots ) If we didn t have the self. , Python wouldn t know where to find it or what it belongs to. While it looks like a function, it is a method of a class.

  40. Objects If we didn t have initial values, it looks a bit different. class Demo: def __init__ (self): self.name = "" self.start = None self.end = None You ll have to set them later.

  41. ~~ So, that was what we had already covered. ~~ What s left? Scripts and Automation Structured Data Projects in Python A few theory related parts of Lectures 1 and 5

  42. Thank you for attending this ComSSA revision session! Coming up: Hackathon Beers with ComSSA DSA / UCP revision sessions (Semester 2) Check #fop-revision on Discord for materials.

Related


More Related Content