Lecture 20 – Test revision COMPSCI 101 Principles of Programming.

Slides:



Advertisements
Similar presentations
COMPSCI 101 Principles of Programming Lecture 6 – Getting user input, converting between types, generating random numbers.
Advertisements

COMPSCI 101 Principles of Programming Lecture 5 – Manipulating strings, String functions, dot notation.
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Structured programming
Introduction to Python
Python Crash Course by Monica Sweat. Python Perspective is strongly typed, interpreted language is used to define scripts (Don't even need to define a.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lecture 11 – if … else, if... elif statements, nested ifs COMPSCI 1 1 Principles of Programming.
Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.
Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming.
Introduction to Python
Programming for Linguists An Introduction to Python 24/11/2011.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CS1022 Computer Programming & Principles Lecture 1.2 A brief introduction to Python.
Introduction. 2COMPSCI Computer Science Fundamentals.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 5 Functions.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Input, Output, and Processing
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.
COMPSCI 101 Principles of Programming Lecture 4 –The type() function, the string type, the len() function, string slices.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Variables and Expressions CMSC 201 Chang (rev )
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Last Week if statement print statement input builtin function strings and methods for loop.
Repetition Structures Repetition Structures allow you to write programs that will repeat program steps multiple times. –Also called Loops –Counter controlled.
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
FUNCTIONS. Topics Introduction to Functions Defining and Calling a Void Function Designing a Program to Use Functions Local Variables Passing Arguments.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Lecture 15 – more on lists and for…in loops, the split() function COMPSCI 1 1 Principles of Programming.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
COP 2510 Chapter 6 - Functions. Random function (randint) #import the desired function import random #integer random number in the range of 1 through.
Variables, Types, Expressions Intro2CS – week 1b 1.
Trinity College Dublin, The University of Dublin GE3M25: Computer Programming for Biologists Python, Class 2 Karsten Hokamp, PhD Genetics TCD, 17/11/2015.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Introduction to Python Lesson 2a Print and Types.
Python unit_4 review Tue/Wed, Dec 1-2
COMPSCI 107 Computer Science Fundamentals
Topics Designing a Program Input, Processing, and Output
Topics Introduction to Functions Defining and Calling a Void Function
Topic: Iterative Statements – Part 1 -> for loop
CS1022 Computer Programming & Principles
Introduction to Python
COMPSCI 107 Computer Science Fundamentals
CS-104 Final Exam Review Victor Norman.
Introduction to Scripting
Arithmetic operations, decisions and looping
And now for something completely different . . .
An Introduction to Python
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
COMPUTER PROGRAMMING SKILLS
Class code for pythonroom.com cchsp2cs
Fundamentals of Python: First Programs Second Edition
Presentation transcript:

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