Full Transcript

Lecture 2.1 Variables, Statements, and Comments Topic 2 Intended Learning Outcomes ◎ By the end of week 2 you should be able to: ○ Write simple statements and expressions, ○ Use sensible variable names and comments to improve the readability of code, and ○ Understand the difference between integ...

Lecture 2.1 Variables, Statements, and Comments Topic 2 Intended Learning Outcomes ◎ By the end of week 2 you should be able to: ○ Write simple statements and expressions, ○ Use sensible variable names and comments to improve the readability of code, and ○ Understand the difference between integers, floats, and strings. 2 Labs Start This Week ◎ Please attend the lab that you have enrolled in. ◎ Bring your laptop if you have one. ○ You will be setting up programming software. 3 Lecture Overview 1. Literals and Variables 2. Statements 3. Naming Conventions and Comments 4 Users vs. Programmers o Users see computers as a set of tools - word processor, email, excel, note, website, messenger, etc. o Programmers learn computer languages to write a Program. o Programmers use some tools (Python) that allow them to build new tools (Program or Software). o Programmers often build tools for lots of users and/or for themselves. What is a program? 5 6 7 Writing a program ◎ A program can be used to solve complex problem ○ ○ Programs are a set of written actions in order to fulfil a need / solve a problem A programming language is the tool used to create a solution (Program) Design a flowchart Implement: Python print data Problem Task Definition if condition true print data Solution for x in range print x Call function ... By writing a program using Python, you can make a computer do something useful 8 Computer Program A program is a sequence of instructions that specifies how to perform a computation. • Input: Get data from the keyboard, a file, the network, or some other devices. • Process: • Math: Perform basic mathematical operations like addition (+) and multiplication (*). • Conditional execution: Check for certain conditions and run the appropriate code. • Repetition: Perform some action repeatedly, usually with some variation. • Output: Display data on the screen, save it in a file, send it over the network, etc. Computer programs 10 Computer programs 11 1. Literals and Variables 12 Values A value (Literal) is one of the basic things a program works with, like a number or a letter. 13 Literals ◎ Literals are values that Python interprets literally (as written). ◎ Represent numbers, text, and other values that are: ○ Required by the program, and ○ Known ahead of time. ◎ For example, a calendar program might contain string literals such as 'Wednesday' and 'August'. 14 Numeric and String Literals ◎ Numeric literals are written as you'd expect. ○ e.g. 42 means the number 42. ◎ String literals (snippets of text) are written between matched quotation marks. ○ e.g. 'text' or "text". >>> 42 42 >>> 27.5 27.5 >>> 'Hello there!' 'Hello there!' >>> "Double quotes work too." 'Double quotes work too.' 15 Check Your Understanding Q. Which lines in the shown program contain numeric/string literals? 1 2 3 4 5 x = 5.1 y = x + 2 z = x + y print('Result:') print(z) 16 Check Your Understanding Q. Which lines in the shown program contain numeric/string literals? A. Lines 1, 2, and 4. ◎ Line 1: 5.1 (numeric). ◎ Line 2: 2 (numeric). ◎ Line 4: 'Result:' (string). 1 2 3 4 5 x = 5.1 y = x + 2 z = x + y print('Result:') print(z) 17 Variables ◎ A variable allows you to give a name to a value. ◎ You can think of a variable like a labelled box. ◎ A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variables “name” ◎ Variable names are decided by the programmer. ◎ The contents of a variable can change. 18 Creating Variables ◎ A variable can be defined (created) via assignment. ◎ Assignment links a variable name with a value. >>> day = 'Wednesday' >>> day 'Wednesday' >>> age = 28 >>> age 28 ◎ Assignment in Python is performed using the equals symbol, e.g. x = 5. 19 Single Equals (=) Mathematics ◎ '=' indicates equality. ◎ An expression of state (how things are). ◎ x = 5 means "x is equal to 5". Python ◎ '=' indicates assignment. ◎ An instruction. ◎ x = 5 means "assign 5 to x" (i.e. "store 5 in x"). x = 5 20 Updating Variables ◎ Assignment can also be used to update the value of an existing variable. ◎ In the example shown, x originally has a value of 5 but is later updated to contain 10 instead. >>> x = 5 >>> x 5 >>> y = 'Hello' >>> y 'Hello' >>> x = 10 >>> x 10 21 Updating Variables Variable Value x = 5 y = 'Hello' x = 10 22 Updating Variables Variable Value x 5 x = 5 y = 'Hello' x = 10 23 Updating Variables Variable Value x 5 y 'Hello' x = 5 y = 'Hello' x = 10 24 Updating Variables Variable Value x 5 10 y 'Hello' x = 5 y = 'Hello' x = 10 25 Variable Naming Rules ◎ Variable names: ○ Must only contain letters, digits, and underscores. ○ Must not begin with a digit. ◎ Lowercase/uppercase matters. ○ myVariable, MyVariable, and MYVARIABLE are all different in Python. 26 Variable Naming Rules Allowed ✓ ✓ ✓ ✓ ✓ x name2 street_address MyAge _rocket Not allowed ✗ ✗ ✗ ✗ ✗ 2d_map best-score school/work $Cost my variable 27 Reserved Words ◎ There are reserved words which have special meanings in the Python language. ◎ Reserved words can't be used as variable names. and as assert break class continu e def del elif else except finally False for from global if import in is lambda nonloca l None not or pass raise return True try with while yield 28 Selecting Variable Names ◎ Variable names are for programmers, not computers. ○ Regardless of whether you name a variable x, age, or zz23v, Python will interpret your program in the same way. ○ However, good variable names can help make code more understandable to humans. 29 Selecting Variable Names s2sfg = 5 s2sgf = 10 s2sff = s2sfg * s2sgf print(s2sff) width = 5 height = 10 area = width * height print(area) ◎ The two programs above are equivalent to Python. ◎ But the one on the right is much easier to understand as a human! 30 Check Your Understanding Q. Which of the following are valid variable names? ◎ ◎ ◎ ◎ ◎ paper,scissors,rock _friend 2_friends KEKWait if 31 Check Your Understanding Q. Which of the following are valid variable names? ◎ ◎ ◎ ◎ ◎ paper,scissors,rock _friend 2_friends KEKWait if A. _friend and KEKWait. ◎ Variable names can't contain commas. ◎ Variable names can't begin with a digit. ◎ if is a reserved word. 32 Ask the Audience ◎ What name might you give a variable which represents the cost of a product? 33 2. Statements 34 What is a Statement? ◎ A statement is a complete "step". ◎ A program consists of multiple statements. ◎ When you run a Python program, the statements within are executed in a well-defined order. ◎ Often a statement takes the form of a line of code. 35 What is a Statement? ◎ We have already seen a few different kinds of statements, for example: ○ width = 5 is an assignment statement. ○ print(area) is a print statement. 36 Expression Statements ◎ Common uses: ○ Interacting with the Python interpreter. ○ Calling functions. 23 y - 5 max(100, 200) ◎ More about expressions and functions in future lectures. 37 Print Statements ◎ Technically a kind of expression statement. print('Hello my friend!') print(x * 2) ◎ Used to display output text to the user. 38 Assignment Statements ◎ Common uses: ○ Defining a variable. ○ Updating the contents of a variable. minimum_age = 18 area = 2 * pi * radius ◎ Assignment statements involve an equals sign. ○ Remember, this is different to = in mathematics! 39 Input Statements. ◎ Technically a kind of assignment statement. ◎ Used to accept input from the user. ◎ Waits for the user to type input and hit "Enter". ◎ Input is stored in a variable. ◎ Optionally specify a prompt to show the user. name = input() c = input('Enter a colour: ') 40 Python Interactive Sessions vs. Scripts Interactive interpreter session ◎ Start an interactive session with the python command. ◎ Write and execute a single statement at a time. ◎ If a statement produces a result, the result will be shown. Python script ◎ Write multiple statements in a ".py" text file. ◎ Execute all of the statements together, for example: ○ python my_script.py ◎ If a statement produces a result, the result will not be shown. ○ Use print statements to display results. 41 Example: Interactive Session >>> x = 5 >>> x + 2 7 >>> name = input('Enter your name: ') Enter your name: Billy >>> print('Hello ' + name) Hello Billy ◎ Writing and running code is interleaved. ◎ Expression statements display results. 42 Example: Script x = 5 x + 2 name = input('Enter your name: ') ◎ First write all the code, then run all of the code. print('Hello ' + name) $ python my_script.py ◎ Expression statements so not display results unless printed. Enter your name: Billy Hello Billy 43 Check Your Understanding Q. What output(s) will be displayed after executing these statements in a Python script? age = 36 print(age) age + 1 print('Done') 44 Check Your Understanding Q. What output(s) will be displayed after executing these statements in a Python script? A. 36 and Done. ◎ Only the print statements produce output messages. ◎ Even though line 3 contains a statement which produces a result, it is not shown. age = 36 print(age) age + 1 print('Done') 45 3. Naming Conventions and Comments 46 Meaningful Variable Names ◎ It is good practice to give variables meaningful names. ◎ Meaningful names are for the benefit of human programmers only. ○ Naming a variable "interest_rate" won't magically give Python the ability to calculate interest. ◎ Spending a few moments to select good variable names can greatly increase code readability. ○ This saves time in the long run! 47 Example: Meaningful Variable Names variable1 = 10 variable2 = 5 variable3 = 20 variable4 = variable1 * variable2 if variable4 > variable3: print('Danger!') acceleration = 10 acceleration_time = 5 maximum_safe_speed = 20 speed = acceleration * acceleration_time if speed > maximum_safe_speed: print('Danger!') ◎ The names of the variables in the second program are meaningful to humans. ◎ When the meaning of a program is unclear, as in the first program, the programmer is more likely to make mistakes. 48 Common Python Naming Conventions ◎ Multiple words in a variable name are separated with_underscores. ◎ Ordinary variables are named in lowercase, with underscores separating words. ○ e.g. current_score = 0 ◎ Constants (variables with values that are never updated) are named in UPPERCASE. ○ e.g. EARTH_GRAVITY = 9.81 49 Other Naming Conventions ◎ Where appropriate, you may want to adopt your own naming conventions. ○ Indicate units: ◉ time → time_secs ○ Indicate that a count is being stored: ◉ participants → num_participants ○ Indicate subtle differences: ◉ password1, password2 → old_password, new_password 50 Comments ◎ Comments are sections of code ignored by Python. ◎ Can be used to annotate code in plain English (good variable names aren't always enough) ◎ In Python, a comment starts with a hash (#) and continues to the end of the line. # This is a comment on its own line. x = 5 # This comment shares a line with actual code. # You can't place a comment before code # y = 7 51 Common Uses for Comments ◎ Explain to other programmers (or your future self) how a complex section of code works. ◎ Leave notes about future work to do. ◎ Add a copyright notice or indicate authorship. ◎ Temporarily disable a section of code ("commenting out" code). 52 Comments in the Wild: Description Don't be afraid of writing comments which are longer than the associated code if you deem it appropriate! 53 Comments in the Wild: Future Work Future work comments often start with "TODO:" (as in "this is future work to do"). 54 Comments in the Wild: License Information 55 "Commenting Out" Code ◎ Since comments are effectively ignored by Python, they can be used to disable lines of code. ○ Simply add a "#" to the start of the line. ◎ The program below outputs 5 (not 6) since line 2 is "commented out". x = 5 # x = x + 1 print(x) 56 Check Your Understanding Q. What result will be displayed by the program? x = 2 five = x + 2 y = five + 4 # y = y + 1 print(y) 57 Check Your Understanding Q. What result will be displayed by the program? A. 8. ◎ Naming a variable "five" does not affect its value. ◎ The commented line is not executed (line 4 is ignored). x = 2 five = x + 2 y = five + 4 # y = y + 1 print(y) 58 Summary 59 In This Lecture We... ◎ Discovered what literals and variables are. ◎ Explored some basic statements in Python. ◎ Learnt how to make code more understandable using comments and well-named variables. 60 Next Lecture We Will... ◎ Delve deeper into programming fundamentals by learning about expressions and types. 61 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 62 Lecture 2.2 Expressions and Types Lecture Overview 1. Expressions 2. Types 3. Example Program: Temperature Converter 2 1. Expressions 3 What Are Expressions? ◎ An expression is a small piece of code that resolves to a value. ◎ Some extremely simple examples are: ○ 42 (a literal resolves to itself). ○ my_var (a variable resolves to its value). 4 What Are Expressions? ◎ The highlighted parts of the code shown on the right are expressions. ◎ Note that only the right hand side of assignment is an expression. ○ The left hand side must be an identifier (e.g. a variable name). >>> 33.33 33.33 >>> artist = 'Avenade' >>> albums = 1 >>> albums 1 >>> new_albums = albums + 1 >>> new_albums 2 5 What Are Expressions? ◎ Expressions can use operators to compute a result. ◎ A combination of numeric values, operators, and sometimes parenthesis (). ○ 3.5 - 0.75 (resolves to 2.75). ○ x + y (resolves to the sum of x and y). ○ r + 1 (resolves to the value of r plus one). 6 Operators Numeric Operators OPERATOR NAME + Addition - Subtraction * Multiplication / Division ** Exponentiation % Modulo // Integer division ◎ An asterisk (*) denotes multiplication. ○ 2 * 3 (gives 6) ◎ A forward slash (/) denotes division. ○ 5 / 2 (gives 2.5) ◎ // Integer division ○ 5 / 2 (gives 2) ◎ A double asterisk (**) denotes "to the power of". ○ 2 ** 3 (gives 8) 7 Integer Division and Modulo ◎ Recall performing division by hand in school. ○ We would get two results: the quotient, and the remainder. ◎ For example, when evaluating 7 ÷ 2, we might say: "2 goes into 7 three times, with a remainder of one". ○ The quotient is 3. ○ The remainder is 1. 8 Integer Division and Modulo ◎ In Python: ○ Integer division (//) calculates the quotient. ○ Modulo (%) calculates the remainder. ◎ Examples: ○ 7 // 2 (gives 3) ○ 7 % 2 (gives 1) ◎ Can also think of integer division as regular division with the result rounded down. 9 Combining Expressions ◎ Multiple expressions can be combined: ○ e.g. 3 + 2 * 6 – 1 ◎ But how does Python decide which operator goes first? ○ In the above example, how does Python choose whether to do 3 + 2, 2 * 6, or 6 - 1 first? 10 Operator Precedence ◎ Each of the operators in Python has a certain precedence ("priority"). ◎ This is similar to mathematics. ○ Remember learning PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction) in school? ◎ Operators with higher precedence are evaluated first. ◎ Operators with the same precedence are evaluated leftto-right. 11 Operator Precedence OPERATOR () NAME Higher Parentheses ** Exponentiation *, /, %, // Multiplication, etc. +, - Lower Addition, etc. ◎ Similar order to mathematics (PEMDAS). ◎ Since parentheses have highest precedence, you can always explicitly group things. 12 Check Your Understanding Q. What does the expression 2 + 5 * 7 // (1 + 1) evaluate to? OPERATOR NAME () Parentheses ** Exponentiation *, /, %, // Multiplication, etc. +, - Addition, etc. 13 Check Your Understanding Q. What does the expression 2 + 5 * 7 // (1 + 1) evaluate to? A. 19. 1. 2 + 5 * 7 // (1 + 1) 2. 2 + 5 * 7 // 2 3. 2 + 35 // 2 4. 2 + 17 5. 19 OPERATOR NAME () Parentheses ** Exponentiation *, /, %, // Multiplication, etc. +, - Addition, etc. 14 2. Types 15 Primitive Types In Python, we can assign different values of different variables, and different types can do different things. The assigned values are known as Data Types. TYPE NAME DESCRIPTION EXAMPLE str String A string of characters (text). 'Hello' int Integer A whole number. -43 float Float A number with a decimal point. 23.6 bool Boolean A boolean (true/false) value. True Today we will discuss integers, floats, and strings. We will cover booleans in the next lecture. 16 Different Types of Numbers ◎ Integers (type int) represent whole numbers. ◎ Often used to represent counts of things: ○ Inventory levels ○ Age (in years) ○ Attendance ◎ -43, 0, and 10000 are all integers. ◎ Floating point numbers, or "floats", (type float) have a decimal point and fractional part. ◎ Often used to represent precise measurements: ○ Temperature ○ Percentages ○ Prices. ◎ 22.5, 0.0, and -0.9999 are all floats. 17 Strings ◎ String (type str) literals (snippets of text) are written between matched quotation marks. ○ e.g. 'text' or "text". >>> x = “1” >>> type(x) <class ‘str'> >>> type(‘hi’) <class ‘str’> >>> x=20 >>> print (str(x)) >>>’20’ 18 String Concatenation ◎ String concatenation means joining two pieces of text ("strings") together. ○ 'bed' + 'room' (gives 'bedroom’) ◎ Can be used to build a message to show the user. >>> name = 'Jeremiah' >>> print('Hello ' + name) Hello Jeremiah 19 String Concatenation Beware! You can't combine a string and a number using the "+" operator. We'll discuss how to avoid this error in the next part of the lecture as we learn about types. >>> 'My age is: ' + 28 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str 20 Determining Types ◎ Python can tell us the type of a value. ◎ Simply use the type() function. ◎ Especially useful in interactive sessions. >>> x = 1 >>> type(x) <class 'int'> >>> type(3.4) <class 'float'> >>> type(x + 3.4) <class 'float’> >>> type(“Hi CSE4P”) <class ‘str’> 21 Different Types Behave Differently ◎ There is a difference between 20, 20.0, and '20': ○ 20 is an integer. ○ 20.0 is a float. ○ '20' is a string. ◎ Python sees these values differently. ◎ Values of different types behave differently. ○ Python chooses what operators do based on types. 22 Check Your Understanding Q. What does the expression '1' + '2' evaluate to? 23 Check Your Understanding Q. What does the expression '1' + '2' evaluate to? A. The string '12'. Since both '1' and '2' are strings---not floats or integers--Python treats them as text and not numbers. So, when Python sees the + operator, it performs string concatenation instead of numerical addition. This is the same behaviour as our earlier example of 'bed' + 'room'. 24 Automatic Type Conversion ◎ Type conversion is the process of deriving a value of a different type from an existing value. ◎ Sometimes Python will automatically convert types. ◎ For example, when an integer and a float are added, the integer is automatically converted into a float. >>> x = 1 >>> x + 3.4 4.4 # Python converts the 1 to 1.0 25 Explicit Type Conversion ◎ Python doesn't always know how types should be converted, so there are times when you need to convert types explicitly. ◎ This can be achieved using the int(), float(), str(), and bool() functions. 26 Converting Numbers to Strings ◎ Converting numbers to strings can be useful for building output messages. ◎ Converting a float to a string will always include the decimal part, even if it is zero. >>> age = 28 >>> 'My age is: ' + str(age) 'My age is: 28' >>> str(420.0) '420.0' 27 Converting Strings to Numbers ◎ Converting strings to numbers can be useful for accepting input. ◎ If the string does not represent a number, Python will raise an error. >>> age = input('Enter your age: ') Enter your age: 28 >>> int(age) + 7 35 >>> float('apple') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: could not convert string to float: 'apple' 28 Check Your Understanding Q. What value does the following expression evaluate to? str(9 + 1.0) + '0' 29 Check Your Understanding Q. What value does the following expression evaluate to? str(9 + 1.0) + '0' A. The string '10.00'. 1. Python implicitly converts the 9 to 9.0, and adds 1.0 to get 10.0. 2. The str() function converts the float 10.0 to the string '10.0’. 3. Finally, the string '10.0' is concatenated with '0' to get '10.00'. 30 3. Example Program: Temperature Converter 31 Task Definition Create a program which converts a temperature value from degrees Celsius (C) to degrees Fahrenheit (F) using the following conversion formula, where C is the temperature in degrees Celsius and F is the temperature in degrees Fahrenheit: 32 Identifying Inputs and Outputs ◎ Input: C, the temperature in degrees Celsius. ◎ Output: F, the temperature in degrees Fahrenheit. ◎ Examples: ○ 0 °C → 32 °F ○ 100 °C → 212 °F ○ 22.5 °C → 68.9 °F 33 Identifying Processing Steps Example ◎ Input: 100 → C=100 ◎ Processing: 1. 100 × 9 = 900 2. 900 ÷ 5 = 180 3. 180 + 32 = 212 ◎ Output: 212 34 Drawing a Flowchart Start Input number Multiply by 9 Divide by 5 Add 32 Output number Stop Example ◎ Input: 100 ◎ Processing: 1. 100 × 9 = 900 2. 900 ÷ 5 = 180 3. 180 + 32 = 212 ◎ Output: 212 35 Translating to Python Code Start Input number Multiply by 9 Divide by 5 tc = input('Enter Celsius: ') x = float(tc) ◎ The input is initially read in as a string (type str). ◎ We convert it into a number (type float). Add 32 Output number Stop 36 Translating to Python Code Start Input number Multiply by 9 x = x * 9 ◎ The asterisk (*) "multiply" in Python. means Divide by 5 Add 32 Output number Stop 37 Translating to Python Code Start Input number Multiply by 9 x = x / 5 ◎ The forward slash (/) means "divide" in Python. Divide by 5 Add 32 Output number Stop 38 Translating to Python Code Start x = x + 32 Input number Multiply by 9 Divide by 5 Add 32 Output number Stop 39 Translating to Python Code Start Input number Multiply by 9 Divide by 5 tf = str(x) print('Fahrenheit: ' + tf) ◎ We convert our number (type float) into a string (type str) so that we can build our output message. Add 32 Output number Stop 40 The Final Program Start Input number Multiply by 9 Divide by 5 # Input tc = input('Enter Celsius: ') x = float(tc) # Processing x = x * 9 # Multiply by 9 x = x / 5 # Divide by 5 x = x + 32 # Add 32 # Output tf = str(x) print('Fahrenheit: ' + tf) Add 32 Output number Stop 41 Check Your Understanding Q. After reading user input, we converted the value into a float: x = float(tc) Why didn't we convert to an integer instead? x = int(tc) 42 Check Your Understanding Q. After reading user input, we converted the value into a float: x = float(tc) Why didn't we convert to an integer instead? A. Type int only supports whole numbers. Therefore using int() would not allow the user to input fractional temperatures, like 20.5. x = int(tc) 43 Live Coding Demo ◎ Let's say that you have to calculate a bunch of hypotenuse lengths (a totally normal thing that normal people have to do). ◎ You could use a calculator like a peasant, or you could write a program like a non-genderspecific member of the royal family! 😅 c a b 44 Live Coding Demo # a b c File: hypotenuse.py = float(input('Enter a: ')) = float(input('Enter b: ')) = (a ** 2 + b ** 2) ** 0.5 print('Hypotenuse: ' + str(c)) $ python hypotenuse.py Enter a: 3 Enter b: 4 Hypotenuse: 5.0 c a b 45 Summary 46 In This Lecture We... ◎ Explored simple expressions in Python and how they can be crafted using operators. ◎ Learnt about different basic data types in Python. ◎ Worked through the steps of solving a real problem with Python code. 47 Next Lecture We Will... ◎ Learn about the boolean type, comparison operators, and logical expressions. 48 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 49 Lecture 1 .1 Introduction to Programming Acknowledgement of Country La Trobe University acknowledges that this lecture and our participants are located on the lands of many Traditional Custodians in Australia. We recognise their ongoing connection to the land and value their unique contribution to the University and wider Australian society. We pay our respects to Indigenous Elders, past present and emerging and extend this respect to any Indigenous participants joining this subject. Artist: Kane Nelson 2 Hello! I am Nasser Sabar I am your CSE4IP-CSE5CES lecturer for the semester. I will be delivering subject content in presentations like this one. 3 What to expect In this subject the other teaching staff and I will guide you on your journey to learn computer programming. Programming is not something that can be learned well half-heartedly. However, if you put some effort in you will find that it can be very fun and rewarding! 4 Subject Structure The majority of your learning will take place in lectures and labs Lectures will be delivered F2F, on campus Labs will be completed on campus Please ask lots of questions along the way Lectures: 2 hours per week Labs: 2 hours per week (starting week 2) 5 Subject Learning Guide 6 Subject timetable CSE4IP - CSE5CES Sem 1 Timetable Activity Day Start End Duration Campus Room Lecture Thursday 10:00 AM 12:00 PM 2 hours BU - F2F AT-02-1.12 | Agora Cinema Computer Lab Thursday Computer Lab Thursday Computer Lab Friday Computer Lab Friday Computer Lab Friday Computer Lab Friday Computer Lab Friday 1:00 PM 3:00 PM 9:00 AM 11:00 AM 1:00 PM 3:00 PM 5:00 PM 3:00 PM 5:00 PM 11:00 AM 1:00 PM 3:00 PM 5:00 PM 7:00 PM 2 hours 2 hours 2 hours 2 hours 2 hours 2 hours 2 hours BU - F2F BU - F2F BU - F2F BU - F2F BU - F2F BU - F2F BU - F2F BG-01-105 BG-01-105 BG-01-105 BG-01-105 BG-01-106 BG-01-105 BG-01-105 Please note that, subject to Echo availability, all lectures will be recorded and uploaded in LMS. Labs will not be recorded. NO live lab 7 LMS (Learning Management System) ◎ All subject material is available on LMS: https://lms.latrobe.edu.au/ ◎ There are many resources provided for you, including: ○ Notes for all lecture topics ("workbooks"), ○ The subject schedule, ○ References for further reading ○ Lab session materials, and ○ Discussion forums 8 LMS (Learning Management System) 9 LMS (Learning Management System) 10 Weekly tiles 11 Assessments ◎ Labs are not assessed, but are an important part of the subject material and must be completed. ◎ Your understanding will be assessed via: ○ 2× Programming Assignments (25% each) ○ 1× 2-hour Final Exam (50%)---not a hurdle ◎ Assessments must be submitted via LMS. ○ Refer to the LMS for assessment dates. 12 Assessments ◎ Submission of all three assessments is vital for success in CSE4IP. ○ 78.75% of students that failed in Semester 1 or 2 20212022 did not submit all three assessments. ◎ Don't leave the assignments until the last minute! ○ Start early so you can ask questions. 13 Academic Integrity (Cheating) ◎ All assessments must be completed individually. ◎ This means that you are not allowed to: ○ Copy/share code and make superficial changes so it "looks different". ○ Obtain partial or complete answers from friends, relatives, strangers, contractors, online, etc. ○ Use generative AI such as ChatGPT ◎ If you are unsure whether something is considered cheating, ask me. 14 Academic Integrity (Cheating) ◎ Reasons to avoid cheating include: ○ ○ ○ ○ Future learning difficulties, Reputational harm, Severe penalties (including expulsion), and Blackmail. ◎ Cheating is more trouble than it's worth, don't do it! 15 Recommended Texts Python for Everybody: Exploring Data Using Python 3 Charles Severance, 2016 Free digital copy and accompanying video lessons: https://www.py4e.com/ 16 Recommended Texts Python Programming: An Introduction to Computer Science (3rd edition) John Zelle, 2016 17 Additional Learning Support ◎ La Trobe Coding Hub on LMS. ○ https://www.latrobe.edu.au/students/studyresources/learninghub/coding-hub ◎ Provides access to tutors that are highly knowledgeable about programming: ○ Online forums, and ○ Live help sessions ◎ I highly recommend that you check out this resource. 18 Subject Intended Learning Outcomes (SILOs) ◎ After completing this subject you should be able to: ○ Analyse a data processing problem, ○ Design a solution, and ○ Implement that solution as a working computer program written in the Python programming language. ◎ The full list of SILOs is provided as part of the subject learning guide (available on LMS). 19 Is CSE4IP a tough or easy subject? o Yes, it can be extremely difficult, particularly the final exam, if you ○ do NOT go through the teaching materials (Workbook, Slides …etc). ○ do NOT practice and solve lab questions. ○ do NOT do the assignment tasks by yourself! 20 Topics We Will Cover ◎ Week 1 -Topic 1: Algorithms and Flowcharts ◎ Week 2 - Topic 2: Statements and Expressions ◎ Week 3 - Topic 3: Booleans and Conditional Execution ◎ Week 4 - Topic 4: Iteration ◎ Week 5 - Topic 5: Functions and Objects ◎ Week 6 - Topic 6: Strings and Files Week 7 - Topic 7: Data Structures Week 8 - Topic 8: Software Errors Week 9 - Topic 9: Using Modules Week 10 - Topic 10: Structuring and Documenting Code ◎ Week 11 - Topic 11: Algorithm Design Strategies ◎ Week 12 - Topic 12: Revision ◎ ◎ ◎ ◎ 21 Topic 1 Intended Learning Outcomes ◎ By the end of week 1 you should be able to: ○ Understand the purpose of algorithms and programming languages, ○ Use the Python interpreter to start an interactive session or run Python scripts, and ○ Create flowcharts to describe simple algorithms. 22 Lecture Overview 1. Why Learn Programming? 2. Computational Thinking 3. Python 23 1. Why Learn Programming? 24 The Digital World ◎ People are spending increasing amounts of time in digital environments. ◎ These digital environments are defined by software: ○ “Apps” (applications), “websites”, “user interfaces”, “databases”, “artificial intelligence”, etc. ◎ The software that we interact with shapes our lives. ○ Social media is a prime example. 25 Learning how software works empowers you, and opens up new opportunities in an everexpanding digital world. 26 Computers are Everywhere ◎ To appreciate how much software you interact with, think of all of the devices you use: ○ Laptops, phones, TVs, self-service checkouts, etc. ◎ Sometimes software is mostly unseen: ○ EFTPOS, washing machines, cars, etc. ◎ Programming is the practice of creating software. ○ You are learning how to control the most important machines on the planet! 27 Programming Saves You Time ◎ Have you ever found yourself in a situation where you are performing repetitive tasks on a computer? ○ ○ ○ ○ Renaming a bunch of songs one-by-one? Cropping a whole album of photos? Downloading many files individually? Sifting through documents to pull out information? 28 Programming Saves You Time ◎ You can write your own computer programs to perform time-consuming tasks. ◎ It’s like being able to create your own little digital robot assistant. ○ This only becomes more useful as the digital world expands. 29 Anecdote: Car Audio ◎ I have a large digital music collection. ◎ I also have a fairly old car, so I installed a stereo which can play music from USB. ◎ When I tried to use it, I ran into a few issues: ○ The track order within albums was wrong. ○ The volume across songs was inconsistent. ○ Some songs just wouldn’t play at all. 30 But… but… ... ... ... ...I just wanted to jam in my car... 😢 31 Doing Things Manually == Sadness ◎ I could have manually gone through track-by-track, using audio editing software to convert every song into MP3 format and adjust the volume and fix up metadata and so on... ◎ Sure, this would work, but it would take me hours. ◎ Furthermore, whenever I wanted to add fresh music I’d have to do it all again! 32 Automation for a Happier Existence ◎ Instead, I used my programming knowledge to write a small amount of code (software). ◎ This code was able to convert the songs to MP3, normalise the volume, copy them to USB, and sort them correctly. ◎ After a few minutes, I was able to jam in my car! 33 Career Opportunities ◎ Computers are used in almost all industries. ○ Medicine, agriculture, engineering, etc. ◎ As a result, programmers are in high demand. ◎ Job opportunities are varied ○ Website design ○ Data analysis ○ Research ○ ... 34 Programming is Fun and Rewarding ◎ Besides everything else, programming can just be a fun hobby. ◎ Finding a good way of solving a tricky programming task can be very satisfying. ◎ You can turn an idea into a working piece of software and share it with the world. ○ Got an idea for a cool video game? Learn to program and make it! 35 2. Computational Thinking 36 Human Thinking ◎ As humans, we have common sense and are able to “read between the lines”. ◎ We are good at reasoning and using our past experiences and intuition to solve problems. ◎ Humans are creative and independent thinkers. 37 Computer Thinking ◎ On the other hand, computers are extremely logical and do exactly what they are told. ◎ Computers do not “read between the lines” and can’t “figure things out for themselves”. ◎ Computers are literal and subordinate thinkers. ◎ This may seem frustrating at times, but computers make up for it in other ways. ○ For example, modern computers can perform billions of calculations per second! 38 The “Baby Robot” Analogy ◎ A computer is like a baby robot. ○ No prior experience. ○ Does exactly what you tell it. ◎ You need to give clear, unambiguous, step-by-step instructions. ◎ A set of such instructions is called an algorithm. 39 What is an Algorithm? ◎ An algorithm is a well-defined sequence of step-by-step instructions. ◎ There is no single algorithm---different tasks require different algorithms. ◎ An algorithm is a lot like a cooking recipe. ○ Individual, detailed steps with a defined order. ◎ Programmers design algorithms and turn them into computer programs. 40 An Algorithm for Making a Sandwich 1. Place two slices of bread on the bench. 2. Spread butter on one slice of bread using a knife. 3. Place one slice of ham on the buttered slice. 4. Place two pieces of lettuce on top of the ham. 5. Place the unbuttered slice of bread on top of the lettuce. 41 Bugs ◎ A bug is a flaw in software (program) which results in incorrect behaviour. ◎ Bugs can arise due to logical errors in an algorithm. ◎ It is important to think algorithms through carefully to avoid introducing bugs. ◎ The process of finding and fixing bugs is called debugging. 42 3. Python 43 What is a Programming Language? ◎ Computers are logical machines that follow instructions very literally. ◎ Computers do not understand plain English. ◎ In order to describe an algorithm to a computer, it is necessary to write a computer program using a programming language. ○ This is also known as “coding”. 44 What is a Programming Language? ◎ A programming language is a structured, unambiguous way of describing an algorithm. ◎ Programming languages have a strict syntax. ○ Much stricter than grammar in natural language! ○ “Typos” such as a misplaced comma or misspelled word can prevent an entire program from working. 45 Machine Code ◎ The fundamental language understood by computers is machine code. ◎ Machine code is fast and natively understood by computers, but is very, very difficult for humans to write directly. 46 Other Programming Languages ◎ Writing a program in machine code is like baking a cake with a chicken, cow, and some wheat---possible, but unnecessarily time-consuming. ◎ Other programming languages have been developed which trans late into machine code. ◎ This allow humans to indirectly produce machine code in a much easier way. ◎ Python is one such programming language. 47 Python ◎ The first version of the Python programming language was released in 1991. ◎ Python places a large emphasis on code readability. ○ That is, Python is designed to be human-friendly. ◎ The language has improved over the years. ◎ Our code will work with Python version 3.6 (released in 2016) and newer. 48 Python is Readable Even with no programming experience, you should have some idea about what this Python code does: for item in store_inventory: if item.stock <= 2: print('Low stock for ' + item.name) “For each item in the store’s inventory, if there are 2 or fewer in stock, display a low stock message with the item name.” 49 Getting Python ◎ Python is free for everyone and can be installed on Windows, Mac, and Linux computers. ◎ You can download and install Python here: ○ https://www.python.org/downloads/ ◎ There are instructional videos on LMS which walk you through setting up a Python development environment on your own computer. 50 Summary 51 In This Lecture We... ◎ Discovered why programming is a useful skill to learn. ◎ Learnt about how computers follow algorithms to solve tasks. ◎ Learnt that programming languages such as Python are used by programmers to express algorithms to computers. 52 Next Lecture We Will... ◎ Learn how flowcharts can be used to design algorithms before writing a single line of code. 53 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 54 Lecture 1.2 Flowcharts Lecture Overview 1. Introduction to Flowcharts 2. Example Flowchart: Guessing Game 3. Designing Effective Flowcharts 2 1. Introduction to Flowcharts 3 Motivation ◎ Let's say you want to start a housecleaning business. ◎ You hire three employees and start taking customers. ◎ After running your business for a while, you start receiving complaints about inconsistent results. ◎ You decide to investigate: ○ You take each employee to a bedroom, and instruct them to “clean the room”. ○ You observe different processes! 4 What Went Wrong? ◎ “Clean the room” is not a precise description of the task to be performed. ◎ Human beings fill in the gaps based on “human intuition”: ○ Past experiences, ○ Preferences, ○ Mood, ○ etc. 5 What Can Be Done? ◎ Document the steps in detail, without room for interpretation. ○ i.e. design the algorithm. ◎ Hand out the detailed instructions. ◎ Each employee can now follow the exact same process. 6 Motivation ◎ Describing processes in detail is especially important for machines. ◎ Computers typically do exactly what they are told and lack any “human intuition”. ○ Recall the baby robot analogy. ◎ This means that a detailed algorithm is not just preferable---it is required. 7 Describing Processes ◎ One way of describing a process is through written paragraphs. ◎ Complicated processes can be difficult to read. Begin by dusting the furniture and blinds. Next, vacuum the floor. If the floor is carpeted, then you should shampoo the carpet. Otherwise, if the floor is not carpeted, mop the floor. 8 Describing Processes ◎ Another way of describing a process is with a flowchart. ◎ A flowchart provides a clear visual representation. 9 What is a Flowchart? ◎ A flowchart diagram details the flow of a process. ○ Used to document or communicate a process. ○ Describes steps clearly and unambiguously. ○ Applicable to both physical processes and computer processes. 10 What is a Flowchart? ◎ Flowcharts can be a useful tool for designing computer programs before writing code. ○ Helps you to think through the individual decisions and steps involved in a process. ○ Can be translated into actual programming code afterwards. 11 The Origin of Flowcharts ◎ The first flowcharts were introduced in 1921. ◎ Covered workflows like “loading rifle grenades”. 12 Elements of a Flowchart ◎ A flowchart consists of shapes joined with arrows. ○ The arrows describe the flow of the process. ○ The shapes describe steps in the process. ◎ We will now describe the meaning of each of the different shapes. 13 Start/Stop Elements ◎ Start/stop elements describe points where a process begins and ends. ◎ Start element: 1 outgoing arrow. Start ◎ Stop element: 1 incoming arrow. ◎ Each flowchart should include one start element and one stop element. ◎ Represented rectangles. using Stop rounded 14 Process Elements ◎ Process elements describe a processing step. ◎ 1 incoming arrow and 1 outgoing arrow. ◎ Description usually starts with a verb (action). ◎ Flowcharts can include many process elements. Pay the bill ◎ Represented using rectangles. 15 Input/Output Elements ◎ Input/output elements describe points where data enters/leaves a program. ○ e.g. Accepting user input, displaying results. Input name ◎ 1 incoming arrow and 1 outgoing arrow. ◎ Flowcharts typically include at least one input and one output element. Display cost ◎ Represented using parallelograms. 16 Decision Elements ◎ Decision elements select between multiple flows based on some kind of test condition. ◎ 1 incoming arrow and multiple outgoing arrows. no Is age ≥ 65? ◎ Often phrased as a yes/no question. ◎ Represented using diamonds. yes 17 Connectors ◎ Connector elements join multiple flows. ◎ Multiple incoming arrows and 1 outgoing arrow. ◎ Useful for rejoining multiple flows after a decision. ◎ Represented using circles. 18 Check Your Understanding Q. What are the expected outputs of the program described by this flowchart when the user inputs an age of 19? 19 Check Your Understanding Q. What are the expected outputs of the program described by this flowchart when the user inputs an age of 19? A. “adult” and “ticket”. “adult” is output because age (19) is not less than 18. “ticket” is always output irrespective of the input age. 20 2. Example Flowchart: Guessing Game 21 Task Definition The computer picks a number between 1 and 100, and the user tries to guess that number. Whenever the user makes an incorrect guess, they are told whether the number is higher or lower than their guess. When the user correctly guesses the number, a victory message is displayed and the program stops. 22 Example Behaviour 1. 2. 3. 4. 5. 6. 7. 8. 9. Generate a random number (x ← 44). Input user guess (y ← 25). Is y equal to x? No. Is x greater than y? Yes, display “Higher”. Input user guess (y ← 50). Is y equal to x? No. Is x greater than y? No, display “Lower”. Input user guess (y ← 44). Is y equal to x? Yes, display “Correct”. 23 Identifying Flowchart Elements ◎ We can analyse the example behaviour to identify flowchart elements: ○ Input/output ○ Decision ○ Process 24 Identifying Input/Output Elements 1. 2. 3. 4. 5. 6. 7. 8. 9. Generate a random number (x ← 44). Input user guess (y ← 25). Is y equal to x? No. Is x greater than y? Yes, display “Higher”. Input user guess (y ← 50). Is y equal to x? No. Is x greater than y? No, display “Lower”. Input user guess (y ← 44). Is y equal to x? Yes, display “Correct”. 25 Identifying Input/Output Elements ◎ Inputs: ○ User guess (a number, y). ◎ Possible outputs: ○ Higher hint (“Higher”). ○ Lower hint (“Lower”). ○ Victory message (“Correct”). Input guess as y Display “Higher” Display “Lower” Display “Correct” 26 Identifying Decision Elements 1. 2. 3. 4. 5. 6. 7. 8. 9. Generate a random number (x ← 44). Input user guess (y ← 25). Is y equal to x? No. Is x greater than y? Yes, display “Higher”. Input user guess (y ← 50). Is y equal to x? No. Is x greater than y? No, display “Lower”. Input user guess (y ← 44). Is y equal to x? Yes, display “Correct”. 27 Identifying Decision Elements ◎ Is y equal to x? ◎ Is x greater than y? Is y == x? Is x > y? 28 Identifying Processing Elements 1. 2. 3. 4. 5. 6. 7. 8. 9. Generate a random number (x ← 44). Input user guess (y ← 25). Is y equal to x? No. Is x greater than y? Yes, display “Higher”. Input user guess (y ← 50). Is y equal to x? No. Is x greater than y? No, display “Lower”. Input user guess (y ← 44). Is y equal to x? Yes, display “Correct”. 29 Identifying Processing Elements ◎ Generate a random number (x). Generate a random number between 1 and 100 as x 30 Constructing the Flowchart ◎ Now that we have the elements, we can construct the flowchart. ◎ Need to think about the flow (order of steps). ◎ Once again, the example behaviour is a good reference. 31 Start Generate a random number between 1 and 100 as x Input guess as y Is y == x? yes no Is x > y? yes Display “Higher” no Display “Lower” Display “Correct” Stop 32 Next Steps ◎ Computers can’t read flowcharts like this one directly. ◎ The next step towards creating a working program would be to translate the flowchart into code (program). ○ This will be covered in future lectures. ◎ Having a well-designed flowchart makes writing code much easier. 33 3. Designing Effective Flowcharts 34 Order is Important ◎ Order is important. ◎ Think carefully about the order in which things should happen as you draw the flowchart. Would you trust this recipe? 1. Take the cake out of the oven. 2. Mix ingredients thoroughly. 3. Allow the cake to cool. 4. Put the cake into the oven. 5. Add ingredients into the bowl. 35 Clear, Concise, and Complete ◎ Clear ○ Space elements out. ○ Avoid crossing over arrows where possible. ◎ Concise ○ Use short, accurate descriptions. ○ Avoid unnecessary duplication. ◎ Complete ○ Cover all possible eventualities. 36 Start Generate a random number between 1 and 100 as x ✗ Incomplete. What happens if x is not greater than y? Input guess as y Is y == x? yes no Is x > y? yes Display “Higher” Display “Correct” Stop 37 Start Generate a random number between 1 and 100 as x ✗ Unnecessarily repeated elements add clutter. Input guess as y Is y == x? Input guess as y yes Input guess as y no Is x > y? yes Display “Higher” no Display “Lower” Display “Correct” Stop 38 Top-To-Bottom Layout ◎ Aim for the process to flow from top to bottom. ◎ Arrows should generally point downwards. ◎ Put the start element at the top of the page. ◎ Put the stop element at the bottom of the page. ◎ Sometimes decisions cause the flow to go back up, this is OK. 39 Input guess as y ✗ Inconsistent flow direction is hard to follow. Stop no Is y == x? yes Display “Correct” Display “Higher” yes Generate a random number between 1 and 100 as x Is x > y? no Start Display “Lower” 40 Know Your Arrows ◎ Different elements have different numbers of incoming and outgoing arrows. ◎ Check that each element in your flowchart has the correct number of arrows. ◎ Use connectors where appropriate. 41 ELEMENT INCOMING ARROWS OUTGOING ARROWS Start 0 1 Stop 1 0 Process 1 1 Input/Output 1 1 Decision 1 2+ 2+ 1 Connector A table showing the correct number of arrows for each flowchart element. 42 Start ✗ Generate a random number between 1 and 100 as x Input guess as y Is y == x? no Is x > y? Incorrect number of incoming arrows. Use connectors to make joined flows obvious. yes yes Display “Higher” no Display “Lower” Display “Correct” Stop 43 Flowchart Creation Checklist ✓ Is there one start element and one stop element? ✓ Are the elements in a logical order? ✓ Is the flowchart clear, concise, and complete? ✓ Does the flowchart flow from top to bottom? ✓ Is the number of arrows correct? 44 Summary 45 In This Lecture We... ◎ Discovered the purpose of flowcharts. ◎ Learnt the essential flowchart elements. ◎ Worked through creating a flowchart from a task definition. ◎ Explored best flowcharts. practices for designing effective 46 Next Lecture We Will... ◎ Begin learning basic elements of programming code: ○ Variables, ○ Statements, and ○ Comments. 47 Labs Start Next Week (Week 2) ◎ Please attend the lab class that you're enrolled in. ◎ Bring your laptop if you have one. ○ You will be setting up programming software. 48 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 49

Use Quizgecko on...
Browser
Browser