Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

Python for Physical Science.pdf

Nächste SlideShare
Python fundamentals
Python fundamentals
Wird geladen in …3

Hier ansehen

1 von 115 Anzeige

Weitere Verwandte Inhalte

Ähnlich wie Python for Physical Science.pdf (20)

Aktuellste (20)


Python for Physical Science.pdf

  1. 1. Python 3 for Physical Science M. Anderson & M. Tellez
  2. 2. Python and Programming Languages
  3. 3. Programming Languages A Programming Language is the set of rules that provides a way of telling a computer what operations to perform. This is done by translating an algorithm (series of steps to solve a problem) into the linguistic framework provided by the programming language. A programming language provides a human-readable form to communicate machine-readable instructions.
  4. 4. Types Programming Languages High-Level Language 1. It is programmer-friendly language. 2. It is easy to understand. 3. It is simple to debug. 4. It is simple to maintain. 5. It can run on any platform. 6. It needs compiler or interpreter for translation. 7. Examples: Java, Python, Objective C, Swift, C++ Low-level Language 1. It is a machine-friendly language. 2. It is difficult to understand. 3. It is complex to debug comparatively. 4. It is complex to maintain comparatively. 5. It is machine-dependent. 6. It needs assembler for translation. 7. Examples: Assembly language and machine language.
  5. 5. Why Python - Python is an open source programming language - Free - Python is flexible and intuitive - Plenty of available Python libraries and resources online - Python is good for beginners and great foundational language - Closer to human/natural language - Python is a current and commercial language. - More than just an academic exercise. Students can apply their learning in real industry. - Python can be used for - AI - Web/Mobile Development - Data Analysis and Visualization - Desktop GUIs
  6. 6. 9th grade goals for Computer Science Programming Fundamentals: These are foundational concepts of programming that can be easily translated in another programming language and that are necessary to fully understand for a programmer to reach higher levels of complexity - Sequencing - Variables - Input and Output - Selection - Repetition - Data Structures Computational Thinking: This is the underlying set of ways of thinking that are necessary for computer scientist to solve complex problems. Computational thinking can be improved by programming. The main pillars of computational thinking are: - Decomposition. - Pattern recognition - Abstraction - Algorithmic thinking. *more info here
  7. 7. PyCharm ❏ IDE: Integrated Development Environment. ❏ Software to write, compile (translate into machine code), debug and test your programs. Goal ❏ Get familiar with the PyCharm environment
  8. 8. First time PyCharm Installation
  9. 9. 1. Sign-up to Jetbrains for free licenses 1. Go to https://www.jetbrains.com/community/education/#st udents 2. Scroll down to find the “Apply now” button 3. Complete the form for Products for Learning 4. Confirm your account in your school email. Use school email account SIGN UP FIRST! DON’T DOWNLOAD THE FREE PYCHARM VERSION
  10. 10. 2. Download licensed Pycharm IDE 1. Login to https://account.jetbrains.com/login using your school google account 2. Download Pycharm IDE 1 2 3
  11. 11. 3. Install PyCharm 1. Drag and drop PyCharm to Applications folder 2. Follow the prompts to completely install the program
  12. 12. 4. Activate PyCharm 1. Open your PyCharm 2. PyCharmActivate 3. Click “Log in to Jetbrains Account to authorize” 4. On PyCharm, Click Activate 5. You should see “Authorization Successful” confirmation
  13. 13. 4. Successful Installation This is the screen you should see if PyCharm was successfully installed.
  14. 14. 5. Download and Setup Python Interpreter 1. Download Interpreter from here 2. Install the interpreter downloaded END of HW
  15. 15. Second time Pycharm installation for new computers
  16. 16. Installing PyCharm for students who got a new computer Interpreter 1. Download the Python Interpreter by clicking the yellow button https://www.python.org/downloads/ 2. Install the Python Interpreter until finished PyCharm 3. Login to your Jetbrains account https://account.jetbrains.com/licenses 4. Download the PyCharm from the list JetBrains Product Pack for Students 5. After downloading, open, drag and drop the Pycharm app to the Applications folder and follow the prompt until installation is complete. 6. Open the installed Pycharm, you should be good to go
  17. 17. We Do #1 - Create a new Project - Create your first Python program: “Hello Physical Science” On your PyCharm
  18. 18. Create a new project 1. Click New Project
  19. 19. 2. Check Interpreter ❏ Choose the “Pure Python” option ❏ Name your project “Unit1” using camel notation (capital initial letter for every word, no space in between) ❏ If you don’t see a Base interpreter, refer back to step 5 of the installation process.
  20. 20. Python Files Fundamentals ❏ A Python Project can contain one or more packages. These are simply folders to organize your programs*. ❏ A package can contain one or more Python Files. ❏ Python File can hold all the instructions needed for a program. These instructions are normally broken down into multiple functions
  21. 21. Create a Python Package ❏ Right click on the Project (Folder) ❏ Select “New” ❏ Select “Python Package” ❏ Name the new package “variablesAndFunctions”
  22. 22. Create Python File - Right-click on the package - Create a Python File - Name it: HelloPS (camelStyle)
  23. 23. Quick PyCharm IDE* Orientation Project navigation Output window Editor window Debugging and VCS tools *“Integrated Development Environment”
  24. 24. Code your first program - Type the instructions you wish to add to your program on the editor window: print(“Hello Physical Sciences”) - Right click the file, and choose Run to compile and execute your program. - If you see “Hello Physical Sciences” in your output window, your first program is running!
  25. 25. Code Comments ❏ Comments in code refers to lines of text that are excluded from compilation (not executed by the compiler) and are used to document your code. Proper code documentation is fundamental to be able to share, maintain, and reuse code ❏ In Python a inline and single line comment is created by using the character # before your comment (use a space before and after the #) ❏ Multiple line comments can be created using three quotation marks at the beginning and end.
  26. 26. Unit 1: Output, Variables, Input, Operators and Functions
  27. 27. Variables and Output with Built-in Functions Variables are containers for storing data values. ❏ Variable names are case sensitive ❏ a, b, c, A, d are different variables ❏ “=” is an assignment operator ❏ 5, “John”, 24.5, 4 are values assigned to the variables ❏ print() is a built-in function ❏ type() is a built-in function - (optional) use the type() function to determine the type of data assigned to a variable a = 5 b = "John" c = 24.5 A = 4 d = True print(a) # prints 5 print(b) # prints John print(c) # prints 24.5 print(A) # prints 4 print(type(a)) # prints class int print(type(b)) # prints class str print(type(c)) # prints class float print(type(A)) # prints class int print(type(d)) # prints class bool
  28. 28. Output in Python - print() function print("Wow! " + "Python is cool!") print("Hello", end=' ') print("Physicists!") print("Good night", "Chemists", sep=", ") print("Jeff's last name is Clark") # concatenation (add text together) # keeps the following print on the same line #prints adding a separator in between each text #the backslash () allows you to print characters that are language reserved (‘)
  29. 29. Output in Python - print() function var = “Science is fun!” print("Wow! ", var) force = 5 force_unit = “N” print(force, force_unit) # Print multiple things by separating them with a comma. We are printing a variable and a string here. What would print here? # Prints two variables. What types of variables are these?
  30. 30. DISCUSSION What is similar and different between the term “variable” in Python and Science?
  31. 31. You Do ❏ Create 3 variables (name, height, height_units) for your data ❏ Print your info using text and variables (see example on the left) END of Lesson
  32. 32. Arithmetic Operations print(8 - 2) print(4.5 + 3) print(7 / 2) print(7 // 2) # integer division print(7 * 3) print(7 % 3) # modulo print(2 ** 3) # exponent # subtraction with two integers # subtraction/addition with float and integer # division (real division) # integer division (truncates the decimal portion) # multiplication # modulo (remainder operator) # exponent
  33. 33. OPTIONAL: Compound Assignment Operators Operator Example Equivalent += a += 1 a = a + 1; -= a -= 1 a = a - 1; *= a *= 2 a = a * 2; /= a /= 2 a = a / 2; //= a /= 2 a = a // 2; %= a %= 2 a = a % 2; **= a **= 2 a = a ** 2;
  34. 34. Trace the changing values of x x = 0 print(x) x += 1 print(x) x += 2 print(x) x *= 4 print(x) x /= 2 print(x) x %= 5 print(x) # # # # # #
  35. 35. print() function (continuation) a = 4 b = 2 print("Sum: ", (a + b)) print("Difference: ", (a - b)) print("Product: ", (a * b)) print("Quotient: ", (a / b) print("Remainder: " + str(a % b)) You can concatenate text and variable values with operations together on print statements. You can print a text and then a number separating them with a comma/s. You can convert the number to a text casting to String using str() built-in function
  36. 36. You Do: Age and Height ❏ Create 3 variables (Name, Year of birth, height) ❏ Print the info using text and variables ❏ Calculate and print your age ❏ Calculate and print your your height difference from 1.7 m Sample Solution (teachers only)
  37. 37. Built-in Functions (print, input) You’ve already been using built-in functions! The print function to print a string - print(“Hello Physical Sciences!”) Other built-in function: input allows you to get user input. The program will wait for input and store it on the variable movie. - movie = input(“What is your favorite movie?”)
  38. 38. Built-in Functions (print, input, int) PROBLEM - inputs default as text (strings) This means Python assumes that anything a user inputs is text, not a number EVEN IF IT’S A NUMERIC DIGIT (e.g. “4”) - force = input(“What is the force? “) - print(force * 2) …causes an ERROR because it thinks the force is text and you can’t do math with text The int function to change from one data type to another data type (integer) - force = int(input(“What is the force? “)) - print(force * 2) ← SUCCESS
  39. 39. Built-in Functions (print, input, int) Optional for later Here are some other useful built-in functions: ❏ round(float, int) - rounds float to int decimal places ❏ max(arg1, arg2, argN) - gets the maximum value of arguments ❏ min(arg1, arg2, argN) - gets the minimum value of arguments ❏ len(s) – gets the length (number of items) of an object s For reference: https://docs.python.org/3/library/functions.html
  40. 40. We Do Expected output Enter length: Enter width: Area: Perimeter: Create a Python program that reads and stores a rectangle’s length and width and calculate and outputs the area and perimeter of a rectangle *note: Your input needs to be cast as a integer before you are able to do operations. number = int(input(“Enter a number: “))
  41. 41. You Do - Velocity Write a Python program to store the values of distance and time and calculate and print the velocity. Enter distance: Enter time: Velocity is:
  42. 42. You Do - Distance/Time Write a program that will read the velocity of an object and will output the distance traveled at 5 constant intervals of time. Sample Solution (teachers only) END of Lesson
  43. 43. User-defined Functions
  44. 44. What is a function? ❏ A function is a block of organized, reusable code that is used to perform a single, related action ❏ A function provides modularity for your applications and a high degree of code reuse ❏ Python provides built-in functions which are part of the core language. ❏ Python allows you to define your own (user-defined) functions ❏ Functions can be called several times allowing for the same set of statements to be executed without repeating code. TimerApp showTimer() startTime() pauseTime() stopTime() resetTime() QuizApp showInstruction() startQuiz() showQuestion() showChoices() showTimer() Physics Quiz Instructions Start Quiz Time:
  45. 45. Conventions of user-defined functions ● Functions have conventions a. Name a function based on what it does (in lowercase (no camel) - python) b. Whitespace/indentation is important! c. Function body “code blocks” (groups of statements) are indented (4 spaces or tab) ● Sometimes a function takes values from outside through variables enclosed in parenthesis called parameters. a. When you call (or use) the function, you pass arguments as values to the parameters ● Sometimes a function returns a specific value through a return statement, prints a value using the print function, and/or not return or print at all.
  46. 46. User-defined function ❏ In Python, a user-defined function declaration begins with the keyword def followed by the function name. ❏ The function may take arguments(s) as input within the opening and closing parentheses, just after the function name followed by a colon. ❏ After defining the function name and arguments(s) a block of program statement(s) start at the next line and these statement(s) must be indented. ❏ To end a function you must leave two empty lines after the last statement. ❏ A function can return a value by using the keyword return def function_name(argument1, argument2, ...) : statement_1 statement_2 return…(optional)
  47. 47. A closer look at a Python function def function_name(argument1, argument2, ...) : statement_1 statement_2 return…(optional) Python keyword to define a function function name (arbitrarily named) variable/s to hold the value/s sent to the function to perform its task code/s that work together to perform a task
  48. 48. User-defined Function Function that return (s) This function square() has a single parameter, squares the argument, and returns the result def square(x): y = x * x return y When we call the square function, we pass 10 as an argument. We store the value that is returned a variable result, and print it to_square = 10 result = square(to_square) print(result) # 100 print(square(5) + 1200) # 1225 Void (non-return) Function Function square() takes one argument, squares the argument, and prints the result def square(x): y = x * x print(y) When we call the square function, we pass 10 as an argument. In this case we won’t have access to the result of the operation. to_square = 10 square(to_square) print(square(5) + 10) # cause an error square(2) # 4
  49. 49. We Do [5 minutes] Rectangle Functions Expected output Enter length: 2 Enter width: 4 Area: 8 Perimeter: 12 Create a Python Rectangle program that includes 2 functions that allow for length and width to be passed as arguments, calculate the area and perimeter, and returns the result. Sample Solution (teachers only)
  50. 50. You Do - Velocity Function Create a Python file with a function that allows for passing distance and time as arguments and returns the velocity. Make sure you are using a function to determine the velocity. Enter distance in m:5 Enter time in s: 2 Velocity in m/s: 2.5 Sample Solution (teachers only) END of Lesson
  51. 51. Scope of a variable ❏ When utilizing functions it is important to understand the scope (or lifetime) of any variable. ❏ Variables created within a function are local to that function and cannot be accessed outside of it. ❏ Variables created outside a function are known as global and can be accessed inside of functions. def local1(): spam = "local spam" # local variable print("Local printing:", spam) def local2(): spam2 = "local spam2" # local variable spam = "test spam" # sets a variable with global in scope local1() # calls the local1 function print("After local assignment:", spam) # uses the global variable print("Attempt to access local:", spam2) # causes a name error because spam2 is not defined The output of the example code is: Local printing: local spam After local assignment: test spam
  52. 52. Scope of a variable def function1(): local_variable = "ONLY IN the function" print(local_variable) # prints the variable inside the function global_variable = "EVERYWHERE in the program, including functions” print(global_variable) # uses the global variable print(local_variable) # error, local_variable doesn’t exist outside of the function
  53. 53. You Do Moving Object Complete the following Python project Work with someone (code independently) END of Lesson Sample Solution (teachers only)
  54. 54. Submit your Python Program in 2 steps
  55. 55. 1. On PyCharm 1. Right click on the file (.py) you want to submit 2. Choose >> Open In 3. Choose Finder
  56. 56. 2. On Finder Window 1. You should see the Python file you selected to submit on the finder window 2. That is the file you will drag and drop to the submission bin on Google classroom
  57. 57. Unit 2: For loops and Lists
  58. 58. for loop
  59. 59. Loops and for loop ❏ Loop structure that executes a set of statements a fixed number of times ❏ for loops ❏ Run a piece of code for a given number of times for loop flowchart start last item? end statement try next item yes no
  60. 60. for loop for n in range(5): print(n) Initialization - n is a loop control variable that represents every number in a range starting at a default value of 0 range()- function to specify where to end the loop. Ends before the specified value Update step - by default n will increment by 1 Loop body - what needs to be done
  61. 61. for loop and the range() function def printNums(num): for n in range(num): print(n) n = int(input("Enter a number: " )) printNums(n) What is the output of the code segment if n is 2? ❏ Use the range() function to loop through a set of statements ❏ The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends before the specified number as parameter of the function. ❏ Inclusive of 0, exclusive of the argument/parameter specified
  62. 62. Looping from a different start value for n in range(2, 12): print(n*2) What is the output of the code segment? ❏ To loop from another starting value other than 0, specify the starting value by adding a second parameter: range(2, 6), which means values from 2 to < 6 (excluding 6):
  63. 63. Looping and using a different value to increment other than 1 for n in range(2, 30, 3): print(n) # to place the next item to be printed on the same line after the space 2 5 8 11 14 17 20 23 ❏ The range() function defaults to increment by 1 ❏ To specify another increment value other than 1, add a third parameter: range(2, 30, 3):
  64. 64. Looping and using a different value to increment other than 1 for n in range(2, 30, 3): print(n, end=" ") # to place the next item to be printed on the same line after the space 2 5 8 11 14 17 20 23 26 29 ❏ We can change the way the print function ends, using “end” ❏ Print default is to end with a hidden new line (script=“n”). We can change it to just a space using end=" "
  65. 65. We Do Create a Python program called OddsEvens with 2 functions called printOdds and printEvens. The printOdds function prints all the odd numbers from zero (0) to the number passed to the parameter. The printEvens function uses 2 parameters to set the start number and the end number, then prints all even numbers on one line, from start number to end number passed to the 2 parameters. The program output should look like this: Odd numbers from 0 to n Enter value of n: 4 1 3 Even numbers from n1 to n2: Enter value of n1: 2 Enter value of n2: 6 2 4 6 Sample Solution (teachers only)
  66. 66. You Do Allow the user to input a force and a mass of an object. Make a program that prints (using a for loop) the work done on the box after each meter and the velocity of the object. Print these values for the first 5 meters. (Advanced option, allow the user to input the max distance and the distance increment) Work = F * D KE = 0.5 * mv2 Sample Solution (teachers only)
  67. 67. Looping through a String for x in "physics": print(x) p h y s i c s ❏ You can iterate through a string value ❏ A string contains a sequence of characters. ❏ The loop control variable represents each character in the string
  68. 68. Random Numbers ❏ To generate a pseudo-random number in Python you need to import the random module to use the Python random built-in functions import random print(random.random()) # Random float: 0.0 <= x < 1.0 print(random.uniform( 2.5, 10.0)) # Random float: 2.5 <= x <= 10.0 print(random.randrange( 10)) # Integer from 0 to 9 inclusive print(random.randrange( 0, 101, 2)) # Integer from 0 to 100 inclusive
  69. 69. Submit your Python Program in 2 steps
  70. 70. 1. On PyCharm 1. Right click on the file (.py) you ant to submit 2. Choose >> Open In 3. Choose Finder
  71. 71. 2. On Finder Window 1. You should see the Python file you selected to submit on the finder window 2. That is the file you will drag and drop to the submission bin on Google classroom
  72. 72. List in Python
  73. 73. List ❏ Lists are used to store multiple items in a single variable. ❏ Lists are created using square brackets [ ] ❏ The list is changeable, meaning that we can change, add, and remove items in a list after it has been created. ❏ The elements in a list are indexed in definite sequence and the indexing of a list is done with 0 being the first index and the last index is at len(list) - 1. ❏ Structure: fruits = ["apple", "banana", "cherry"] print(fruits) 0 1 2 index numbers Prints items in list
  74. 74. Create a list with different types of items ❏ Create a list with random strings someList = ['1', 'dog', 'cat', '789'] ❏ Print the list print(someList) ❏ Get the length of the list print(len(someList)) ❏ Get the 2nd item in the list print(someList[1]) ❏ Get the 5th item in the list print(someList[4]) #Note: this doesn’t exist. This will cause an error
  75. 75. Adding and removing items from List ❏ You can add items to a list someList.append('banana') ❏ Remove items from a list someList.pop() #Removes the last item from list print(someList) someList.pop(2) #Removes the 3rd item from list print(someList) ❏ Check if an item is in a list print('dog' in someList) #checks if dog is in list
  76. 76. Looping through a list velocity = [23, 32, 45] for x in velocity: print(x) List velocity with 3 items For every item x in list velocity prints each item x Output 23 32 45
  77. 77. Looping through a list velocity = [23, 32, 45] for x in velocity: print(x, end=" ") 23 32 45 ❏ The elements in a list are indexed in definite sequence and the indexing of a list is done with 0 being the first index and the last index is at len(list) - 1. velocity = [23, 32, 45] total = 0 for x in velocity: total += x average = total / len(velocity) print("Average Velocity: ", round(average, 2)) len() - function that returns the number of elements in the list Average Velocity: 33.33 NOTE: By default, the print function ends with a new line. Passing the whitespace to the end parameter (end=' ') indicates that the end character has to be identified by whitespace and not a newline.
  78. 78. Looping through a List
  79. 79. May 18: 3a. Control Flow
  80. 80. CodeHS Practice exercises Use the following sections of the self-paced CodeHS course to review some of the concepts we have covered: Variables and Data Types Section 3.2 Section 3.5 Operators / Input / Output (Built-in Functions) Section 3.1 Section 3.3 Section 3.4 User-defined Functions Section 6.1 Section 6.2 Section 6.4
  81. 81. Control Flow Control flow statements allow you to create alternative branches in the execution of your program. They are the foundation of many of the logic in programming and in Artificial Intelligence Control flow statements are as good as the conditional statements that we create to determine those branches or paths.
  82. 82. Relational Operators Operator Meaning == equal (double equal sign) < less than <= less than or equal > greater than >= greater than or equal != not equal ❏ A relational operator is a programming language construct that tests or defines the relation between two entities. ❏ The result of using the operator will yield one (1) of two (2) possible boolean outputs (True or False) ❏ An expression that uses one or more of these operators is called a Boolean expression.
  83. 83. If Statements ❏ If statements require a boolean expression to decide if the following code will be executed. ❏ There can be zero or more elif clauses, and the else part is optional. The keyword ‘elif’ is short for ‘else if’. The elif clause requires an additional boolean statement to create an alternative path. ❏ Only one of the parts on an if..elif..elif..else statement will be executed ❏ The else part does not require a conditional and will be executed if none of the previous conditions are True def checkX(x): if x < 0: print('Negative') print('This is still the if ') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More')
  84. 84. We do Create a letterGrade application that prompts the user for the percentage earned on a test or other graded work and then displays the corresponding letter grade. The application should use your favorite grading scale Sample Output: Enter the percentage: 80 The corresponding letter grade is: B
  85. 85. You Do Complete the attached python project on BMI calculation. Use functions as appropriate Work with someone
  86. 86. 1. Logical operators (not), (and), and (or) are used to form compound boolean expressions. 2. The table below shows the order these operators will be evaluated by the compiler. 3. A compound boolean expression will evaluate to a single Boolean value (true or false). Compound or complex boolean expressions: ● grade > 70 and grade < 60 ● temp > 39 and coughing == true ● tired == true or time >= 21 ● not (initialSpeed > 30) Logical Operators Operator Boolean Algebra equivalent not ~ (⌐) and . (⋀) or + (∨)
  87. 87. Evaluating expressions with Logical Operators Example 1: (condition1 and condition2) Is true if and only if both c1 and c2 are true Example 2: (condition1 or condition2) Is true if c1 or c2 or both are true Example 3: not(condition1) Is true if and only if c1 is false
  88. 88. Truth Tables (AND, OR, NOT) If both conditions are true, the output is true. Otherwise, false and X = (A and B) A B X False False False False True False True False False True True True If both conditions are false, the output is false. Otherwise, true or X = (A or B) A B X False False False False True True True False True True True True The output is the reversed of the input not X = not A A X False True True False
  89. 89. Truth Tables (XOR, NAND, NOR) The output is true if either one condition or the other is true. Excluding the case that they both are XOR Exclusive OR X = (A ^ B) A B X False False False False True True True False True True True False The reversed of AND NAND X = not(A and B) A B Output False False True False True True True False True True True False The reversed of OR NOR X = not(A or B) A B Output False False True False True False True False False True True False
  90. 90. We do What is printed after executing the given code segment? a = True b = False c = a and b d = a or b e = not b f = a ^ b g = not(a or b) h = not(a and b) or b print(c) print(d) print(e) print(f) print(g) print(h)
  91. 91. You Do Write a program that asks for the atomic number of an element and returns the number of valence electrons and the ion charge Notes: Ensure the atomic number (atno) is between 1-20 Elements with atno <= 2 (Helium) have valence electron equal to atno Elements with atno <= 10 (Neon) have valence electron equal to atno - 2 Elements with atno <= 18 (Argon) have valence electron equal to atno - 10 Elements with valence <= 4 have equal valence and ion charge Elements with valence > 4 have ion charge equal to valence - 8
  92. 92. 4. Classes and Objects
  93. 93. CodeHS Practice exercises Use the following sections of the self-paced CodeHS course to review some of the concepts we have covered: Variables and Data Types Section 3.2 Section 3.5 Operators / Input / Output (Built-in Functions) Section 3.1 Section 3.3 Section 3.4 User-defined Functions Section 6.1 Section 6.2 Section 6.4 Selection statements (if) Section 4.1 - 4.6
  94. 94. Python Class ❏ Python is an object-oriented-programming language. ❏ Almost everything in Python is an object, with its properties and functions. ❏ Objects are patterned from real-world objects Read-world object Attributes - type - diameter Behaviour - getType - getDiameter - getSurfaceArea - getVolume Decompose object information 1. Create a Python class based on object name 2. Create an __init__ function and use the attributes as parameters 3. Create functions from the list of behaviour identified Translate to program code
  95. 95. WHY??? Why are we doing this? Writing 100 functions is fine with me! We want to break a bigger program into smaller manageable components by 1. grouping information and functions together for a specific object 2. making objects work together to perform bigger and more complex tasks
  96. 96. Remember this? TimerApp showTimer() startTime() pauseTime() stopTime() resetTime() QuizApp showInstruction() startQuiz() showQuestion() showChoices() showTimer() Physics Quiz Instructions Start Quiz Time: A group of functions only for the TimerApp Another group of functions for the QuizApp Another group of functions for the Graphical User Interface for the user to interact with
  97. 97. Python Class and Objects ❏ An object consists of : ❏ State: It is represented by the attributes of an object. It also reflects the properties of an object. ❏ Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects. ❏ Identity: It gives a unique name to an object and enables one object to interact with other objects. Identity Name of Ball State|Attribute Type Diameter Behaviors ● Informs type ● Informs diameter ● Calculates surface area ● Calculates volume
  98. 98. Writing a Python Class ClassName ❏ Uses the keyword “class” ❏ A noun, starts with a Capital letter, then follows a Camel case Class variables ❏ Indented, aligned with functions Behavior | Functions ❏ Indented ❏ Starts with def keyword ❏ In __init__ function, add the instance variables as parameters class ClassName: # class/static variable/s . . . # def __init__(instance variable/s) # def function1() # def function2()
  99. 99. We Do Translate the information of a Ball into a Python class the following the steps provided. ● Write the class and name it after the object name ● Write an __init__ function and use the instance variables as parameters ● Create user-defined functions based on the behaviour identified ● Create a runner code ○ Create 3 ball objects of instances ○ Test your code with input values ● Add static variable/s that hold/s a common value for all objects
  100. 100. Python Class and Objects ❏ An Object is an instance of a Class. ❏ A class is like a blueprint while an instance is a copy of the class with actual values. ❏ You can create many instances or objects from the class template. Without the class as a guide, you would be lost, not knowing what information is required. Class Ball State | Attributes type diameter Behaviors getType getDiameter getSurfaceArea getVolume ball1 ball2 ball3 Objects or instance of a class Class Diagram | Template
  101. 101. You Do #1 Group/Partner 1. Atom 2. Element With your group ● Identify the attributes of the given object ● Identify the behaviour of the object ● Create a class diagram of the information gathered ● Translate the diagram into a Python class program
  102. 102. Class Diagram of “Atom” Class Atom State | Attributes Name Atomic Number Mass Number Symbol Behaviors getName() getNeutronNumber getValenceElectrons() getIonCharge() atom1 atom2 atom3 Objects or instance of a class Class Diagram | Template
  103. 103. Parts of a Python Class class Dog: # Class Variable animal = 'dog' # The init method or constructor def __init__(self, breed, color): # Instance Variable self.breed = breed self.color = color def makesound(self, sound): return sound # Objects or instances of Dog class Roger = Dog( "Pug", "brown") Charlie = Dog( "Bulldog", "black") print("Breed: ", Roger.breed , " Color: ", Roger.color) print("Make sound: " , Roger.makesound( "Woof woof" )) print("Breed: ", Charlie.breed , " Color: ", Charlie.color) print("Make sound: " , Charlie.makesound( "Zzzzzzzz")) Class name Class variables | Static Constructor/Special function Instance variables User-defined method with parameter sound Calls the constructor. Creates an object or instance called Roger of type Dog and passes “Pug” as value of breed and “brown” as value of color (NOTE: All values are only specific to the instance Roger)
  104. 104. __init__ function and self keyword ❏ __init__ - a special function called a constructor. It is called when an object is created ❏ Constructors are used to initializing the object’s state. ❏ Like functions, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. ❏ It runs as soon as an object of a class is instantiated. ❏ The function is useful to do any initialization you want to do with your object. ❏ self - is a keyword that indicates that a function is an instance function or variables are instances of a class. ❏ Class methods must have an extra first parameter in the method definition. ❏ We do not give a value for this parameter when we call the method, Python provides it. ❏ If we have a method that takes no arguments, then we still have to have one argument.
  105. 105. Organizing our runner codes - def main() and if __name__ def main(): length = float(input("Enter length: ")) width = float(input("Enter width: ")) print("Area: ", getArea(length, width)) print("Perimeter: ", getPerimeter(length, width)) if __name__ == "__main__": main() # calls the main function if it exists ❏ main() function acts as the point of execution for any program ❏ The main function is normally used to control the main operation of your entire program. Using sequencing you normally complete general tasks such as requesting input, calling other functions, etc. ❏ The __name__ is a special built-in variable which evaluates to the name of the current module and normally calls the main() function.
  106. 106. You Do Create a class Element to define periodic table elements. The class should include name, atomic number. Use boolean logic to determine whether the two atoms would make a covalent, ionic, or metallic compound. Unit 2 Summative Style
  107. 107. 5. Repetition | Loops
  108. 108. while loop
  109. 109. while loop flowchart Loops and while loop ❏ Used to repeat a process (block of statements) or perform an operation multiple times ❏ while loops ❏ Run a piece of code indefinitely while a condition is met start end condition statement true false variation
  110. 110. initialize the loop control variable while condition: - what happens if condition is true - changes to control variable ● A variable is created and given an initial value. Usually a String, an int or a boolean type ● This variable can then be used as a loop control variable ● Statements to be executed when the condition is true. ● Include a variation to the control variable to eventually stop looping ● A condition (boolean expression) that has to be true for the loop to continue. ● It should include the control variable
  111. 111. Example #1 (while loop) i = 0 while i < 3: print(“gum”) i = i + 1 # or i += 1; Output ? declare i (Control variable) set i to 0 Continue while i is less than 3 At end of while loop, increase i by 1
  112. 112. while loop example with break keyword ❏ break exits the entire loop immediately ❏ What is the output after running the code segment? x = 1 while x <= 10: if x == 5: break #this exits the while loop! print("x is now:", x) x += 1
  113. 113. The while statement ❏ Loop structure that executes a set of statements as long as a condition is true ❏ The condition is a Boolean expression ❏ Will never execute if the condition is initially false What does the code segment do? response = int(input("Enter 1 or 0: ")) while response == 1: response = int(input("Enter 1 or 0: "))
  114. 114. Example: Describe what the code segment does. password = 'secret' pw = input('Enter the password: ' ) while pw != password: print('Password incorrect! Try again.' ) pw = input('Enter the password: ' ) print("You have successfully logged in!" )
  115. 115. You Do Allow the user to input an initial mass and velocity and a frictional force. Write a program to print the KE and Thermal Energy after each meter. Use a while loop to ensure that the KE does not go negative. If the user enters zero for the frictional force it should instead print “Never slows down!”