PROGRAMMING FUNDAMENTALS

Similar documents
PROGRAMMING FUNDAMENTALS

PROGRAMMING FUNDAMENTALS

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Python, Part 2 CS 8: Introduction to Computer Science Lecture #4

Python for Non-programmers

CS1 Lecture 4 Jan. 23, 2019

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Flow Control: Branches and loops

Programming in Python

Introduction to Python (All the Basic Stuff)

If Statements, For Loops, Functions

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Static Methods. Why use methods?

CMSC201 Computer Science I for Majors

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

CS1 Lecture 5 Jan. 25, 2019

Intro. Scheme Basics. scm> 5 5. scm>

CS 100: Computability, Python Lists

CMSC201 Computer Science I for Majors

Last time. Reasoning about programs. Coming up. Project Final Presentations. This Thursday, Nov 30: 4 th in-class exercise

Reasoning about programs

Built-in functions. You ve used several functions already. >>> len("atggtca") 7 >>> abs(-6) 6 >>> float("3.1415") >>>

CS1 Lecture 4 Jan. 24, 2018

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

(Python) Chapter 3: Repetition

Slide Set 1. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Difference Between Dates Case Study 2002 M. J. Clancy and M. C. Linn

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Chapter 11: Create Your Own Objects

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Unit E Step-by-Step: Programming with Python

Program development plan

Lecture 5 8/24/18. Writing larger programs. Comments. What are we going to cover today? Using Comments. Comments in Python. Writing larger programs

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Chapter 4: Conditionals and Recursion

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

The compiler is spewing error messages.

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

roboturtle Documentation

Implementing an Algorithm for Boomerang Fraction Sequences in Python

3 ADT Implementation in Java

Function Call Stack and Activation Records

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

Control Structures 1 / 17

PYTHON PROGRAMMING FOR ENGINEERS AND SCIENTISTS

Problem Solving for Intro to Computer Science

CS1 Lecture 5 Jan. 26, 2018

Implementing Continuations

COMS 469: Interactive Media II

Moodle 3.1 Backup and Restore

Fundamentals of Programming Session 13

COMP 250 Winter stacks Feb. 2, 2016

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

T H E I N T E R A C T I V E S H E L L

nostarch.com/pfk For bulk orders, please contact us at

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

142

Control Flow: Loop Statements

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Intro to Python & Programming. C-START Python PD Workshop

Iteration Part 1. Motivation for iteration. How does a for loop work? Execution model of a for loop. What is Iteration?

CS1 Lecture 3 Jan. 22, 2018

Intro. Speed V Growth

CS 106 Introduction to Computer Science I

CS Introduction to Programming Fall 2016

Text Input and Conditionals

FUNctions. Lecture 03 Spring 2018

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

COP 1220 Introduction to Programming in C++ Course Justification

Errors. And How to Handle Them

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

You Need an Interpreter! Comp Spring /28/08 L10 - An Interpreter

CMSC 201 Spring 2019 Lab 06 Lists

[CHAPTER] 1 INTRODUCTION 1

How to Think Like a Computer Scientist: Learning with Python 3»

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Fundamentals of Programming. Lecture 1: Introduction + Basic Building Blocks of Programming

DECOMPOSITION, ABSTRACTION, FUNCTIONS

Project 4: ATM Design and Implementation

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

CS1 Lecture 9 Feb. 5, 2018

Lecture Notes on Contracts

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

9.2 Linux Essentials Exam Objectives

At full speed with Python

Object Oriented Methods : Deeper Look Lecture Three

Writing and Running Programs

Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

CSE 374 Programming Concepts & Tools. Brandon Myers Winter 2015 Lecture 4 Shell Variables, More Shell Scripts (Thanks to Hal Perkins)

Intro to Python Programming

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

Flow Control. So Far: Writing simple statements that get executed one after another.

Transcription:

PROGRAMMING FUNDAMENTALS TESTING, MAIN, GLOBAL VARIABLES João Correia Lopes INESC TEC, FEUP 23 October 2018 FPRO/MIEIC/2018-19 23/10/2018 1 / 24

INTRODUCTION GOALS By the end of this class, the student should be able to: Understand and perform (simple) unit testing Understand the use of the function main() Understand the use of global variables FPRO/MIEIC/2018-19 23/10/2018 2 / 24

