Fundamentals of Programming Class Notes - ITM 200
Document Details
Uploaded by ProdigiousOlive
Toronto Metropolitan University
2024
Tags
Related
- Ch-2 Python Introduction PDF
- Fundamentals of Programming - ITM200 Data Variables and Calculations PDF
- Introduction to Programming - ITM200 Lecture Notes PDF
- Meeting 2 - Fundamentals of Python Programming - s.en.ar.pptx PDF
- Introduction to Programming - STEM 1502 Lecture Notes PDF
- Python – Podstawy Programowania PDF
Summary
These are class notes for ITM 200, Fundamentals of Programming, Section 011/021 at Ryerson University. The notes cover topics like solving problems using computers, source code, compilation, and executable files. They also detail Python programming concepts and provide examples and exercises.
Full Transcript
ITM 200, Fundamentals of Programming Important Links/Side Info Class Info Professor: Sec. 011/021 Youcef Derbal Wednesdays...
ITM 200, Fundamentals of Programming Important Links/Side Info Class Info Professor: Sec. 011/021 Youcef Derbal Wednesdays Email: [email protected] 3-6 pm Webpage: http://www.ryerson.ca/~yderbal/ TRS1109 Syllabus detailed on D2L. Office Consultation: By appointment only. TA: name??? Office hours?? Email? Weekly Homework (10%) Due dates: Weeks 1-6 & Weeks 8-11 Anticipated return dates: Weeks 9 & 12 Midterm (40%) Final (50%) Week 7, Wednesday Oct 23, 2024 TBD Anticipated return date: Week 9 Extra Notes/Links: Quick start guide | PyCharm Documentation (jetbrains.com) - installation is only good thing The Python Tutorial - has actual terms and stuff MIDTERM QUESTION: HOW MANY THINGS CAN YOU REPRESENT WITH N BITS? 2^n 3 BITS? 2^3=8 8 THINGS CAN BE REPRESENTED WITH 8 BITS! 1 W1 Intro. To Programming Sep 3, 2024 Overview: Solving Problems Using Computers Source Code, Compilation & Executable Anatomy of a Simple Python Program Basic Python Programming by Examples Computers have the special property of being programmable to automatically execute different sets of instructions that specify what data to process & how to process it. These sets of instructions are called Computer Programs. ADITI Problem Solving Formula Analysis Design Understand the problem! Devise a solution - ALGORITHM. A step-by-step procedure for the computer to execute towards solving the problem. Implementation Testing Code the solution using a computer language Test & Debug Iterating Iterate through the previous steps as needed to achieve a solution that meets the requirements of the solution. Source Code, Compilers, Interpreters, Executable (file_name).py = source code file/computer programming language being used, py for Python. 2 Anatomy of a Python Program 1. hashtag (#) = comments 2. Print = displays whatever is provided as an argument Testing & Debugging Syntax Errors Semantic Errors Logic Errors Violation of Grammatical Rules Executes ✅ Does Not Solve ❌ Mistakes In Program Flow Ex. missing closing bracket in Ex. gives incorrect output. Ex. attempting to print the area the “print” instruction Fixing these errors can be more of a square before computing Easy to fix as Python/java difficult the actual area. shows it ○ Analyze & consider changes Lumped in with semantics. to the algorithm. 3 W1 In-Class Notes Sep 4, 2024 HOMEWORK RESTRICTIONS (Assigned Wednesday due next Tuesday taken up in class) - If you submit something with any syntax errors, it’s a ZERO PERCENT - I FORGOT WHAT HE SAID BUT ALSO ZERO MIDTERM - Bring laptop - Administered through D2L (probs lockdown) FINAL - Will be discussed later He went over the outline. Went over: - Percentage distribution - Topics for each week He went over slides Python is slower than C++ BUT Python is easier to use (has its own interpreter) - Dynamic vs static programming languages Program languages have changed greatly over the years - Started with simple stuff and binary codes - Slowly developed into higher level languages like Python and Java that are natural languages (ex. instructions are similar to sentences in English) - Programming languages have their own vocabulary (list of reserved words) and grammar (rules for forming valid instructions/expressions) - With natural languages, we take pride in the nuances we can express (ex., the same sentences can have different meanings based on tone). Computer languages don't get that. - If you were able to learn your mother tongue, extremely rich and complex as it is, then learning this (restricted grammar) computer language is nothing compared to learning a natural human language. He suggested that we use print statements instead of the more complex orders for now. SYNTAX ERROR - If you start with ‘ end with ‘ - If you start with “ end with “ - NEVER MIX EM, YA GET AN ERROR 4 CONV. STRING TO NUMBER print = print whatever is written input = USER inputs a specified value. Anything you put in Python will be automatically decided as a string, ex. s = string, word = string…, you gotta interpret it later Int, dec, (whole/real), double, float… s = input(“Enter temperature: “) t = float (s) print(t) if t0: t = float(input(“Enter temperature: “)) average = average + t n = n -1 average = average / m print(average) TEST: entered 3, 20, 20, 20 RESULT: 20.0 INCREMENT (COUNT) UP average = 0 s = input(“Enter the number of data points: “) n = int(s) 6 i=0 while i < n: t = float(input(“Enter temp [”+str(i)+‘]: ’)) average = average + t i=i+1 average = average / n print(“Average”, average) TEST: 40, 40, 40, 40 RESULT: 40 FOR LOOP av = 0 n = input(“Enter the number of data points: “) for i in range (n): av = av + float(input(“Enter temp Missed it 😡 WHILE TRUE 7 ^exited the entire program. 8 EXIT ONLY THE LOOP: 9 W2 Data Variables, Calculations Sep 10, 2024 Calculations Coding this formula using Python will entail the use of constructs equivalent to the three mathematical elements making up the formula: Variables Arithmetic Operators Assignment Operator Conversion of Celsius to Fahrenheit 10 Data Data Types int – used for variables that hold natural numbers 0,1,2,3,... and their negative counterparts -1,-2,-3... Float –real numbers (DECIMALS) such as -23.5, -9, 0, 0.5, 1, 2.34,6,.. str – alphanumeric character strings such as “ITM200”, “123ER” Data Variables In Python, a variable name may be any arbitrary alphanumeric string of literals that does not start with a numeral. Variable names are case-sensitive & may not be any of Python’s listed keywords. → Dynamically Typed Strongly Typed Variables can be bound (by assignment) to Operations that are incompatible with the type of different types at execution time. the operands (variables) are not allowed and will result in run-time errors. Arithmetic Operators Arithmetic operators used in Python work in the usual way. The evaluation of an arithmetic expression is done from left to right in the following order (rules of precedence): 1. Evaluate whatever is enclosed between brackets “( )” 2. Evaluate ** 3. Evaluate *, /, %,// 4. Evaluate +, - 11 Characters in Python No character data type = a character is a string of a single character ord() and chr() functions = get the ASCII/Unicode value of a character and vice versa. Formatting Outputs str(n) converts n to a str type to allow concatenation to another string using the +, interpreted in this case as a string concatenation operator round(x,n) rounds x to n digits after the decimal point 12 print(round) float inaccuracy Types & Operations Q. What can we do with the integer that we can’t do with the float? Think of counting and arrays. We can’t have a real number as an index of an array. An index cannot be a float; has to be an integer. So, the float (decimal) m value with 3.0 won’t work in an array. WHAT WAS THE OTHER ONE????? ASK AFTER CLASS 13 Strings String Manipulation 14 User Input Processing User Input 15 Calculations Using Input Data Variable Conversion int – integers float – real numbers str – a string of characters bool – A boolean variable that can only take the values True or False The following Python built-in functions can be used, when possible, to do type conversion: int() float() str() bool() 16 Run-Time Errors String To An Int String to Float You’ll get a run-time error when passing a string to an The “conversion” of a string of numerals to a float will int if the string does not look like an int. succeed only if the string can be interpreted as a float. The example below will result in a run-time error. Ex. s = “7A” j = int(s) = run-time error. Ex. Although “7.5” looks like a number (float), it’s not s = “7A” an int. j = float(s) If the string can be interpreted as an int no error will result because int values do fit in float variables. Ex: 7 is an int and can also be taken as a float. Type Conversion 17 Exercise 1 Exercise 2 18 Exercise 3 Make it pretty (remove spaces in between): 19 20 Exercise 4 If the s is simply x floor division by 10, we get our flag. Exercise 5 - DIFFERENT VERS. Python ignores trailing spaces. Java doesn’t do this. 21 HMWRK-BASED Exercise 6 - DIFFERENT VERS. LOCATION OF THE “x”: SLICE IT TO FIND BEFORE X: LOOK AT RESULT: 22 DON’T KEEP “x” IN CALCULATION, CONVERT TO FLOAT, SOLVE: Can save as a copy and change sentence to have ‘+’ which changes n=op.find(‘x’) 23 W2 HMWRK 24 Instructions Write a Python program, call it scicalc.py, to evaluate an arithmetic expression provided as input in one of the following forms: + (12, 2.5) -(7, 0.5) *(5,4.9) / (67, 16.5) % (27,8) (i.e. 12.5 plus 2.5) (i.e. 7 minus 0.5) : (i.e. 5 times 4.9) : (i.e. 67 divided by 16.5) : (remainder of the division of 27 by 8) The program must work correctly for any arbitrary real numbers used in the arithmetic expression irrespective of the number of spaces separating the different elements of the input expression. For example, the expression + ( 12.5, 2.5) should still yield 15. Note the following: 1. Submitted programs must be void of any syntax errors. 2. The format of the input string must be as specified above. 3. The solution must not use any constructs that we have not studied, including if statements, while statements, dictionaries, functions, and library/module imports. 4. The submission must be the source code file scicalc.py. Do not zip the file. Any other forms of submission will be marked as zero. Submissions that are non-compliant with any of the above requirements will be automatically marked as zero. The expected input/output behaviour of the program is illustrated below for a few example inputs: Enter arithmetic expression: +(8,3) +(8,3) = 11.0 Enter arithmetic expression: - ( 11, 4) - (11, 4) = 7.0 Enter arithmetic expression: *(11, 3) *(11, 3) = 33.0 Enter arithmetic expression: / (10, 2.5) / (10, 2.5) = 4.0 25 SHORTER: Write a Python program to evaluate an arithmetic expression provided as input in one of the following forms: + (12, 2.5) : (i.e. 12.5 plus 2.5) -(7, 0.5) : (i.e. 7 minus 0.5) *(5,4.9) : (i.e. 5 times 4.9) / (67, 16.5) : (i.e. 67 divided by 16.5) % (27,8) : (remainder of the division of 27 by 8) The program must work correctly for any arbitrary real numbers used in the arithmetic expression irrespective of the number of spaces separating the different elements of the input expression. For example, the expression + ( 12.5, 2.5) should still yield 15. Note the following: Submitted programs must be void of any syntax errors. The format of the input string must be as specified above. The solution must not use any constructs that we have not studied; i.e. NO if statements, while statements, dictionaries, functions, or library/module imports. 26 W2 UPDATED INSTRUCTIONS HMWRK 27 W3 Decision Sep 18, 2024 Agenda Homework Solution Write & Evaluate Boolean Expressions Use If – else and if-elif-else Statements to implement decisions Boolean (Bool) Data Type Used to represent two-value logic variables. 28 Boolean Expressions The RHS of the shaded expression is not a statement that asserts scoreA to be greater than scoreB! It is rather a “Question” whose evaluation can either be True or False and hence is said to be a Boolean expression. Boolean Expression Ex. Assuming that awards are given to second-year students with GPAs greater than 3.5, the following example determines whether or not a particular student should be given an award. Expressions that evaluate to True or False are formed using relational and logical operators. These operators are also used to compare strings. For strings, the comparisons are based on the lexicographical order. Ex: the evaluation of the expression “ABC” < “ADC” would yield True. Relational Operators Logical Operators < less than and greater than not >= greater than or equal to == equal to != not equal to 29 Rules of Operator Precedence 1. () 2. Exponentiation 3. * / % // 4. +- 5. < >= == != 6. not 7. and 8. or Simple Decision Course Pass/Fail Example Ex. Given a course mark provided as input, determine the student’s Pass/Fail status for the course. Statement blocks are indented four spaces to the right of the if and else keywords. Statement blocks may have an arbitrary number of instructions. If we are interested in finding the letter grade instead of the “Pass/Fail” status, we need to include more decision elements/questions to determine where the course mark falls in the value ranges of the grade letters A, B, C, and D. A: mark >= 80 B: 70