Programming Principles Lecture 2: Data Types and Selection This Lecture • Data types – Common data types: integer, float, string and boolean – Weak/Strong typing and type conversion – Implicit and explicit conversion – Static and dynamic typing – Numeric, string and boolean conversions • Selection – If-then, if-then-else and else-if statements – Boolean expressions – Comparison operators and logical operators 2 Textbook • Starting Out with Python, 4th Edition (Global) – Tony Gaddis • Reading the chapter(s) is required – Read the indicated chapter(s) before class • This week covers the following textbook chapter(s): – Chapter 3 – Decision Structures and Boolean Logic – Note: You may also wish to revise parts of Chapter 2 regarding data types 3 Data Types Data Types • Last week we introduced the concept of variables – Assigning a name to data stored in memory for later use • We also briefly mentioned data types – the “categories” of data – Integers, floating point numbers (floats), strings… – The difference can be subtle; 3.14 is a float, '3.14' is a string – All data (and hence every variable) in a program has a data type • The data type essentially tells the language/computer how to interpret the values that are stored in memory – It determines what can and cannot be done with the data, e.g. Arithmetic works on integers and floats, but not strings – Functions often require values of a certain data type, e.g. round() needs a float and an integer: round(2.327, 2) 5 Data Types • The most common data types are: Type Description Examples integer (int) Whole numbers 2, -500, 4294967296 float (float) Numbers with a fractional part 3.14159, -0.3, 25.0 string (str) A sequence of characters 'Hello, World!', '25', ' ' boolean (bool) A true or false value True, False • Some languages divide numeric data types further – Data types for very large numbers, e.g. “long” in Java, or numbers with large fractional parts, e.g. “double” in Java • Some languages, such as C, do not support strings – Such languages typically have a “character” or “char” data type, representing a single character. An “array” of multiple characters can be used to represent a string 6 “Weak” and “Strong” Typing • Different languages take different approaches to whether data types can be mixed and converted automatically • “Weakly typed” languages focus on being convenient – Generally achieved by making it easier to mix different data types together and converting between them automatically wherever appropriate • The programming language tries to work things out for you • “Strongly typed” languages focus on being safe – Generally achieved by limiting the ability to mix different data types together – conversions must be done explicitly by the programmer • The programmer must consider and convert types manually • Languages allow and disallow things based on their design, often ending up somewhere between weak and strong 7 Data Type Conversion and Coercion • Some values can be converted between different data types – e.g. 100 (int), 100.0 (float) and '100' or '100.0' (strings) • All languages provide ways to convert between data types – e.g. The int(), float() and str() functions in Python – Some languages use “(typename) value”, e.g. (int) 3.14 – Conversion will fail (or give unexpected results) if it doesn’t make sense, e.g. trying to convert a string of 'cat' to an int – Some conversions may involve a loss of data, e.g. converting 3.14 to an int • Many languages do implicit (automatic) conversion between compatible data types as needed, where possible; This is known as coercion – Integers are commonly coerced to floats, e.g. 5 + 2.5 would become 5.0 + 2.5 – Languages like PHP can coerce numeric strings, e.g. 1 + '2' + 3.4 = 6.4 8 Static and Dynamic Typing • “Static typing” is when a language requires you to declare (and adhere to) the data type of every variable you create. C and Java are statically typed – Trying to assign a value of a different type will result in an error (or coercion) – Helps program/memory optimisation and to prevent type-related bugs • “Dynamic typing” is when the data type of a variable is determined by the value it currently refers to, which can change. Python and PHP are dynamically typed – You do not “declare” a data type for the variable, you just assign a value to it – Convenient, particularly in languages which coerce data types automatically String value; // declare a string value = 1; // assign int to string Error: Incompatible types int value; // declare an int value = 3.14; // assign float to int 3 Java C value = 1 # int 1 HELLO, my name is… total Python value = 'Potato' # string 'Potato' value = -2.74 # float -2.74 9 Type Conversion Example – Numbers • What is happening in these examples? int value_1 = 15; int value_2 = 20; Java value_1 = 15 value_2 = 20 Python float result = value_1 / value_2; result = value_1 / value_2 System.out.println(result); 0.0 print(result) 0.75 – In Java (and some other “strongly typed” languages), dividing an integer by another integer results in an integer • The result was truncated to 0, then stored as a float of 0.0 • No rounding was performed; It simply kept the integer portion only – In Python (and other “weakly typed” languages), the result of dividing two integers is automatically coerced to a float 10 Type Conversion Example – Numbers • In this version, we explicitly convert value_one to a float int value_1 = 15; int value_2 = 20; Java float result = (float) value_1 / value_2; // convert value_1 to float System.out.println(result); 0.75 – We use (float) to convert value_1, an integer, to a float – 15.0 • Java will coerce value_2 to match, and give the result as a float – In Java, the result of any arithmetic is “widened” to the more encompassing data type; int < long < float < double… e.g. • int / int = int • float / float = float • float / int = float • int / float = float 11 Type Conversion Example – String Concatenation • What is happening in these examples? total = 79.4 Python output = 'The total is ' + total TypeError: can only concatenate str (not "float") to str output = total + ' is the total' TypeError: unsupported operand type(s) for +: 'float' and 'str' – Both of them are trying to combine a string and a float • In the first one, the error message says that concatenation can only be performed between strings, not between a string and a float • In the second one, the error message says that you cannot add a float and a string together – that’s not how arithmetic works! – The goal is the same in both – concatenating them together into a single string, i.e. 'The total is 79.4' or '79.4 is the total' • The solution to both is to convert total to a string: str(total) 12 Type Conversion Example – String Concatenation • In this version, we explicitly convert total to a string total = 79.4 Python output = 'The total is ' + str(total) 'The total is 79.4' output = str(total) + ' is the total' '79.4 is the total' – We use the str() function to convert total to a string • Now that there are strings on both sides of the “+”, Python can determine that you want to concatenate them and do so without any problems • Reminder: The total variable still refers to a float of 79.4 – the str() function simply produces a string version of the value – it does not change the variable itself – Concatenating numbers and strings is an area that languages handle differently • We’ll look at some examples on the next slide! 13 Type Conversion Example – String Concatenation var num = 79.4; alert(num + ' is the total') '79.4 is the total' JavaScript var string_num = '25'; alert(num + string_num) '79.425' – JavaScript always coerces both values to strings and concatenate them – Even if the string contains a number… $total = 79.4; echo 'The total is ' . $total; 'The total is 79.4' PHP echo "$total is the total"; '79.4 is the total' – PHP avoids ambiguity by using “.” for concatenation – It can also detect variables inside strings due to the “$” at the start of variable names total = 79.4 print(total, 'is the total. The total is', total) '79.4 is the total. The total is 79.4' – As covered last week, Python’s print() function offers another way of combining strings and numbers… Python Reading 5.3 (Module 5) introduces an approach that is very elegant and flexible! 14 Type Conversion Example – Boolean Values • True and False are the only two boolean values, but values of other data types can always be converted to a boolean value – The bool() function converts a value to a boolean value bool(5) # positive int True bool(-245.271) # negative float True bool('False') # string of 'False' True bool('0') # string of 0 True Python bool(0) # int of 0 False bool(0.0) # float of 0.0 False bool('') # empty string False bool([]) # an empty "list" False Python • The rule that most languages follow when converting to a boolean value is: – Values equivalent to 0, or empty/blank values are considered False – All other values are considered True • As always, there can be subtle differences between languages… e.g. '0' (a string of the “zero” character) is True in Python, but False in PHP 15 Data Types / Type Conversion Summary • While there are general concepts such as “weak” and “strong” typing, our examples have demonstrated that… – Almost every language handles things slightly differently! – Regardless of what a language allows and supports, a good programmer should always consider data types • Know what type your data is, and how it can be used • Learn how your language behaves when mixing/coercing types • Failing to do so can result in bugs and security vulnerabilities – Always test your code thoroughly to ensure it is working • Particularly in weakly typed languages or ones you’re new to • You won’t always receive an error message to let you know! input() always returns the user’s input as a string. Arithmetic requires integer and/or float values. This is why the user’s input was converted to a float in Lecture 1’s program. 16 Selection Selection • When a program is run, it runs the statements in the source code from start to end (unless it encounters an error) – Certain statements allow for a choice between different blocks of code to run based upon the result of checking for a specific condition – These are known as selection statements If timer value is 0 Make beeping noise Pseudocode – In this example, the beeping noise only occurs if the timer value is 0 • We will examine the most common selection statement – “if-then” (aka just “if”) – Can be extended upon with “else” and “else-if” – Another selection statement, “switch”, is covered in Reading 2.4 18 If-Then Statements • An if-then statement will run a block of code only if a condition (known as a “boolean expression”) evaluates to True – Often used run certain code in response to user input Python # tax free threshold check income = int(input('Enter income: ')) condition True False if income <= 18200: print('No tax for you!') // tax free threshold check int income; printf("Enter income: "); scanf("%d", &income); C only run if true if(income <= 18200) { printf("No tax for you!"); } 19 If-Then Statements • The structure of an if-then statement is largely the same in most languages, although Python strives for readability and uses indentation – Most languages: Boolean expression if (<boolean expression>) in parentheses { <code to run if True> } True-code enclosed by braces (curly brackets) – Python: if <boolean expression>: <code to run if True> No parentheses, but a colon at the end True-code controlled by indentation (4 spaces is the standard/default) 20 If-Then Statements • There are some subtle nuances that you should be aware of… (remember, we’re learning a concept, not a language) – In languages that use braces (curly brackets), they are usually optional if only one statement is to be run when the expression is true: if (<boolean expression>) <single statement to run if True> <code to run regardless> – Some languages use (or just allow) “endif” instead of braces: if (<boolean expression>) <code to run if True> endif 21 Boolean Expressions & Comparison Operators • Selection statements choose which code to run based upon the result of a boolean expression – i.e. An expression that results in either True or False • You can compare values and receive a True or False result by using a comparison operator Comparison Operator Description Example Example Result < Less than 7 < 2 False <= Less than or equal to 5 <= 5 True > Greater than 7 > 2 True >= Greater than or equal to 7 >= 2 True == Equal to 7 == 2 False != Not equal to 7 != 2 True – Many functions will return (result in) either True or False – A non-boolean value can be coerced to either True or False 22 If-Then / Boolean Expression Examples • Example 1: Comparing a numeric variable to a number: score =user Prompt float(input('Enter for a score outaof score 100 out of 100: ')) If score < 50: if 50 Show 'You fail!' print('You fail!') Pseudocode Python – The input was converted to a float (using the float() function), so that the “less than” comparison with a number works as intended • Example 2: Using a function in a comparison: value =user Prompt input('Enter to type exactly exactly55characters characters: ') If input if len(value) length !=!= 5:5 Show error message print('Error: Incorrect number of characters.') Pseudocode Python – The built-in function len() returns the “number of items in an object” (in this case, the number of characters in the string) – We are using a “not equal to” comparison (!=) to check if the length of the string is not equal to 5 23 If-Then / Boolean Expression Examples • Example 3: Using a boolean value returned from a function: value =user Prompt input('Enter to type something somethingin inupper uppercase case: ') If user if value.isupper(): typed something in upper case Congratulate user print('Congratulations on typing in upper case!') Pseudocode Python – .isupper() is a function that can only be used on strings, hence why it is “attached to the end” of the string variable instead of being “wrapped around it” – .isupper() returns True if all of the letters in the string are uppercase • Example 4: Using a coerced boolean value: value =user Prompt input('Type to type anything!: anything ') If value: if user typed at least one character Congratulatedone!') print('Well user Pseudocode Python – The value variable is coerced to a boolean value (see earlier slide): An empty string ('') is False, anything else is True 24 Logical Operators • Often you will need to make multiple comparisons in a boolean expression. For this we use logical operators – e.g. “is A and B True?”, or “is A or B True?” – You may also find situations where you want to know if something is not true, i.e. turn False into True and vice-versa – For added readability, Python uses “and”, “or” and “not” for logical operators. Many languages use “&&”, “||” and “!” Logical Operator Description Example Example Result Python Alternate and && True if both comparisons are true, otherwise false 1 < 5 and 4 == 6 False or || True if either (or both) comparison is true, false if they are both false 1 < 5 or 4 == 6 True not ! Reverse/Flip true and false not (1 < 5) False 25 Logical Operator Truth Tables & Evaluation • These “truth tables” illustrate which situations will result in which outcome when using logical operators: and True False or True False True True False True True True False False False False True False – An “and” will only be True if both expressions are True; If either (or both) are False, the end result is False – An “or” will be True if either (or both) expressions are True • Logical operators are evaluated after evaluating the expressions on either side of them to True/False 5 > 2 and 6 < 4 True and False False 26 If-Then / Logical Operator Examples • Example 1: Using “and”: value =user Prompt float(input('Enter to a number between a number 5 and between 15 5 and 15: ')) If value if number>= is5between and value 5 and <= 15: 15 Congratulatedone!') print('Well user Pseudocode Python • Example 2: Using “or”: value =user Prompt input('Enter to type at atleast least55characters, characters,no with spaces no spaces: Pseudocode ') Python If input if len(value) length < < 5 5 oror value.count(' input contains ') spaces > 0: Show 'Better luck print('Better lucknext nexttime!' time!') – count() is a function that can be used on strings. It returns the number of occurrences of a specified string within another string • Example 3: Using “not”: Prompt value =user input('Type to type something that isn't is notaaletter letter: ') If if input not value.isalpha(): is not a letter Congratulate print('Well done!') user Pseudocode Python – .isalpha() is another function that can only be used on strings. It returns True if all of the characters in the string are letters 27 Terrible Programmer Joke Break! Mum said, “Please go to the market and get a bottle of milk, and if they have eggs, get six.” I came back with six bottles of milk. Mum asked, “Why did you get six bottles of milk?!” I replied, “Because they had eggs!” 28 Boolean Expression & Logical Operator Notes • Each side of an “and” or an “or” must be a full comparison – x == 0 or 1 ✘ x == 0 or x == 1 ✔ • Boolean expressions can have multiple logical operators – Order of operations: “not” first, then “and”, then “or” – e.g. True or False and not True True or False and False (not evaluated) True or False (and evaluated) True (or evaluated) – Parentheses can be used to alter order of operations – e.g. (True or False) and not True (result is False) – Even if not altering the order of operations, parentheses are a good way to make your code clearer and more readable 31 If-Then-Else Statements • An if-then-else statement runs one block of code if the boolean expression is true, and another block if it is false – it is an extension of an if-then statement Python # test result check result = int(input('Enter your result: ')) if result >= 50: print('You passed!') else: print('You failed!') condition True False only run if true only run if false // checkbox check if (document.form.checkbox.checked) { alert('Checkbox checked!') } else { alert('Checkbox not checked!') } JavaScript 32 If-Then-Else Statements • An if-then-else statement uses the word “else” to indicate the block of code to be run if the expression is False – Everything we have discussed regarding if-then is relevant to if-then-else (e.g. optional braces for single statements) – Most languages: if (<boolean expression>) { <code to run if True> } else { <code to run if False> } – Python: if <boolean expression>: <code to run if True> else: <code to run if False> 33 If-Then-Else Examples name = input('Name: ') Python if name.isalpha(): print('Letters!') else: print('Not all letters!') – Prompt user to type their name – If the name consists of only alphabetic characters, print “Letters!” – Otherwise print “Not all letters!” – total_mark is an integer – exam_passed is a boolean – If both conditions are True (&& is and), “You passed!” otherwise “You failed!” • The else applies to all other outcomes (one or both conditions False) if (total_mark >= 50 && exam_passed) Java { System.out.println("You passed!"); } else { System.out.println("You failed!"); } 34 Nested If-Then-Else Statements • If-Then-Else statements can be “nested” within one another – This allows you to test multiple conditions and run different code depending on which ones are met, to implement whatever sequences of checks your program needs… Python if <condition 1>: <run if condition 1 True> else: if <condition 2>: <run if condition 1 False and condition 2 True> else: <run if both False> This is just one example of how selection statements can be nested: Any desired flow of logic possible! Most Languages if (<condition 1>) { <run if condition 1 True> } else { if (<condition 2>) { <run if condition 1 False and condition 2 True> } else { <run if both False> } } 35 Else-If • If-Then can be also expanded by using an Else-If – This allows you to “chain” selection statements together – Only the code following the first condition that is True is run condition 1 False True condition 2 False True condition 3 True only run if condition 1 true • Languages use slightly different else-if syntax: – “else if” only run if condition 2 true • C, C++, Java, PHP, JavaScript… – “elseif” • PHP, Visual Basic… only run if condition 3 true False only run if all conditions false – “elsif” • Ada, Perl, Ruby… – “elif” • Python, Bash… 36 Else-If • While the word used for else-if may differ between languages, it works the same in pretty much all of them – Remember, Python uses indentation instead of braces (“{}”)! if <condition 1>: <run if condition 1 True> Python elif <condition 2>: <run if condition 2 True> elif <condition 3>: <run if condition 3 True> elif <condition 4>: <run if condition 4 True> else: <run if all conditions False> Placing the opening brace after the condition/else instead of on a separate line is a common space-saving technique Most Languages if (<condition 1>) { <run if condition 1 True> } else if (<condition 2>) { <run if condition 2 True> } else if (<condition 3>) { <run if condition 3 True> } else if (<condition 4>) { <run if condition 4 True> } else { <run if all conditions False> } 37 Else-If Example • Here’s an (overused) example for grade calculation: Pseudocode PROMPT for mark # calculate grade from mark mark = float(input('Enter your mark: ')) IF mark >= 80 SET grade to 'HD' if mark >= 80: grade = 'HD (High Distinction)' ELSE IF mark >= 70 SET grade to 'D' elif mark >= 70: grade = 'D (Distinction)' ELSE IF mark >= 60 SET grade to 'CR' elif mark >= 60: grade = 'CR (Credit)' ELSE IF mark >= 50 SET grade to 'P' elif mark >= 50: grade = 'P (Pass)' ELSE else: grade = 'F (Fail)' SET grade to 'F' DISPLAY grade Python print('Your grade is:', grade) 38 Else-If Example • A flowchart for this program would look like: Prompt for mark mark >= 80 True Set grade to HD False mark >= 70 True Set grade to D False mark >= 60 True Set grade to CR False mark >= 50 True Set grade to P False Set grade to F Display grade 39 Conclusion • It is important to be aware of data types, even in languages which make it convenient to mix them implicitly – Know how your language coerces things, what it allows and doesn’t allow, how to convert things explicitly, etc… • If-Then statements allow you to make a choice in your code – Controlled by boolean expressions, which can involve comparison operators and logical operators – If-Then-Else to do one thing or another – Else-If to chain multiple comparisons together 40