INTRODUCTION BIBLIOGRAPHY Brad Miller and David Ranum, Learning with Python: Interactive Edition. Based on material by Jeffrey Elkner, Allen B. Downey, and Chris Meyers (Section 6.7) [HTML] Peter Wentworth, Jeffrey Elkner, Allen B. Downey, and Chris Meyers, How to Think Like a Computer Scientist Learning with Python 3 (RLE), 2012 (Section 6.7) [HTML] Peter Wentworth, Jeffrey Elkner, Allen B. Downey, and Chris Meyers, How to Think Like a Computer Scientist Learning with Python 3, 2018 (Section 4.18) [PDF] FPRO/MIEIC/2018-19 23/10/2018 3 / 24

INTRODUCTION TIPS There s no slides: we use a script and some illustrations in the class. That is NOT a replacement for reading the bibliography listed in the class plan Students are responsible for anything that transpires during a class therefore if you re not in a class, you should get notes from someone else (not the instructor) David Mayer The best thing to do is to read carefully and understand the documentation published in the Content wiki (or else ask in the class) We will be using Moodle as the primary means of communication FPRO/MIEIC/2018-19 23/10/2018 4 / 24

INTRODUCTION CONTENTS 1 UNIT TESTING 2 USING A MAIN FUNCTION 3 TRICKS & TIPS 4 GLOBAL VARIABLES 5 COMPUTATIONAL THINKING 6 EXERCISES FPRO/MIEIC/2018-19 23/10/2018 5 / 24

UNIT TESTING 6.7. UNIT TESTING It is a common best practice in software development to include automatic unit testing of source code Unit testing provides a way to automatically verify that individual pieces of code, such as functions, are working properly This makes it possible to change the implementation of a function at a later time and quickly test that it still does what it was intended to do Unit testing also forces the programmer to think about the different cases that the function needs to handle Extra code in your program which is there because it makes debugging or testing easier is called scaffolding A collection of tests for some code is called its test suite FPRO/MIEIC/2018-19 23/10/2018 6 / 24

UNIT TESTING UNIT TESTS At this stage we re going to ignore what the Python community usually does (see Codeboard), and we re going to code two simple functions ourselves Then we ll use these for writing our unit tests and we ll apply a test suit to absolute_value() First we plan our tests (think carefully about the edge cases): 1 argument is negative 2 argument is positive 3 argument is zero FPRO/MIEIC/2018-19 23/10/2018 7 / 24

UNIT TESTING HELPER FUNCTION We re going to write a helper function for checking the results of one test. 1 import sys 2 3 def test(did_pass): 4 """ Print the result of a test. """ 5 linenum = sys._getframe(1).f_lineno # the caller s line number 6 if did_pass: 7 msg = "Test at line {0} ok.".format(linenum) 8 else: 9 msg = "Test at line {0} FAILED.".format(linenum) 10 print(msg) https://github.com/fpro-admin/lectures/blob/master/09/tests.py FPRO/MIEIC/2018-19 23/10/2018 8 / 24

UNIT TESTING TEST SUIT With the helper function written, we can proceed to construct our test suite: 1 def test_suite(): 2 """ 3 Run the suite of tests for code in this module (this file). 4 """ 5 test(absolute_value(17) == 17) 6 test(absolute_value(-17) == 17) 7 test(absolute_value(0) == 0) 8 test(absolute_value(3.14) == 3.14) 9 test(absolute_value(-3.14) == 3.14) 10 11 test_suite() # Here is the call to run the tests See it with the absolute_value(n) buggy version. https://github.com/fpro-admin/lectures/blob/master/09/tests.py FPRO/MIEIC/2018-19 23/10/2018 9 / 24

USING A MAIN FUNCTION USING A MAIN FUNCTION Using functions is a good idea It helps us to modularize our code by breaking a program into logical parts where each part is responsible for a specific task For example, remember the function called drawsquare() that was responsible for having some turtle draw a square of some size The actual turtle and the actual size of the square were defined to be provided as parameters These final five statements of the program perform the main processing that the program will do https://github.com/fpro-admin/lectures/blob/master/09/mainproc.py FPRO/MIEIC/2018-19 23/10/2018 10 / 24

