Agenda of LO CS.1.08 W3 1- Warm up about programming 10 min 2- ppt teacher demonstrate about Python 15m 3- Video about Python 5min 4- Practical work Students divided in pairs and use Anaconda : Spyder or on line Python platform to create very simple program using python -3.8.1 7 - Questions and answers as pretest about Python 5 m 8-Refelection 5 min 9- Home work 5 min Python Eng. & Educator Osama Ghandour
LO CS.1.08 W3 - Gain Interpret a work of design, implement, test and debug programs that use different data types, variables and constants. • Use strategies before, during and post (Arithmetic and Assignment).. Lesson plan Python Eng. & Educator Osama Ghandour
Warm Up Why Python Listen to this video Offline On line Python Eng. & Educator Osama Ghandour
Essential Question 1- What is the different between the data types? 2- What is the different between the Constants and Variables? Python Eng. & Educator Osama Ghandour
Essential Question 3- How can test a program and debug its errors? 4- Mention the Arithmetic and Assignment Operators, and give some examples. Python Eng. & Educator Osama Ghandour
Getting Started With Python Programming •Tutorial: creating computer programs •Variables and constants •Input and output •Operators •Common programming errors •Formatted output
James Tam Tips For Success: Programming Sections • (The previous 4 tips are still applicable but there’s some tips specific to programming): – Take extensive notes: everything in class not just what the instructor “writes down” but also what he/she “says in class”. • Some students may find when studying the lecture slides for the exam that they cannot understand concepts. • The extra “filling of the blanks” occurs during lecture so you need to annotate the slides with your own notes – After lectures have covered a particular concept/example • If you have time try writing the program on your own (without looking at the online examples or notes) in order to create a program that fulfills the same task as the example program • (It’s one thing to see the solution to a problem explained, your depth of understanding will be deeper if you have to re-create it from scratch yourself). • JT’s note: you may find this unnecessary for the simple examples in this section but it will be beneficial to do this when more complex concepts are covered (e.g. nested loops onwards)
James Tam Python • This is the name of the programming language that will be used to illustrate different programming concepts this semester: –My examples will be written in Python –Your assignments will be written in Python • Some advantages (from Python dot org) –Free –Powerful –Widely used (Google, NASA, Yahoo, Electronic Arts, some Linux operating system scripts etc.) • Named after a British comedy “Monty Python’s Flying Circus” –Official website (Python the programming language, not the Monty Python comedy troop): http://www.python.org –An overview of the web site: https://www.python.org/about/gettingstarted/
James Tam Python History • Developed in the early 1990s by Guido van Rossum. • Python was designed with a tradeoff in mind (from “Python for everyone” (Horstman and Necaise): – Pro: Python programmers could quickly write programs (and not be burdened with an overly difficult language) – Con: Python programs weren’t optimized to run as efficiently as programs written in some other languages. From: http://www.python.org/~guido/
James Tam Working From Home • Remotely login to the Computer Science network • Advantage: – The interface will be the same in the CPSC lab vs. working at home. – If you login to the correct machine then your program is guaranteed to work in the lab (pick a “Linux” based machine). – No need to transfer files because you are directly editing them on your CPSC account when you are at home • Drawback: – There is a fair learning curve at first – Example: Connect using a remote login program such as SSH or Putty • Info: http://pages.cpsc.ucalgary.ca/~tamj/resources/new_CPSC_student/ working_at_home.html • Downloads: – Working from home, use Putty: http://www.ucalgary.ca/cpsc/files/cpsc/putty.zip – Transferring files to/from home, use Filezilla: https://filezilla-project.org/ – (The remote login software SSH comes with MacOS so no download is needed). • Sometime later in the semester, in tutorial, the Teaching Assistants will show you how to use these programs.
James Tam Working From Home (Installing Python) • Alternative (OK for 217/231 but not recommended for 219/233): Getting Python (get version 3.X and not version 2.X) – http://www.python.org/download/
James Tam The First Python Program • Program name: small.py print ("hello",end="") Filename: 1small.py
James Tam Creating/Running Programs: One Operating System • The process is similar on other platforms/OS’s (the TA’s will show you how to do it on the lab computers (Linux) during tutorials). Step 1: Writing your program –You need a text editor (e.g., WordPad, Notepad, Notepad++) to enter the program. –It can be done using any editor that you want, but don’t use a word processor (e.g., MS-Word) and remember to save it as a text file ending with the suffix dot-py “.py”
James Tam Creating/Running Programs: One Operating System (2) Step 2: Translating and running your program – You need to open a command line to translate/run your Python program. – The name of the Python translator is “Python” – To translate/run your program type “python filename.py” at the command line. • The first example program would be executed by typing “python small.py” • For a program whose filename is called “output1.py” you would type “python output1.py”. Running /translating the program Output of program (result of running the program)
James Tam Important Reminders • Make sure you type the whole file name (including the part after the period) when you translate/run your program. –E.g., “python small.py” • Unless you are very familiar with your operating system when you translate/run a program you should first navigate to the directory/folder where your Python program resides. –JT: the ‘cd’ command changes your directory (Windows and UNIX although something different is needed when changing Windows drives) –Suppose my program was under: C:231 (Windows) OR /home/231 (UNIX) –To reach this location you could (shortcuts excluded for now) then type: c:231 (Windows) OR cd /home/231 (UNIX)
James Tam Variables • Set aside a location in memory. • Used to store information (temporary). – This location can store one ‘piece’ of information. • Putting another piece of information at an existing location overwrites previous information. – At most the information will be accessible as long as the program runs i.e., it’s temporary • Some types of information which can be stored in variables include: integer (whole), floating point (fractional), strings (essentially any characters you can type and more) Format (creating): <name of variable> = <Information to be stored in the variable> Examples (creating): – Integer (e.g., num1 = 10) – Floating point (e.g., num2 = 10.0) – Strings: alpha, numeric, other characters enclosed in quotes. • e.g., name = "james" • To be safe get in the habit of using double (and not single) quotes Image curtesy of James Tam slide 16
James Tam The Assignment Operator: = • The assignment operator '=' used in writing computer programs does not have the same meaning as mathematics. –Don’t mix them up! • Example: y = 3 (what is stored in ‘x’ at this point) x = y (what is stored in ‘x’,’y’ at this point) y = 6 (what is stored in ‘x’,’y’ at this point) • What is the end result? How was this derived (what are the intermediate results from each assignment/line above)? • See the program ‘2assignment.py’
James Tam Variable Naming Conventions • Python requirements: – Rules built into the Python language for writing a program. – Somewhat analogous to the grammar of a ‘human’ language. – If the rules are violated then the typical outcome is the program cannot be translated (nor run). • A language such as Python may allow for a partial execution (it runs until the error is encountered). • Style requirements: – Approaches for producing a well written program. – (The real life analogy is that something written in a human language may follow the grammar but still be poorly written). – If style requirements are not followed then the program can still be translated but there may be other problems (more on this during the term).
James Tam Variable Naming Conventions (2) 1. Style requirement: The name should be meaningful. 2. Style and Python requirement: Names must start with a letter (Python requirement) and should not begin with an underscore (style requirement). 3. Style requirement: Names are case sensitive but avoid distinguishing variable names only by case. Examples #1: age (yes) x, y (no) #2 height (yes) 2x, _height (no) #3 Name, name, nAme (no to this trio)
James Tam Variable Naming Conventions (2) 4. Style requirement: Variable names should generally be all lower case (see next point for the exception). 5. Style requirement: For names composed of multiple words separate each word by capitalizing the first letter of each word (save for the first word) or by using an underscore. (Either approach is acceptable but don’t mix and match.) 6. Python requirement: Can't be a keyword (see next slide). Examples #4: age, height, weight (yes) Age, HEIGHT (no) #5 firstName, last_name (yes to either approach)
James Tam Key Words In Python1 and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try 1 From “Starting out with Python” by Tony Gaddis
James Tam Displaying Output Using The Print() Function • This function takes zero or more arguments (inputs) – Multiple arguments are separated with commas – print() will display all the arguments followed by a blank line (move the cursor down a line). – end="" isn’t mandatory but can be useful to prevent Python from adding the extra line (when precise formatting is needed) – Zero arguments just displays a blank line • Simple Examples (3output1.py) print("hi") print("hey",end="") print("-sup?")
James Tam Print("… ") Vs. Print(<name>) • Enclosing the value in brackets with quotes means the value in between the quotes will be literally displayed onscreen. • Excluding the quotes will display the contents of a memory location. • Example: 4output2.py aString = "Some message" print(aString) print("aString")
James Tam Print("… ") Vs. Print(<name>): 2 Format: print(arg1,arg2 … )1 Example: 5output3.py num = 10.0 name = "james" print("Sup?") print("num=", end="") print(num) print() print("My name: ", name) 1 From what you’ve learned thus far each argument can be a constant string or name of a variable. Exercise 1: remove these quotes and see if you can correctly predict the results. Exercise 2: remove parts: 1) end=“” 2) print() and see if you can correctly predict the results.
James Tam • The back-slash character enclosed within quotes won’t be displayed but instead indicates that a formatting (escape) code will follow the slash: Escape Codes/Characters Escape sequence Description a Alarm: Causes the program to beep. n Newline: Moves the cursor to beginning of the next line. t Tab: Moves the cursor forward one tab stop. ' Single quote: Prints a single quote. " Double quote: Prints a double quote. Backslash: Prints one backslash.
James Tam Escape Codes (2) • Program name: 9formatting4.py print ("a*Beep!*") print ("hinthere") print ('it's') print ("hey "you"")
James Tam Escape Codes: Application • It can be used to nicely format text output (alignment output, provide separators within and between lines) • Program example: 10formatting5.py firstName = "James" lastName = "Tam" mobile = "123-4567" print("Last name:t", lastName) print("First name:t", firstName) print("Contact:t", mobile) • Escape codes for aligning text is even more valuable if the width of a field (data to be displayed) is variable e.g., comes from user input or a text file.
James Tam Extra Practice • Traces: – Modify the examples (output using format specifiers and escape codes) so that they are still valid Python statements. • Alternatively you can try finding some simple ones online or from a textbook. – Hand trace the code (execute on paper) without running the program. – Then run the program and compare the actual vs. expected result. • Program writing: – Write a program the will right-align text into 3 columns of data. – Write a program the will left-align text into 3 columns of data.
James Tam Reminder: Variables • By convention variable names are all lower case • The exception is long (multi-word) names • As the name implies their contents can change as a program runs e.g., income = 300000 income = income + interest Income = income + bonuses
James Tam Named Constants •They are similar to variables: a memory location that’s been given a name. •Unlike variables their contents shouldn’t change. •This means changes should not occur because of style reasons rather than because Python prevents the change •The naming conventions for choosing variable names generally apply to constants but the name of constants should be all UPPER CASE. (You can separate multiple words with an underscore). •Example PI = 3.14 •They are capitalized so the reader of the program can distinguish them from variables. –For some programming languages the translator will enforce the unchanging nature of the constant. –For languages such as Python it is up to the programmer to recognize a named constant and not to change it.
James Tam Why Use Named Constants 1. They make your program easier to read and understand # NO populationChange = (0.1758 – 0.1257) * currentPopulation Vs. #YES BIRTH_RATE = 17.58 MORTALITY_RATE = 0.1257 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation Avoid unnamed constants whenever possible!
James Tam Why Use Named Constants (2) 2) Makes the program easier to maintain – If the constant is referred to several times throughout the program, changing the value of the constant once will change it throughout the program. – Using named constants is regarded as “good style” when writing a computer program.
James Tam Purpose Of Named Constants (3) BIRTH_RATE = 0.998 MORTALITY_RATE = 0.1257 populationChange = 0 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation if (populationChange > 0): print("Increase") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange) elif (populationChange < 0): print("Decrease") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) else: print("No change") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
James Tam Purpose Of Named Constants (4) BIRTH_RATE = 0.998 MORTALITY_RATE = 0.1257 populationChange = 0 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation if (populationChange > 0): print("Increase") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange) elif (populationChange < 0): print("Decrease") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) else: print("No change") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) One change in the initialization of the constant changes every reference to that constant
James Tam Purpose Of Named Constants (5) BIRTH_RATE = 0.1758 MORTALITY_RATE = 0.0001 populationChange = 0 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation if (populationChange > 0): print("Increase") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange) elif (populationChange < 0): print("Decrease") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) else: print("No change") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) One change in the initialization of the constant changes every reference to that constant
James Tam When To Use A Named Constant? • (Rule of thumb): If you can assign a descriptive, useful, self- explanatory name to a constant then you probably should. • Example 1 (easy to provide self explanatory constant name) INCH_CM_RATIO = 2.54 height = height * INCH_CM_RATIO • Example 2 (providing self explanatory names for the constants is difficult) calories used = (10 x weight) + (6.25 x height) - [(5 x age) - 161]
James Tam Extra Practice • Provide a formula where it would be appropriate to use named constants (should be easy). • Provide a formula where unnamed constants may be acceptable (may be trickier). • Search for formulas in science articles online if you can’t think of any.
James Tam Section Summary: Named Constants • What is a named constant – How does it differ from a variable – How does it differ from an unnamed constant – What are some reasons for using named constants • Naming conventions for named constants
James Tam Arithmetic Operators Operator Description Example = Assignment num = 7 + Addition num = 2 + 2 - Subtraction num = 6 - 4 * Multiplication num = 5 * 4 / Division num = 9 / 2 // Integer division num = 9 // 2 % Modulo num = 9 % 2 ** Exponent num = 9 ** 2 4.5 4 1 81
James Tam • First level of precedence: top to bottom • Second level of precedence – If there are multiple operations that are on the same level then precedence goes from left to right. Order Of Operation () Brackets (inner before outer) ** Exponent *, /, //, % Multiplication, division, modulo +, - Addition, subtraction = Assignment Example x = 3 * 2 ** 3 Vs. x = (3 * 2) ** 3
James Tam Order Of Operation And Style • Even for languages where there are clear rules of precedence (e.g., Java, Python) it’s good style to explicitly bracket your operations and use blank spaces as separators. x = (a * b) + (c / d) • It not only makes it easier to read complex formulas but also a good habit for languages where precedence is not always clear (e.g., C++, C).
James Tam Input •The computer program getting string information from the user. •Strings cannot be used for calculations (information for getting numeric input will provided shortly). •Format: <variable name> = input() OR <variable name> = input("<Prompting message>") •Example: Program name: 11input1.py print("What is your name: ") name = input() OR name = input("What is your name: ") OR print("What is your name: ", end="") name = input() Avoid alignment issues such as this
James Tam Variables: Storing Information (If There Is Time) • On the computer all information is stored in binary (2 states) – Example: RAM/memory stores information in a series of on-off combinations – A single off/off combination is referred to as a ‘bit’ Bit on off OR Byte •8 bits
James Tam Can be stored as Variables: Storing Information (If There Is Time) • Information must be converted into binary to be stored on a computer. User enters 13 slide 44
James Tam • 1 bit is used to represent the sign, the rest is used to store the size of the number – Sign bit: 1/on = negative, 0/off = positive • Format: • Previous example Storing Integer Information (If There Is Time) slide 45 Digits representing the size of the number (all the remaining bits) Negative number Positive number 1 bit Positive number Size of number, in this case = 13
James Tam Storing Real Numbers In The Form Of Floating Point (If There Is Time) – Mantissa: digits of the number being stored – Exponent: the direction (negative = left, positive=right) and the number of places the decimal point must move (‘float’) when storing the real number as a floating point value. • Examples with 5 digits used to represent the mantissa: – e.g. One: 123.45 is represented as 12345 * 10-2 – e.g. Two: 0.12 is represented as 12000 * 10-5 – e.g. Three: 123456 is represented as 12345 * 101 • Remember: Using floating point numbers may result in a loss of accuracy (the float is an approximation of the real value to be stored). Sign Mantissa Exponent 1 bit Several bits Several bits
James Tam • Typically characters are encoded using ASCII • Each character is mapped to a numeric value – E.g., ‘A’ = 65, ‘B’ = 66, ‘a’ = 97, ‘2’ = 50 • These numeric values are stored in the computer using binary Storing Character Information (If There Is Time) Character ASCII numeric code Binary code ‘A’ 65 01000001 ‘B’ 66 01000010 ‘a’ 97 01100001 ‘2’ 50 00110010
James Tam Storing Information: Bottom Line • Why it important to know that different types of information is stored differently? – One motivation: sometimes students don’t why it’s significant that “123” is not the same as the number 123. – Certain operations only apply to certain types of information and can produce errors or unexpected results when applied to other types of information. • Example num = input("Enter a number") numHalved = num / 2
James Tam Converting Between Different Types Of Information • Example motivation: you may want numerical information to be stored as a string (for built in string functions e.g., check if a string consists only of numbers) but also you want to perform calculations). • Some of the conversion mechanisms (functions) available in Python: Format: int(<value to convert>) float(<value to convert>) str(<value to convert>) Examples: Program name: 12convert1.py x = 10.9 y = int(x) print(x,y) Conversion function ( ) Value to convert Converted result
James Tam Converting Between Different Types Of Information (2) Examples: Program name: 13convert2.py x = "100" y = "-10.5" print(x + y) print(int(x) + float(y))
James Tam Converting Types: Extra Practice • Determine the output of the following program: print(12+33) print('12'+'33') x = 12 y = 21 print(x+y) print(str(x)+str(y))
James Tam Converting Between Different Types Of Information: Getting Numeric Input • The ‘input()’ function only returns string information so the value returned must be converted to the appropriate type as needed. – Example Program name: 14convert3.py # No conversion performed: problem! HUMAN_CAT_AGE_RATIO = 7 age = input("What is your age in years: ") catAge = age * HUMAN_CAT_AGE_RATIO print ("Age in cat years: ", catAge) • ‘Age’ refers to a string not a number. • The ‘*’ is not mathematical multiplication
James Tam Converting Between Different Types Of Information: Getting Numeric Input (2) # Input converted: Problem solved! HUMAN_CAT_AGE_RATIO = 7 age = int(input("What is your age in years: ")) catAge = age * HUMAN_CAT_AGE_RATIO print("Age in cat years: ", catAge) • ‘Age’ converted to an integer. • The ‘*’ now multiplies a numeric value.
James Tam Section Summary: Input, Representations • How to get user input in Python • How do the different types of variables store/represent information (optional/extra for now) • How/why to convert between different types
James Tam Program Documentation / comments • Program documentation: Used to provide information about a computer program to another programmer (writes or modifies the program). • This is different from a user manual which is written for people who will use the program. • Documentation is written inside the same file as the computer program (when you see the computer program you can see the documentation). • The purpose is to help other programmers understand the program: what the different parts of the program do, what are some of it’s limitations etc.
James Tam Program Documentation (2) • Doesn’t contain instructions for the computer to execute. • Not translated into machine language. • Consists of information for the reader of the program: – What does the program as a while do e.g., calculate taxes. – What are the specific features of the program e.g., it calculates personal or small business tax. – What are it’s limitations e.g., it only follows Canadian tax laws and cannot be used in the US. In Canada it doesn’t calculate taxes for organizations with yearly gross earnings over $1 billion. – What is the version of the program • If you don’t use numbers for the different versions of your program then simply use dates (tie versions with program features – more on this in a moment “Program versioning and backups”).
James Tam Program Documentation (3) • Format (single line documentation): # <Documentation> • Examples: # Tax-It v1.0: This program will electronically calculate # your tax return. This program will only allow you to complete # a Canadian tax return. The number sign ‘#” flags the translator that the remainder of the line is documentation.
James Tam Program Documentation (4) • Format (multiline documentation): """ <Start of documentation> ... <End of documentation> """ • Examples: """ Tax-It v1.0: This program will electronically calculate # your tax return. This program will only allow you to complete # a Canadian tax return. """
James Tam Program Versioning And Back Ups • As significant program features have been completed (tested and the errors removed/debugged) a new version should be saved in a separate file. # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.Sept20 # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.py Make backup file
James Tam Program Versioning And Back Ups • As significant program features have been completed (tested and the errors removed/debugged) a new version should be saved in a separate file. # Version: Oct 2, 2012 # Program features: # (1) Save game # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.py # Version: Oct 2, 2012 # Program features: # (1) Save game # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.Oct2 Make new backup file # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.Sept20
James Tam Backing Up Your Work • Do this every time that you have completed a significant milestone in your program. – What is ‘significant’ will vary between people but make sure you do this periodically. • Ideally the backup file should be stored in a separate directory/folder (better yet on a separate device and/or using an online method such as an email attachment or ‘cloud’ storage). • Common student reason for not making copies: “Backing up files takes time!” • Compare: – Time to copy a file: ~10 seconds (generous in some cases). – Time to re-write your program to implement the feature again: 10 minutes (might be overly conservative in some cases). • Failing to backup your work is not a sufficient reason for receiving an extension.
James Tam Over-Documenting A Program • Except for very small programs documentation should be included • However it is possible to over-document a program • (Stating the obvious) num = num + 1 # Variable num increased by one • (Documentation can be useful in this case) lastRow = SIZE – 1 # Row numbering begins at zero Example: there are 3 rows in a list (size = 3) – First row = 0 – Second row = 1 – Third (and last) row = 2 (equals 3-1 = 2)
James Tam Section Summary: Documentation • What is program documentation • What sort of documentation should be written for your programs • How program documentation ties into program versioning and backups
James Tam Types Of Programming Errors 1. Syntax/translation errors 2. Runtime errors 3. Logic errors
James Tam DrawingPanel • To create a window, create a drawingpanel and its graphical pen, which we'll call g : from drawingpanel import * panel = drawingpanel(width, height) g = panel.get_graphics() ... (draw shapes here) ... panel.mainloop() • The window has nothing on it, but we can draw shapes and lines on it by sending commands to g . – Example: g.create_rectangle(10, 30, 60, 35) g.create_oval(80, 40, 50, 70) g.create_line(50, 50, 90, 70) Eng. & Educator Osama Ghandour
James Tam Graphical commands Command Description g.create_line(x1, y1, x2, y2) a line between (x1, y1), (x2, y2) g.create_oval(x1, y1, x2, y2) the largest oval that fits in a box with top-left corner at (x1, y1) and bottom-left corner at (x2, y2) g.create_rectangle(x1, y1, x2, y2) the rectangle with top-left corner at (x1, y1), bottom-left at (x2, y2) g.create_text(x, y, text="text") the given text at (x, y) • The above commands can accept optional outline and fill colors. g.create_rectangle(10, 40, 22, 65, fill="red", outline="blue") • The coordinate system is y-inverted: (0, 0) (200, 100) Eng. & Educator Osama Ghandour
James Tam Drawing with loops • We can draw many repetitions of the same item at different x/y positions with for loops. – The x or y assignment expression contains the loop counter, i, so that in each pass of the loop, when i changes, so does x or y. from drawingpanel import * window = drawingpanel(500, 400) g = window.get_graphics() for i in range(1, 11): x = 100 + 20 * i y = 5 + 20 * i g.create_oval(x, y, x + 50, y + 50, fill="red") window.mainloop() • Exercise: Draw the figure at right. Eng. & Educator Osama Ghandour
Check your email to Solve the Online auto answered quiz 15 min after school the quiz will be closed in 10:00pm after tomorrow Eng. & Educator Osama Ghandour Python
Repetition (loops) in Python. Listen to this video Offline On line Eng. & Educator Osama Ghandour Python
Selection (if/else) in Python Listen to this video Offline On line Eng. & Educator Osama Ghandour Python
James Tam Summary 1-Variables – rules for naming . 2-Constants. 3- Run a program debug it . 4-documentation - comments. 5-Back up a progarm. Eng. & Educator Osama Ghandour Python
James Tam Reflection • What is your goal to accomplish in next week End Using Python? Eng. & Educator Osama Ghandour Python
James Tam Home work (s. proj.) 1 • Create a presentation contains some concepts of computer languages (Python) and display the Concepts of Repetition (loops) and Selection (if/else)following the bellow rubric . Eng. & Educator Osama Ghandour Python
James Tam Home work 2 (s. proj.) • Create a small program as a PBL in Collaboration work using integration to your Capstone project . Eng. & Educator Osama Ghandour Python
James Tam Rubaric Blue Design a presentation showing Python to contain some concepts Repetition (loops) and Selection (if/else) Green Design a presentation showing Python to contain one or 2 Repetition (loops) and Selection (if/else). Yellow missing two points of green level. Read No presentation . Eng. & Educator Osama Ghandour Python
James Tam Resources • https://www.youtube.com/user/osmgg2 Other materials: • https://www.sololearn.com • https://www.w3schools.com • www.python.org • “Learning Python,” 2nd edition, Mark Lutz and David Ascher (O'Reilly, Sebastopol, CA, 2004) (Thorough. Hard to get into as a quick read) Eng. & Educator Osama Ghandour Python
James Tam Learn and practice through on line web sites https://www.thewebevolved.com https://www.123test.com/ https://www.wscubetech.com/ https://www.w3schools.com/ https://www.guru99.com https://codescracker.com/exam/review.php https://www.arealme.com/left-right-brain/en/ https://www.proprofs.com/ https://www.geeksforgeeks.org/ https://www.tutorialspoint.com https://www.sololearn.com http://www.littlewebhut.com/ Eng. & Educator Osama Ghandour Python
James Tam If you do not feel happy, smile and pretend to be happy. •Smiling produces seratonin which is a neurotransmitter linked with feelings of happiness
Thanks Eng. & Educator Osama Ghandour Python
James Tam https://twitter.com/osamageris https://www.linkedin.com/in/osamaghandour/ https://www.youtube.com/user/osmgg2 https://www.facebook.com/osama.g.geris Eng. & Educator Osama Ghandour Python

