Lecture 20 – Test revision COMPSCI 101 Principles of Programming
Naming conventions Python types Variables Strings Operators Algebraic expressions The math module, the random module Getting input from the user Functions Boolean expressions, selection statements Loops – while and for…in Lists Test topics CompSci Principles of Programming2
Variable names Must begin with a letter or underscore, e.g., number1 is OK, but 1number is not May contain letters, digits, and underscores, e.g., this_is_an_identifier_123 May be of any length Upper and lower case letters are different, e.g., Rope_Length is not the same variable as rope_length The standard way for most things named in python is lower case with separate words joined by an underline, e.g., my_list x age age_of_child box1 box_2 _age age_ x age age_of_child box1 box_2 _age age_ 3 age of child age-child 1st 2_box 3 age of child age-child 1st 2_box valid variable names: NOT valid variable names: CompSci Principles of Programming3
Python types encountered this semester Information in a program is categorised into different types. A type in Python defines two things: the internal structure of the type (the information being stored) the kinds of operations you can perform with this type of object int float string boolean list CompSci Principles of Programming4
Converting between types Some types can be converted into different types: result1 = int("2.1") result2 = float("2.1 ") input = "2.1" result3 = "$" + float(input) result1 = int("2.1") result2 = float("2.1 ") input = "2.1" result3 = "$" + float(input) result1 = float("2.1") result2 = int("24") result3 = float("24") input = "2.1" result4 = "$" + str(float(input) * 2) result1 = float("2.1") result2 = int("24") result3 = float("24") input = "2.1" result4 = "$" + str(float(input) * 2) NO! YES! CompSci Principles of Programming5
Doing Calculations The following mathematical operators can be used with integers and with floating point numbers: Addition + Subtraction- Multiplication* Division/ and // Exponentiation** Modulus % result1 = 25 / * (10 % 3) result2 = * (3 + 12) / 3 result3 = 17 % 5 ** result4 = 4 ** 2 // 5 / 2 print(result1, result2, result3, result4) result1 = 25 / * (10 % 3) result2 = * (3 + 12) / 3 result3 = 17 % 5 ** result4 = 4 ** 2 // 5 / 2 print(result1, result2, result3, result4) B - Brackets Exponents (**) Multiplication, Division, Modulus, Integer division Addition, Subtraction B - Brackets Exponents (**) Multiplication, Division, Modulus, Integer division Addition, Subtraction CompSci Principles of Programming6
Assignment operator Variables can only store one value. Any value assigned to a variable replaces the value previously stored in the variable. a = 3 b = 12 c = 6 d = 1 d = d * a c = c + 2 * a d = d - b // c c = c * b % c b = b // 2 print (a, b, c, d) a = 3 b = 12 c = 6 d = 1 d = d * a c = c + 2 * a d = d - b // c c = c * b % c b = b // 2 print (a, b, c, d) CompSci Principles of Programming7
math module The math module contains lots of useful functions: import math def main(): area = radius = math.sqrt(area / math.pi) print("Radius of circle", radius) main() import math def main(): area = radius = math.sqrt(area / math.pi) print("Radius of circle", radius) main() CompSci Principles of Programming8
Manipulating string objects strings: the len() function, string slicing, string indices, repeating a string words = "Cheeky one" letter1 = words[0] position = len(words) - 2 letter2 = words[position] print(letter1, letter2) first_part = words[0:4] second_part = words[5:8] print(second_part, first_part) first_part = words[:3] second_part = words[7:] print(second_part, first_part) encouragement = "Go! " encouragement = encouragement * 4 print(encouragement) words = "Cheeky one" letter1 = words[0] position = len(words) - 2 letter2 = words[position] print(letter1, letter2) first_part = words[0:4] second_part = words[5:8] print(second_part, first_part) first_part = words[:3] second_part = words[7:] print(second_part, first_part) encouragement = "Go! " encouragement = encouragement * 4 print(encouragement) CompSci Principles of Programming9
Dot notation with string objects String instances have many methods which can be applied to them such as upper(), lower(), find(), strip(), rfind() words = "Bim Bam" words_lower = words.lower() words_upper = words.upper() print(words, words_lower, words_upper) words = "Sweety pie" postion1 = words.find("e") postion2 = words.rfind("e") postion3 = words.rfind("ty") position4 = words.rfind("typ") print(postion1, postion2, postion3, position4) letters1 = " Sugar pie " letters2 = letters1.strip() print(len(letters2)) words = "Bim Bam" words_lower = words.lower() words_upper = words.upper() print(words, words_lower, words_upper) words = "Sweety pie" postion1 = words.find("e") postion2 = words.rfind("e") postion3 = words.rfind("ty") position4 = words.rfind("typ") print(postion1, postion2, postion3, position4) letters1 = " Sugar pie " letters2 = letters1.strip() print(len(letters2)) CompSci Principles of Programming10
Common Python inbuilt functions Inbuilt: len(), min(), max(), round(), abs() number = min(32.7, max(16.4, 3, -1.1), min(56.99, 32.2)) print(number) num1 = num2 = print(round(num1)) print(round(num2)) print(round(num1, 2)) print(round(num2, 3)) num1 = 10 num2 = 20 num3 = abs(num1 – num2) print(num3) number = min(32.7, max(16.4, 3, -1.1), min(56.99, 32.2)) print(number) num1 = num2 = print(round(num1)) print(round(num2)) print(round(num1, 2)) print(round(num2, 3)) num1 = 10 num2 = 20 num3 = abs(num1 – num2) print(num3) CompSci Principles of Programming11
Getting input from the user The input() function is used to get input from the user. The input() function returns a string. age = input("Enter age: ") print(age * 2, age * 3, age * 4) number = input("Enter number: ") number = int(number) print(number * 2, number * 3, number * 4) age = input("Enter age: ") print(age * 2, age * 3, age * 4) number = input("Enter number: ") number = int(number) print(number * 2, number * 3, number * 4) Enter age: 5 Enter number: 5 Enter age: 5 Enter number: 5 CompSci Principles of Programming12
Random numbers What is the biggest value which can be printed? What is the smallest value which can be printed? import random def main(): num1 = random.randrange(2, 15, 3) num2 = random.randrange(24, 27, 2) num3 = num1 + num2 print(num3) main() import random def main(): num1 = random.randrange(2, 15, 3) num2 = random.randrange(24, 27, 2) num3 = num1 + num2 print(num3) main() CompSci Principles of Programming13
Syntax of a Python function Format of a function def function_name(comma_separated_parameters): statements in the function return value_to_be_returned def function_name(comma_separated_parameters): statements in the function return value_to_be_returned Function nameFunction parameters colon 'def' Indentation (either 1 tab or 4 spaces) Return value'return' Statements in the body of the function. CompSci Principles of Programming14
Python functions def display_welcome(name): message = "Welcome **" + name + " **" print(message) def main(): display_welcome("Sam") def display_welcome(name): message = "Welcome **" + name + " **" print(message) def main(): display_welcome("Sam") def display_welcome(name): message = "Welcome **" + name + " **" print(message) return def main(): display_welcome("Sam") def display_welcome(name): message = "Welcome **" + name + " **" print(message) return def main(): display_welcome("Sam") Both functions do the same thing. The return is optional. CompSci Principles of Programming15
Defining functions Complete the definition of the check_sum() function, which returns True if the sum of the first three parameter values is equal to the fourth parameter value, otherwise the method returns False. def check_sum( ): def main(): print(check_sum(15, 2, 7, 24)) print(check_sum(10, 2, 3, 24)) main() def check_sum( ): def main(): print(check_sum(15, 2, 7, 24)) print(check_sum(10, 2, 3, 24)) main() True False True False CompSci Principles of Programming16
Defining functions Complete the definition of the get_next_even() function which returns the first even number greater than the parameter number. def get_next_even( ): def main(): print(get_next_even(15)) print(get_next_even(10)) main() def get_next_even( ): def main(): print(get_next_even(15)) print(get_next_even(10)) main() CompSci Principles of Programming17
Code trace Show the code trace and the output for the program def main(): years = 5 result = test1(years) print("A", result) result = test2(years + 5) print("B", years) def test1(num): print("C", num) num = test2(num) + 4 return num def test2(num1): num1 = max(num1 + 1, 10) print("D", num1) return num1 main() def main(): years = 5 result = test1(years) print("A", result) result = test2(years + 5) print("B", years) def test1(num): print("C", num) num = test2(num) + 4 return num def test2(num1): num1 = max(num1 + 1, 10) print("D", num1) return num1 main() years 5 main() function CompSci Principles of Programming18
Booleans represent "truth" values, i.e., True or False Relational operators compare two different things, which evaluates to Boolean values Boolean Operators are: and, or and not, e.g., (age=24, gender='F') (age > 18) and (gender == 'F') is True (age > 34) or (gender == 'M') is False not (age > 18) is False Boolean expression 19COMPSCI Principles of Programming DescriptionOperatorExample Equals==age == 10 Less than<age < 10 Less than or equal<=age <= 10 Greater than>age > 10 Greater than or equal>=age >= 10
If statements x = 10 y = 5 if x < 10: if y != 5: print("A") else: print("B") elif y > 10: print("C") else: if y != 5: print("D") else: print("E") x = 10 y = 5 if x < 10: if y != 5: print("A") else: print("B") elif y > 10: print("C") else: if y != 5: print("D") else: print("E") a = 4 b = 12 c = 37 d = 51 if a < b: print("A") if a > b: print("B") if d <= c: print("C") if c != d: print("D") a = 4 b = 12 c = 37 d = 51 if a < b: print("A") if a > b: print("B") if d <= c: print("C") if c != d: print("D") CompSci Principles of Programming20 Give the output
Repetition – while loops Give the possible output: import random def main(): sum = 0 while sum < 10: number = random.randrange(1, 7) sum += number print(sum, number) final_sum = sum – number print("Finally", final_sum) main() import random def main(): sum = 0 while sum < 10: number = random.randrange(1, 7) sum += number print(sum, number) final_sum = sum – number print("Finally", final_sum) main() while boolean_expression: indented_code_block CompSci Principles of Programming21
range(start, stop, step) function The range() function defines a sequence of values within the boundaries (exludes the last value). The step parameter is optional. A for...in loop can be used to repeat code for each element in the specified range. Give the output. number = 50 for num in range(10, 1, -4): number = number – num print("number:", number) sum = 0 for number in range(10, 16, 2): sum += number print("sum:", sum) number = 50 for num in range(10, 1, -4): number = number – num print("number:", number) sum = 0 for number in range(10, 16, 2): sum += number print("sum:", sum) number: sum: number: sum: CompSci Principles of Programming22
Repetition – for loops Give the possible output: def count_vowels(words): vowels = "aeiouAEIOU" length = len(words) count = 0 for i in range(length): if vowels.find(words[i]) != -1: count = count + 1 return count def main(): word = input("Enter the word(s): ") print("Output: " + str(count_vowels(word)) + ".") main() def count_vowels(words): vowels = "aeiouAEIOU" length = len(words) count = 0 for i in range(length): if vowels.find(words[i]) != -1: count = count + 1 return count def main(): word = input("Enter the word(s): ") print("Output: " + str(count_vowels(word)) + ".") main() for var_name in range(start, stop, step): indented_code_block CompSci Principles of Programming23
Lists A list is a sequence of comma separated elements within square brackets. Elements of a list can be accessed using the index. The '+' operator can be used to add a new element to the end of a list my_list = [1, 2, 3] my_list[1] = my_list[0] + my_list[2] my_list[0] = my_list[1] + my_list[2] my_list[2] = my_list[0] + my_list[1] print(my_list) my_list = [1, 2, 3] my_list[1] = my_list[0] + my_list[2] my_list[0] = my_list[1] + my_list[2] my_list[2] = my_list[0] + my_list[1] print(my_list) CompSci Principles of Programming24 Give the output
Lists A list is a sequence of comma separated elements within square brackets. The elements of a list can be traversed using a for…in loop. The elements of a list can be changed using the index value. my_list = [2, 6, 3] b = 0 print("NOT changing list elements") for element in my_list: element = element + 2 b += element print("b:", b) print("my_list:", my_list) print("Changing list elements") for index in range(len(my_list)): my_list[index] = my_list[index] + index print("my_list:", my_list) my_list = [2, 6, 3] b = 0 print("NOT changing list elements") for element in my_list: element = element + 2 b += element print("b:", b) print("my_list:", my_list) print("Changing list elements") for index in range(len(my_list)): my_list[index] = my_list[index] + index print("my_list:", my_list) NOT changing list elements b:17 my_list:[2,6,3] Changing list elements my_list:[2,7,5] NOT changing list elements b:17 my_list:[2,6,3] Changing list elements my_list:[2,7,5] CompSci Principles of Programming25 Give the output
Sequences and for loops A string is a sequence. Each element of the string sequence (i.e., each character) can be accessed using a for loop: phrase = "Give it a go" count = 0 for letter in phrase: if letter in "aeiouAEIOU": count += 1 print("count", count) phrase = "Give it a go" count = 0 for letter in phrase: if letter in "aeiouAEIOU": count += 1 print("count", count) for item in sequence: indented_code_block CompSci Principles of Programming26
Split a string into a list of words The split() method splits a string into its parts. Default split (the delimiter) is white space (e.g., words.split()) Can use any other delimiters (e.g., words.split(", "), lines.split("\n")) lots_of_words = "Whether you think you can or you think you can't, you are right" my_list = lots_of_words.split() count = 0 for word in my_list: if len(word) == 3: count += 1 print("count: ", count) lots_of_words = "Whether you think you can or you think you can't, you are right" my_list = lots_of_words.split() count = 0 for word in my_list: if len(word) == 3: count += 1 print("count: ", count) Count: 7 CompSci Principles of Programming27
The test is worth 15% of your final mark, which covers the topics up to Lecture 15 (included). Date and Time: Tuesday 5th May 6:30pm - 7:45pm. Please bring your Student Id card, a pencil and an eraser. The test is a closed book test, so you cannot refer to any material during the test. Calculators are not permitted. Please arrive by 6:15pm as you will be given 5 minutes' reading time. The first part of the test is Multi-Choice Questions (2/3) and the second part of test is written questions (1/3). Please notify Angela Chang if you have a test clash. Test Next Week - Tuesday (5th May) 28CompSci Principles of Programming