USING A MAIN FUNCTION PROGRAM STRUCTURE Now our program structure is as follows 1 First, import any modules that will be required 2 Second, define any functions that will be needed 3 Third, define a main function that will get the process started 4 And finally, invoke the main function (which will in turn call the other functions as needed) In Python there is nothing special about the name main 1 1 We could have called this function anything we wanted. We chose main just to be consistent with some of the other languages. FPRO/MIEIC/2018-19 23/10/2018 11 / 24

USING A MAIN FUNCTION ADVANCED TOPIC Before the Python interpreter executes your program, it defines a few special variables One of those variables is called name and it is automatically set to the string value " main " when the program is being executed by itself in a standalone fashion On the other hand, if the program is being imported by another program, then the " main " variable is set to the name of that module This ability to conditionally execute our main function can be extremely useful when we are writing code that will potentially be used by others For example, if we ve a collection of functions to do some simple math... https://github.com/fpro-admin/lectures/blob/master/09/mymath.py https://github.com/fpro-admin/lectures/blob/master/09/import.py FPRO/MIEIC/2018-19 23/10/2018 12 / 24

USING A MAIN FUNCTION M A I N 1 #!/usr/bin/python3 2 # Filename: using_name.py 3 4 if name == " main ": 5 print("this program is being run by itself") 6 else: 7 print("i am being imported from another module") FPRO/MIEIC/2018-19 23/10/2018 13 / 24

TRICKS & TIPS TIP: NONE IS NOT A STRING Values like None, True and False are not strings: they are special values in Python Keywords are special in the language: they are part of the syntax So we cannot create our own variable or function with a name True we ll get a syntax error Built-in functions are not privileged like keywords: we can define our own variable or function called len, but we d be silly to do so! FPRO/MIEIC/2018-19 23/10/2018 14 / 24

TRICKS & TIPS TIP: UNDERSTAND WHAT THE FUNCTION NEEDS TO RETURN Perhaps functions return nothing some functions exists purely to perform actions, rather than to calculate and return a result (procedures) But if the function should return a value make sure all execution paths do return the value FPRO/MIEIC/2018-19 23/10/2018 15 / 24

TRICKS & TIPS TIP: USE PARAMETERS TO GENERALIZE FUNCTIONS Understand which parts of the function will be hard-coded and unchangeable, and which parts should become parameters so that they can be customized by the caller of the function FPRO/MIEIC/2018-19 23/10/2018 16 / 24

TRICKS & TIPS TIP: TRY TO RELATE PYTHON FUNCTIONS TO IDEAS WE ALREADY KNOW In math, we re familiar with functions like f(x) = 3x + 5 We already understand that when we call the function f(3) we make some association between the parameter x and the argument 3 Try to draw parallels to argument passing in Python FPRO/MIEIC/2018-19 23/10/2018 17 / 24

TRICKS & TIPS TIP: THINK ABOUT THE RETURN CONDITIONS OF THE FUNCTION Do I need to look at all elements in all cases? Can I shortcut and take an early exit? Under what conditions? When will I have to examine all the items in the list? https://github.com/fpro-admin/lectures/blob/master/09/manyodd.py FPRO/MIEIC/2018-19 23/10/2018 18 / 24

TRICKS & TIPS TIP: GENERALIZE YOUR USE OF BOOLEANS Mature programmers won t write if is_prime(n) == True: when they could say instead if is_prime(n): Like arithmetic expressions, booleans have their own set of operators (and, or, not) and values (True, False) and can be assigned to variables, put into lists, etc. FPRO/MIEIC/2018-19 23/10/2018 19 / 24

TRICKS & TIPS LOCAL VARIABLES Tip: Local variables do not survive when you exit the function Tip: Assignment in a function creates a local variable As soon as the function returns (whether from an explicit return statement or because Python reached the last statement), the stack frame and its local variables are all destroyed. FPRO/MIEIC/2018-19 23/10/2018 20 / 24