Programming intro variables constants - arithmetic and assignment operators

  • 1.
    Agenda of LOCS.1.08 W3 1- Warm up about programming 10 min 2- ppt teacher demonstrate about Python 15m 3- Video about Python 5min 4- Practical work Students divided in pairs and use Anaconda : Spyder or on line Python platform to create very simple program using python -3.8.1 7 - Questions and answers as pretest about Python 5 m 8-Refelection 5 min 9- Home work 5 min Python Eng. & Educator Osama Ghandour
  • 2.
    LO CS.1.08 W3- Gain Interpret a work of design, implement, test and debug programs that use different data types, variables and constants. • Use strategies before, during and post (Arithmetic and Assignment).. Lesson plan Python Eng. & Educator Osama Ghandour
  • 3.
    Warm Up WhyPython Listen to this video Offline On line Python Eng. & Educator Osama Ghandour
  • 4.
    Essential Question 1- Whatis the different between the data types? 2- What is the different between the Constants and Variables? Python Eng. & Educator Osama Ghandour
  • 5.
    Essential Question 3- Howcan test a program and debug its errors? 4- Mention the Arithmetic and Assignment Operators, and give some examples. Python Eng. & Educator Osama Ghandour
  • 6.
    Getting Started WithPython Programming •Tutorial: creating computer programs •Variables and constants •Input and output •Operators •Common programming errors •Formatted output
  • 7.
    James Tam Tips ForSuccess: Programming Sections • (The previous 4 tips are still applicable but there’s some tips specific to programming): – Take extensive notes: everything in class not just what the instructor “writes down” but also what he/she “says in class”. • Some students may find when studying the lecture slides for the exam that they cannot understand concepts. • The extra “filling of the blanks” occurs during lecture so you need to annotate the slides with your own notes – After lectures have covered a particular concept/example • If you have time try writing the program on your own (without looking at the online examples or notes) in order to create a program that fulfills the same task as the example program • (It’s one thing to see the solution to a problem explained, your depth of understanding will be deeper if you have to re-create it from scratch yourself). • JT’s note: you may find this unnecessary for the simple examples in this section but it will be beneficial to do this when more complex concepts are covered (e.g. nested loops onwards)
  • 8.
    James Tam Python • Thisis the name of the programming language that will be used to illustrate different programming concepts this semester: –My examples will be written in Python –Your assignments will be written in Python • Some advantages (from Python dot org) –Free –Powerful –Widely used (Google, NASA, Yahoo, Electronic Arts, some Linux operating system scripts etc.) • Named after a British comedy “Monty Python’s Flying Circus” –Official website (Python the programming language, not the Monty Python comedy troop): http://www.python.org –An overview of the web site: https://www.python.org/about/gettingstarted/
  • 9.
    James Tam Python History •Developed in the early 1990s by Guido van Rossum. • Python was designed with a tradeoff in mind (from “Python for everyone” (Horstman and Necaise): – Pro: Python programmers could quickly write programs (and not be burdened with an overly difficult language) – Con: Python programs weren’t optimized to run as efficiently as programs written in some other languages. From: http://www.python.org/~guido/
  • 10.
    James Tam Working FromHome • Remotely login to the Computer Science network • Advantage: – The interface will be the same in the CPSC lab vs. working at home. – If you login to the correct machine then your program is guaranteed to work in the lab (pick a “Linux” based machine). – No need to transfer files because you are directly editing them on your CPSC account when you are at home • Drawback: – There is a fair learning curve at first – Example: Connect using a remote login program such as SSH or Putty • Info: http://pages.cpsc.ucalgary.ca/~tamj/resources/new_CPSC_student/ working_at_home.html • Downloads: – Working from home, use Putty: http://www.ucalgary.ca/cpsc/files/cpsc/putty.zip – Transferring files to/from home, use Filezilla: https://filezilla-project.org/ – (The remote login software SSH comes with MacOS so no download is needed). • Sometime later in the semester, in tutorial, the Teaching Assistants will show you how to use these programs.
  • 11.
    James Tam Working FromHome (Installing Python) • Alternative (OK for 217/231 but not recommended for 219/233): Getting Python (get version 3.X and not version 2.X) – http://www.python.org/download/
  • 12.
    James Tam The FirstPython Program • Program name: small.py print ("hello",end="") Filename: 1small.py
  • 13.
    James Tam Creating/Running Programs:One Operating System • The process is similar on other platforms/OS’s (the TA’s will show you how to do it on the lab computers (Linux) during tutorials). Step 1: Writing your program –You need a text editor (e.g., WordPad, Notepad, Notepad++) to enter the program. –It can be done using any editor that you want, but don’t use a word processor (e.g., MS-Word) and remember to save it as a text file ending with the suffix dot-py “.py”
  • 14.
    James Tam Creating/Running Programs:One Operating System (2) Step 2: Translating and running your program – You need to open a command line to translate/run your Python program. – The name of the Python translator is “Python” – To translate/run your program type “python filename.py” at the command line. • The first example program would be executed by typing “python small.py” • For a program whose filename is called “output1.py” you would type “python output1.py”. Running /translating the program Output of program (result of running the program)
  • 15.
    James Tam Important Reminders •Make sure you type the whole file name (including the part after the period) when you translate/run your program. –E.g., “python small.py” • Unless you are very familiar with your operating system when you translate/run a program you should first navigate to the directory/folder where your Python program resides. –JT: the ‘cd’ command changes your directory (Windows and UNIX although something different is needed when changing Windows drives) –Suppose my program was under: C:231 (Windows) OR /home/231 (UNIX) –To reach this location you could (shortcuts excluded for now) then type: c:231 (Windows) OR cd /home/231 (UNIX)
  • 16.
    James Tam Variables • Setaside a location in memory. • Used to store information (temporary). – This location can store one ‘piece’ of information. • Putting another piece of information at an existing location overwrites previous information. – At most the information will be accessible as long as the program runs i.e., it’s temporary • Some types of information which can be stored in variables include: integer (whole), floating point (fractional), strings (essentially any characters you can type and more) Format (creating): <name of variable> = <Information to be stored in the variable> Examples (creating): – Integer (e.g., num1 = 10) – Floating point (e.g., num2 = 10.0) – Strings: alpha, numeric, other characters enclosed in quotes. • e.g., name = "james" • To be safe get in the habit of using double (and not single) quotes Image curtesy of James Tam slide 16
  • 17.
    James Tam The AssignmentOperator: = • The assignment operator '=' used in writing computer programs does not have the same meaning as mathematics. –Don’t mix them up! • Example: y = 3 (what is stored in ‘x’ at this point) x = y (what is stored in ‘x’,’y’ at this point) y = 6 (what is stored in ‘x’,’y’ at this point) • What is the end result? How was this derived (what are the intermediate results from each assignment/line above)? • See the program ‘2assignment.py’
  • 18.
    James Tam Variable NamingConventions • Python requirements: – Rules built into the Python language for writing a program. – Somewhat analogous to the grammar of a ‘human’ language. – If the rules are violated then the typical outcome is the program cannot be translated (nor run). • A language such as Python may allow for a partial execution (it runs until the error is encountered). • Style requirements: – Approaches for producing a well written program. – (The real life analogy is that something written in a human language may follow the grammar but still be poorly written). – If style requirements are not followed then the program can still be translated but there may be other problems (more on this during the term).
  • 19.
    James Tam Variable NamingConventions (2) 1. Style requirement: The name should be meaningful. 2. Style and Python requirement: Names must start with a letter (Python requirement) and should not begin with an underscore (style requirement). 3. Style requirement: Names are case sensitive but avoid distinguishing variable names only by case. Examples #1: age (yes) x, y (no) #2 height (yes) 2x, _height (no) #3 Name, name, nAme (no to this trio)
  • 20.
    James Tam Variable NamingConventions (2) 4. Style requirement: Variable names should generally be all lower case (see next point for the exception). 5. Style requirement: For names composed of multiple words separate each word by capitalizing the first letter of each word (save for the first word) or by using an underscore. (Either approach is acceptable but don’t mix and match.) 6. Python requirement: Can't be a keyword (see next slide). Examples #4: age, height, weight (yes) Age, HEIGHT (no) #5 firstName, last_name (yes to either approach)
  • 21.
    James Tam Key WordsIn Python1 and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try 1 From “Starting out with Python” by Tony Gaddis
  • 22.
    James Tam Displaying OutputUsing The Print() Function • This function takes zero or more arguments (inputs) – Multiple arguments are separated with commas – print() will display all the arguments followed by a blank line (move the cursor down a line). – end="" isn’t mandatory but can be useful to prevent Python from adding the extra line (when precise formatting is needed) – Zero arguments just displays a blank line • Simple Examples (3output1.py) print("hi") print("hey",end="") print("-sup?")
  • 23.
    James Tam Print("… ")Vs. Print(<name>) • Enclosing the value in brackets with quotes means the value in between the quotes will be literally displayed onscreen. • Excluding the quotes will display the contents of a memory location. • Example: 4output2.py aString = "Some message" print(aString) print("aString")
  • 24.
    James Tam Print("… ")Vs. Print(<name>): 2 Format: print(arg1,arg2 … )1 Example: 5output3.py num = 10.0 name = "james" print("Sup?") print("num=", end="") print(num) print() print("My name: ", name) 1 From what you’ve learned thus far each argument can be a constant string or name of a variable. Exercise 1: remove these quotes and see if you can correctly predict the results. Exercise 2: remove parts: 1) end=“” 2) print() and see if you can correctly predict the results.
  • 25.
    James Tam • Theback-slash character enclosed within quotes won’t be displayed but instead indicates that a formatting (escape) code will follow the slash: Escape Codes/Characters Escape sequence Description a Alarm: Causes the program to beep. n Newline: Moves the cursor to beginning of the next line. t Tab: Moves the cursor forward one tab stop. ' Single quote: Prints a single quote. " Double quote: Prints a double quote. Backslash: Prints one backslash.
  • 26.
    James Tam Escape Codes(2) • Program name: 9formatting4.py print ("a*Beep!*") print ("hinthere") print ('it's') print ("hey "you"")
  • 27.
    James Tam Escape Codes:Application • It can be used to nicely format text output (alignment output, provide separators within and between lines) • Program example: 10formatting5.py firstName = "James" lastName = "Tam" mobile = "123-4567" print("Last name:t", lastName) print("First name:t", firstName) print("Contact:t", mobile) • Escape codes for aligning text is even more valuable if the width of a field (data to be displayed) is variable e.g., comes from user input or a text file.
  • 28.
    James Tam Extra Practice •Traces: – Modify the examples (output using format specifiers and escape codes) so that they are still valid Python statements. • Alternatively you can try finding some simple ones online or from a textbook. – Hand trace the code (execute on paper) without running the program. – Then run the program and compare the actual vs. expected result. • Program writing: – Write a program the will right-align text into 3 columns of data. – Write a program the will left-align text into 3 columns of data.
  • 29.
    James Tam Reminder: Variables •By convention variable names are all lower case • The exception is long (multi-word) names • As the name implies their contents can change as a program runs e.g., income = 300000 income = income + interest Income = income + bonuses
  • 30.
    James Tam Named Constants •Theyare similar to variables: a memory location that’s been given a name. •Unlike variables their contents shouldn’t change. •This means changes should not occur because of style reasons rather than because Python prevents the change •The naming conventions for choosing variable names generally apply to constants but the name of constants should be all UPPER CASE. (You can separate multiple words with an underscore). •Example PI = 3.14 •They are capitalized so the reader of the program can distinguish them from variables. –For some programming languages the translator will enforce the unchanging nature of the constant. –For languages such as Python it is up to the programmer to recognize a named constant and not to change it.
  • 31.
    James Tam Why UseNamed Constants 1. They make your program easier to read and understand # NO populationChange = (0.1758 – 0.1257) * currentPopulation Vs. #YES BIRTH_RATE = 17.58 MORTALITY_RATE = 0.1257 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation Avoid unnamed constants whenever possible!
  • 32.
    James Tam Why UseNamed Constants (2) 2) Makes the program easier to maintain – If the constant is referred to several times throughout the program, changing the value of the constant once will change it throughout the program. – Using named constants is regarded as “good style” when writing a computer program.
  • 33.
    James Tam Purpose OfNamed Constants (3) BIRTH_RATE = 0.998 MORTALITY_RATE = 0.1257 populationChange = 0 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation if (populationChange > 0): print("Increase") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange) elif (populationChange < 0): print("Decrease") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) else: print("No change") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange)
  • 34.
    James Tam Purpose OfNamed Constants (4) BIRTH_RATE = 0.998 MORTALITY_RATE = 0.1257 populationChange = 0 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation if (populationChange > 0): print("Increase") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange) elif (populationChange < 0): print("Decrease") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) else: print("No change") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) One change in the initialization of the constant changes every reference to that constant
  • 35.
    James Tam Purpose OfNamed Constants (5) BIRTH_RATE = 0.1758 MORTALITY_RATE = 0.0001 populationChange = 0 currentPopulation = 1000000 populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation if (populationChange > 0): print("Increase") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, " Population change:", populationChange) elif (populationChange < 0): print("Decrease") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) else: print("No change") print("Birth rate:", BIRTH_RATE, " Mortality rate:", MORTALITY_RATE, "Population change:", populationChange) One change in the initialization of the constant changes every reference to that constant
  • 36.
    James Tam When ToUse A Named Constant? • (Rule of thumb): If you can assign a descriptive, useful, self- explanatory name to a constant then you probably should. • Example 1 (easy to provide self explanatory constant name) INCH_CM_RATIO = 2.54 height = height * INCH_CM_RATIO • Example 2 (providing self explanatory names for the constants is difficult) calories used = (10 x weight) + (6.25 x height) - [(5 x age) - 161]
  • 37.
    James Tam Extra Practice •Provide a formula where it would be appropriate to use named constants (should be easy). • Provide a formula where unnamed constants may be acceptable (may be trickier). • Search for formulas in science articles online if you can’t think of any.
  • 38.
    James Tam Section Summary:Named Constants • What is a named constant – How does it differ from a variable – How does it differ from an unnamed constant – What are some reasons for using named constants • Naming conventions for named constants
  • 39.
    James Tam Arithmetic Operators OperatorDescription Example = Assignment num = 7 + Addition num = 2 + 2 - Subtraction num = 6 - 4 * Multiplication num = 5 * 4 / Division num = 9 / 2 // Integer division num = 9 // 2 % Modulo num = 9 % 2 ** Exponent num = 9 ** 2 4.5 4 1 81
  • 40.
    James Tam • Firstlevel of precedence: top to bottom • Second level of precedence – If there are multiple operations that are on the same level then precedence goes from left to right. Order Of Operation () Brackets (inner before outer) ** Exponent *, /, //, % Multiplication, division, modulo +, - Addition, subtraction = Assignment Example x = 3 * 2 ** 3 Vs. x = (3 * 2) ** 3
  • 41.
    James Tam Order OfOperation And Style • Even for languages where there are clear rules of precedence (e.g., Java, Python) it’s good style to explicitly bracket your operations and use blank spaces as separators. x = (a * b) + (c / d) • It not only makes it easier to read complex formulas but also a good habit for languages where precedence is not always clear (e.g., C++, C).
  • 42.
    James Tam Input •The computerprogram getting string information from the user. •Strings cannot be used for calculations (information for getting numeric input will provided shortly). •Format: <variable name> = input() OR <variable name> = input("<Prompting message>") •Example: Program name: 11input1.py print("What is your name: ") name = input() OR name = input("What is your name: ") OR print("What is your name: ", end="") name = input() Avoid alignment issues such as this
  • 43.
    James Tam Variables: StoringInformation (If There Is Time) • On the computer all information is stored in binary (2 states) – Example: RAM/memory stores information in a series of on-off combinations – A single off/off combination is referred to as a ‘bit’ Bit on off OR Byte •8 bits
  • 44.
    James Tam Can bestored as Variables: Storing Information (If There Is Time) • Information must be converted into binary to be stored on a computer. User enters 13 slide 44
  • 45.
    James Tam • 1bit is used to represent the sign, the rest is used to store the size of the number – Sign bit: 1/on = negative, 0/off = positive • Format: • Previous example Storing Integer Information (If There Is Time) slide 45 Digits representing the size of the number (all the remaining bits) Negative number Positive number 1 bit Positive number Size of number, in this case = 13
  • 46.
    James Tam Storing RealNumbers In The Form Of Floating Point (If There Is Time) – Mantissa: digits of the number being stored – Exponent: the direction (negative = left, positive=right) and the number of places the decimal point must move (‘float’) when storing the real number as a floating point value. • Examples with 5 digits used to represent the mantissa: – e.g. One: 123.45 is represented as 12345 * 10-2 – e.g. Two: 0.12 is represented as 12000 * 10-5 – e.g. Three: 123456 is represented as 12345 * 101 • Remember: Using floating point numbers may result in a loss of accuracy (the float is an approximation of the real value to be stored). Sign Mantissa Exponent 1 bit Several bits Several bits
  • 47.
    James Tam • Typicallycharacters are encoded using ASCII • Each character is mapped to a numeric value – E.g., ‘A’ = 65, ‘B’ = 66, ‘a’ = 97, ‘2’ = 50 • These numeric values are stored in the computer using binary Storing Character Information (If There Is Time) Character ASCII numeric code Binary code ‘A’ 65 01000001 ‘B’ 66 01000010 ‘a’ 97 01100001 ‘2’ 50 00110010
  • 48.
    James Tam Storing Information:Bottom Line • Why it important to know that different types of information is stored differently? – One motivation: sometimes students don’t why it’s significant that “123” is not the same as the number 123. – Certain operations only apply to certain types of information and can produce errors or unexpected results when applied to other types of information. • Example num = input("Enter a number") numHalved = num / 2
  • 49.
    James Tam Converting BetweenDifferent Types Of Information • Example motivation: you may want numerical information to be stored as a string (for built in string functions e.g., check if a string consists only of numbers) but also you want to perform calculations). • Some of the conversion mechanisms (functions) available in Python: Format: int(<value to convert>) float(<value to convert>) str(<value to convert>) Examples: Program name: 12convert1.py x = 10.9 y = int(x) print(x,y) Conversion function ( ) Value to convert Converted result
  • 50.
    James Tam Converting BetweenDifferent Types Of Information (2) Examples: Program name: 13convert2.py x = "100" y = "-10.5" print(x + y) print(int(x) + float(y))
  • 51.
    James Tam Converting Types:Extra Practice • Determine the output of the following program: print(12+33) print('12'+'33') x = 12 y = 21 print(x+y) print(str(x)+str(y))
  • 52.
    James Tam Converting BetweenDifferent Types Of Information: Getting Numeric Input • The ‘input()’ function only returns string information so the value returned must be converted to the appropriate type as needed. – Example Program name: 14convert3.py # No conversion performed: problem! HUMAN_CAT_AGE_RATIO = 7 age = input("What is your age in years: ") catAge = age * HUMAN_CAT_AGE_RATIO print ("Age in cat years: ", catAge) • ‘Age’ refers to a string not a number. • The ‘*’ is not mathematical multiplication
  • 53.
    James Tam Converting BetweenDifferent Types Of Information: Getting Numeric Input (2) # Input converted: Problem solved! HUMAN_CAT_AGE_RATIO = 7 age = int(input("What is your age in years: ")) catAge = age * HUMAN_CAT_AGE_RATIO print("Age in cat years: ", catAge) • ‘Age’ converted to an integer. • The ‘*’ now multiplies a numeric value.
  • 54.
    James Tam Section Summary:Input, Representations • How to get user input in Python • How do the different types of variables store/represent information (optional/extra for now) • How/why to convert between different types
  • 55.
    James Tam Program Documentation/ comments • Program documentation: Used to provide information about a computer program to another programmer (writes or modifies the program). • This is different from a user manual which is written for people who will use the program. • Documentation is written inside the same file as the computer program (when you see the computer program you can see the documentation). • The purpose is to help other programmers understand the program: what the different parts of the program do, what are some of it’s limitations etc.
  • 56.
    James Tam Program Documentation(2) • Doesn’t contain instructions for the computer to execute. • Not translated into machine language. • Consists of information for the reader of the program: – What does the program as a while do e.g., calculate taxes. – What are the specific features of the program e.g., it calculates personal or small business tax. – What are it’s limitations e.g., it only follows Canadian tax laws and cannot be used in the US. In Canada it doesn’t calculate taxes for organizations with yearly gross earnings over $1 billion. – What is the version of the program • If you don’t use numbers for the different versions of your program then simply use dates (tie versions with program features – more on this in a moment “Program versioning and backups”).
  • 57.
    James Tam Program Documentation(3) • Format (single line documentation): # <Documentation> • Examples: # Tax-It v1.0: This program will electronically calculate # your tax return. This program will only allow you to complete # a Canadian tax return. The number sign ‘#” flags the translator that the remainder of the line is documentation.
  • 58.
    James Tam Program Documentation(4) • Format (multiline documentation): """ <Start of documentation> ... <End of documentation> """ • Examples: """ Tax-It v1.0: This program will electronically calculate # your tax return. This program will only allow you to complete # a Canadian tax return. """
  • 59.
    James Tam Program VersioningAnd Back Ups • As significant program features have been completed (tested and the errors removed/debugged) a new version should be saved in a separate file. # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.Sept20 # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.py Make backup file
  • 60.
    James Tam Program VersioningAnd Back Ups • As significant program features have been completed (tested and the errors removed/debugged) a new version should be saved in a separate file. # Version: Oct 2, 2012 # Program features: # (1) Save game # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.py # Version: Oct 2, 2012 # Program features: # (1) Save game # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.Oct2 Make new backup file # Version: Sept 20, 2012 # Program features: # (1) Load game # (2) Show game world Game.Sept20
  • 61.
    James Tam Backing UpYour Work • Do this every time that you have completed a significant milestone in your program. – What is ‘significant’ will vary between people but make sure you do this periodically. • Ideally the backup file should be stored in a separate directory/folder (better yet on a separate device and/or using an online method such as an email attachment or ‘cloud’ storage). • Common student reason for not making copies: “Backing up files takes time!” • Compare: – Time to copy a file: ~10 seconds (generous in some cases). – Time to re-write your program to implement the feature again: 10 minutes (might be overly conservative in some cases). • Failing to backup your work is not a sufficient reason for receiving an extension.
  • 62.
    James Tam Over-Documenting AProgram • Except for very small programs documentation should be included • However it is possible to over-document a program • (Stating the obvious) num = num + 1 # Variable num increased by one • (Documentation can be useful in this case) lastRow = SIZE – 1 # Row numbering begins at zero Example: there are 3 rows in a list (size = 3) – First row = 0 – Second row = 1 – Third (and last) row = 2 (equals 3-1 = 2)
  • 63.
    James Tam Section Summary:Documentation • What is program documentation • What sort of documentation should be written for your programs • How program documentation ties into program versioning and backups
  • 64.
    James Tam Types OfProgramming Errors 1. Syntax/translation errors 2. Runtime errors 3. Logic errors
  • 65.
    James Tam DrawingPanel • Tocreate a window, create a drawingpanel and its graphical pen, which we'll call g : from drawingpanel import * panel = drawingpanel(width, height) g = panel.get_graphics() ... (draw shapes here) ... panel.mainloop() • The window has nothing on it, but we can draw shapes and lines on it by sending commands to g . – Example: g.create_rectangle(10, 30, 60, 35) g.create_oval(80, 40, 50, 70) g.create_line(50, 50, 90, 70) Eng. & Educator Osama Ghandour
  • 66.
    James Tam Graphical commands CommandDescription g.create_line(x1, y1, x2, y2) a line between (x1, y1), (x2, y2) g.create_oval(x1, y1, x2, y2) the largest oval that fits in a box with top-left corner at (x1, y1) and bottom-left corner at (x2, y2) g.create_rectangle(x1, y1, x2, y2) the rectangle with top-left corner at (x1, y1), bottom-left at (x2, y2) g.create_text(x, y, text="text") the given text at (x, y) • The above commands can accept optional outline and fill colors. g.create_rectangle(10, 40, 22, 65, fill="red", outline="blue") • The coordinate system is y-inverted: (0, 0) (200, 100) Eng. & Educator Osama Ghandour
  • 67.
    James Tam Drawing withloops • We can draw many repetitions of the same item at different x/y positions with for loops. – The x or y assignment expression contains the loop counter, i, so that in each pass of the loop, when i changes, so does x or y. from drawingpanel import * window = drawingpanel(500, 400) g = window.get_graphics() for i in range(1, 11): x = 100 + 20 * i y = 5 + 20 * i g.create_oval(x, y, x + 50, y + 50, fill="red") window.mainloop() • Exercise: Draw the figure at right. Eng. & Educator Osama Ghandour
  • 68.
    Check your emailto Solve the Online auto answered quiz 15 min after school the quiz will be closed in 10:00pm after tomorrow Eng. & Educator Osama Ghandour Python
  • 69.
    Repetition (loops) inPython. Listen to this video Offline On line Eng. & Educator Osama Ghandour Python
  • 70.
    Selection (if/else) inPython Listen to this video Offline On line Eng. & Educator Osama Ghandour Python
  • 71.
    James Tam Summary 1-Variables –rules for naming . 2-Constants. 3- Run a program debug it . 4-documentation - comments. 5-Back up a progarm. Eng. & Educator Osama Ghandour Python
  • 72.
    James Tam Reflection • Whatis your goal to accomplish in next week End Using Python? Eng. & Educator Osama Ghandour Python
  • 73.
    James Tam Home work(s. proj.) 1 • Create a presentation contains some concepts of computer languages (Python) and display the Concepts of Repetition (loops) and Selection (if/else)following the bellow rubric . Eng. & Educator Osama Ghandour Python
  • 74.
    James Tam Home work2 (s. proj.) • Create a small program as a PBL in Collaboration work using integration to your Capstone project . Eng. & Educator Osama Ghandour Python
  • 75.
    James Tam Rubaric Blue Design apresentation showing Python to contain some concepts Repetition (loops) and Selection (if/else) Green Design a presentation showing Python to contain one or 2 Repetition (loops) and Selection (if/else). Yellow missing two points of green level. Read No presentation . Eng. & Educator Osama Ghandour Python
  • 76.
    James Tam Resources • https://www.youtube.com/user/osmgg2 Othermaterials: • https://www.sololearn.com • https://www.w3schools.com • www.python.org • “Learning Python,” 2nd edition, Mark Lutz and David Ascher (O'Reilly, Sebastopol, CA, 2004) (Thorough. Hard to get into as a quick read) Eng. & Educator Osama Ghandour Python
  • 77.
    James Tam Learn andpractice through on line web sites https://www.thewebevolved.com https://www.123test.com/ https://www.wscubetech.com/ https://www.w3schools.com/ https://www.guru99.com https://codescracker.com/exam/review.php https://www.arealme.com/left-right-brain/en/ https://www.proprofs.com/ https://www.geeksforgeeks.org/ https://www.tutorialspoint.com https://www.sololearn.com http://www.littlewebhut.com/ Eng. & Educator Osama Ghandour Python
  • 78.
    James Tam If youdo not feel happy, smile and pretend to be happy. •Smiling produces seratonin which is a neurotransmitter linked with feelings of happiness
  • 79.
    Thanks Eng. & EducatorOsama Ghandour Python
  • 80.