GLOBAL VARIABLES GLOBAL VARIABLES UNLESS it makes use of variables that are global 2 1 sz = 2 2 def h2(): 3 """ Draw the next step of a spiral on each call. """ 4 global sz 5 tess.turn(42) 6 tess.forward(sz) 7 sz += 1 Each time we call h2() it turns, draws, and increases the global variable sz 2 It s generally considered bad practice to use global variables. Functions should be as self-contained as possible (no side-effects). FPRO/MIEIC/2018-19 23/10/2018 21 / 24

BBC, Bitsize, FPRO/MIEIC/2018-19 Introduction to computational thinking 23/10/2018 22 / 24 COMPUTATIONAL THINKING COMPUTATIONAL THINKING Computational thinking allows us to take a complex problem, understand what the problem is and develop possible solutions. We can then present these solutions in a way that a computer, a human, or both, can understand.

COMPUTATIONAL THINKING USE COMPUTATIONAL THINKING (2) There are four key techniques (cornerstones) to computational thinking: DECOMPOSITION breaking down a complex problem or system into smaller, more manageable parts PATTERN RECOGNITION looking for similarities among and within problems 3 ABSTRACTION focusing on the important information only, ignoring irrelevant details 4 ALGORITHMS developing a step-by-step solution to the problem, or the rules to follow to solve the problem BBC, Bitsize, Introduction to computational thinking 3 Have any of the issues we ve encountered in the past had solutions that could apply here? 4 To make solutions as general as possible. FPRO/MIEIC/2018-19 23/10/2018 23 / 24

COMPUTATIONAL THINKING USE COMPUTATIONAL THINKING (2) There are four key techniques (cornerstones) to computational thinking: DECOMPOSITION breaking down a complex problem or system into smaller, more manageable parts PATTERN RECOGNITION looking for similarities among and within problems 3 ABSTRACTION focusing on the important information only, ignoring irrelevant details 4 ALGORITHMS developing a step-by-step solution to the problem, or the rules to follow to solve the problem BBC, Bitsize, Introduction to computational thinking 3 Have any of the issues we ve encountered in the past had solutions that could apply here? 4 To make solutions as general as possible. FPRO/MIEIC/2018-19 23/10/2018 23 / 24

COMPUTATIONAL THINKING USE COMPUTATIONAL THINKING (2) There are four key techniques (cornerstones) to computational thinking: DECOMPOSITION breaking down a complex problem or system into smaller, more manageable parts PATTERN RECOGNITION looking for similarities among and within problems 3 ABSTRACTION focusing on the important information only, ignoring irrelevant details 4 ALGORITHMS developing a step-by-step solution to the problem, or the rules to follow to solve the problem BBC, Bitsize, Introduction to computational thinking 3 Have any of the issues we ve encountered in the past had solutions that could apply here? 4 To make solutions as general as possible. FPRO/MIEIC/2018-19 23/10/2018 23 / 24

COMPUTATIONAL THINKING USE COMPUTATIONAL THINKING (2) There are four key techniques (cornerstones) to computational thinking: DECOMPOSITION breaking down a complex problem or system into smaller, more manageable parts PATTERN RECOGNITION looking for similarities among and within problems 3 ABSTRACTION focusing on the important information only, ignoring irrelevant details 4 ALGORITHMS developing a step-by-step solution to the problem, or the rules to follow to solve the problem BBC, Bitsize, Introduction to computational thinking 3 Have any of the issues we ve encountered in the past had solutions that could apply here? 4 To make solutions as general as possible. FPRO/MIEIC/2018-19 23/10/2018 23 / 24

COMPUTATIONAL THINKING USE COMPUTATIONAL THINKING (2) There are four key techniques (cornerstones) to computational thinking: DECOMPOSITION breaking down a complex problem or system into smaller, more manageable parts PATTERN RECOGNITION looking for similarities among and within problems 3 ABSTRACTION focusing on the important information only, ignoring irrelevant details 4 ALGORITHMS developing a step-by-step solution to the problem, or the rules to follow to solve the problem BBC, Bitsize, Introduction to computational thinking 3 Have any of the issues we ve encountered in the past had solutions that could apply here? 4 To make solutions as general as possible. FPRO/MIEIC/2018-19 23/10/2018 23 / 24

EXERCISES EXERCISES Moodle activity at: LE09: Testing, main and globals FPRO/MIEIC/2018-19 23/10/2018 24 / 24