Programming with Python

Similar documents
Python lab session 1

CMSC 201 Computer Science I for Majors

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

Chapter 2 Writing Simple Programs

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

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

CCBC Math 081 Order of Operations Section 1.7. Step 2: Exponents and Roots Simplify any numbers being raised to a power and any numbers under the

Variables, expressions and statements

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Decisions, Decisions. Testing, testing C H A P T E R 7

The Big Python Guide

ENGR 101 Engineering Design Workshop

Text Input and Conditionals

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

Variable and Data Type I

Jython. secondary. memory

Our Strategy for Learning Fortran 90

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Intermediate Algebra. Gregg Waterman Oregon Institute of Technology

If Statements, For Loops, Functions

Introduction to Programming. Dr Ben Dudson University of York

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

CS112 Lecture: Working with Numbers

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Bits and Bytes and Numbers

Variable and Data Type I

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Introduction to Programming in Turing. Input, Output, and Variables

Lecture 3. Input, Output and Data Types

Expressions and Variables

Basic Syntax - First Program 1

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

a b c d a b c d e 5 e 7

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

Fundamental of Programming (C)

Divisibility Rules and Their Explanations

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Module 01: Introduction to Programming in Python

Lesson 6: Manipulating Equations

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Variables, Expressions, and Statements

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

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

Section 1.1 Definitions and Properties

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 14

Math Day 2 Programming: How to make computers do math for you

cs1114 REVIEW of details test closed laptop period

Topic 2: Introduction to Programming

Signed umbers. Sign/Magnitude otation

Introduction to Python (All the Basic Stuff)

CSCE 110 Programming I

Variables and Constants

CSC 101: Lab Manual#9 Machine Language and the CPU (largely based on the work of Prof. William Turkett) Lab due date: 5:00pm, day after lab session

Introduction to: Computers & Programming: Review prior to 1 st Midterm

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Compilation and Execution Simplifying Fractions. Loops If Statements. Variables Operations Using Functions Errors

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Brainstorm. Period. Scientific Notation Activity 7 NOTES

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Representing numbers on the computer. Computer memory/processors consist of items that exist in one of two possible states (binary states).

Variables and Data Representation

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

SOEE1160: Computers and Programming in Geosciences Semester /08. Dr. Sebastian Rost

MITOCW watch?v=se4p7ivcune

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

And Parallelism. Parallelism in Prolog. OR Parallelism

Shorthand for values: variables

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Python Unit

Algebra 2 Common Core Summer Skills Packet

CITS2401 Computer Analysis & Visualisation

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Lecture 1. Types, Expressions, & Variables

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

The Very Basics of the R Interpreter

6.001 Notes: Section 8.1

The current topic: Python. Announcements. Python. Python

PROGRAMMING FUNDAMENTALS

Section A Arithmetic ( 5) Exercise A

Topic Notes: Bits and Bytes and Numbers

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

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

Programming Fundamentals and Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

MA 1128: Lecture 02 1/22/2018

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Programming. Dr Ben Dudson University of York

How to approach a computational problem

Introduction to TURING

Introduction to Programming with JES

Transcription:

Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2 (1 of 35)

From last time... Last time we looked at problem solving, and methods for thinking up algorithms Understanding a problem Breaking it up into smaller problems Working out a set of steps to follow (recipe / algorithm) Using flow diagrams to express algorithms This lecture, we ll start looking at programming, and the Python language Dr Ben Dudson Introduction to Programming - Lecture 2 (2 of 35)

Programming Last lecture we looked at problem solving, and writing algorithms (instructions) as flow charts. % mark < 0 or > 100? no > 70? yes A grade yes no Error > 40? yes B grade no C grade Dr Ben Dudson Introduction to Programming - Lecture 2 (3 of 35)

Programming Last lecture we looked at problem solving, and writing algorithms (instructions) as flow charts. The actual computer hardware (CPU) needs instructions in numerical codes which are very hard for humans to write, and even harder to read. 83 C0 01 A3 88 03 06 08 FF 14 85 90 Dr Ben Dudson Introduction to Programming - Lecture 2 (3 of 35)

Programming Last lecture we looked at problem solving, and writing algorithms (instructions) as flow charts. The actual computer hardware (CPU) needs instructions in numerical codes which are very hard for humans to write, and even harder to read. 83 C0 01 A3 88 03 06 08 FF 14 85 90 Instead, people have designed many different ways to express algorithms which can be understood by the computer Dr Ben Dudson Introduction to Programming - Lecture 2 (3 of 35)

Programming Last lecture we looked at problem solving, and writing algorithms (instructions) as flow charts. The actual computer hardware (CPU) needs instructions in numerical codes which are very hard for humans to write, and even harder to read. 83 C0 01 A3 88 03 06 08 FF 14 85 90 Instead, people have designed many different ways to express algorithms which can be understood by the computer The best way to explain algorithms to computers has been found to be writing commands in plain text Languages which are readable to humans, but can be automatically converted into machine instructions Many many different ones around. Evolve over time, but use many of the same ideas Dr Ben Dudson Introduction to Programming - Lecture 2 (3 of 35)

Python programming language Python is a relatively new language (1991, major update 2008) Intended to be clear and easy to start using, but at the same time very powerful for experienced users Widely used as it allows quicker development compared to more traditional languages (e.g. C or Fortran) Becoming quite common in scientific programming Freely available, open source. You can download and install a copy at home, on your laptop etc. Dr Ben Dudson Introduction to Programming - Lecture 2 (4 of 35)

Variables We saw in the last lecture that we give quantities names like x, A etc. These are like variables (x, y, z) in mathematics, but with one crucial difference In maths, once you write x = 2, the value is fixed. In (most) programming languages, the value of variables can be changed Dr Ben Dudson Introduction to Programming - Lecture 2 (5 of 35)

Variables We saw in the last lecture that we give quantities names like x, A etc. These are like variables (x, y, z) in mathematics, but with one crucial difference In maths, once you write x = 2, the value is fixed. In (most) programming languages, the value of variables can be changed This is why it makes sense in Python to write i = i + 1 In mathematics this makes no sense, but in programming what it means is Calculate i + 1, then set i to this new value, or if you prefer Set i to the old i + 1 i i + 1 Dr Ben Dudson Introduction to Programming - Lecture 2 (5 of 35)

Variable names Variable names in programs can be just single characters like x or i, but usually it s better to make them more descriptive This helps make your program easier to understand: it s easier to guess what height represents than h. Names must start with a letter or underscore, and be a combination of letters, numbers, and underscores Dr Ben Dudson Introduction to Programming - Lecture 2 (6 of 35)

Variable names Variable names in programs can be just single characters like x or i, but usually it s better to make them more descriptive This helps make your program easier to understand: it s easier to guess what height represents than h. Names must start with a letter or underscore, and be a combination of letters, numbers, and underscores Exercise: Which of these can be used as variable names? 1 position 2 2ndValue 3 mark% 4 mark percentage 5 my variable 6 studentmark Dr Ben Dudson Introduction to Programming - Lecture 2 (6 of 35)

Variable names Variable names in programs can be just single characters like x or i, but usually it s better to make them more descriptive This helps make your program easier to understand: it s easier to guess what height represents than h. Names must start with a letter or underscore, and be a combination of letters, numbers, and underscores Exercise: Which of these can be used as variable names? 1 position Yes 2 2ndValue No - starts with a number 3 mark% No - not allowed % symbol 4 mark percentage Yes 5 my variable No - Not allowed minus symbol 6 studentmark Yes Dr Ben Dudson Introduction to Programming - Lecture 2 (6 of 35)

Variable names Some words have special meaning in Python, so can t be used as variable names. Reserved words: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, with, while, and yield Dr Ben Dudson Introduction to Programming - Lecture 2 (7 of 35)

Variable names This applies to all names in Python, so that these variables are all different myvariable MyVariable myvariable myvariable Dr Ben Dudson Introduction to Programming - Lecture 2 (7 of 35) Some words have special meaning in Python, so can t be used as variable names. Reserved words: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, with, while, and yield Another important thing to remember is Python is case sensitive, meaning that it treats upper case (A,B,C,...) as different characters to lower case (a,b,c,...)

Calculations The basic operations in Python are Power A B A B Multiply A B A B Divide A / B A/B Add A + B A + B Subtract A B A B Operations higher up the list (e.g. power) are done before those lower down (e.g. add). This is called operator precedence. Dr Ben Dudson Introduction to Programming - Lecture 2 (8 of 35)

Calculations The basic operations in Python are Power A B A B Multiply A B A B Divide A / B A/B Add A + B A + B Subtract A B A B Operations higher up the list (e.g. power) are done before those lower down (e.g. add). This is called operator precedence. Exercise: What is the result of 2 3 2 4 (a) 32 (b) 10 (c) 14 (d) 2/9 Dr Ben Dudson Introduction to Programming - Lecture 2 (8 of 35)

Calculations The basic operations in Python are Power A B A B Multiply A B A B Divide A / B A/B Add A + B A + B Subtract A B A B Operations higher up the list (e.g. power) are done before those lower down (e.g. add). This is called operator precedence. Exercise: What is the result of 2 3 2 4 (a) 32 (b) 10 (c) 14 (d) 2/9 Python interprets this as (2 (3 2)) 4 Dr Ben Dudson Introduction to Programming - Lecture 2 (8 of 35)

Precedence and brackets Exercise: How do you write the following? f = 1 x + 1 g = 1 x + 1 which one is 1/x+1? Dr Ben Dudson Introduction to Programming - Lecture 2 (9 of 35)

Precedence and brackets Exercise: How do you write the following? f = 1 x + 1 g = 1 x + 1 which one is 1/x+1? Divide (/) has a higher precedence than add (+), so the computer reads this as g = (1/ x)+1 Dr Ben Dudson Introduction to Programming - Lecture 2 (9 of 35)

Precedence and brackets Exercise: How do you write the following? f = 1 x + 1 g = 1 x + 1 which one is 1/x+1? Divide (/) has a higher precedence than add (+), so the computer reads this as g = (1/ x)+1 If you want to change this, use brackets to tell the computer which calculations to do first f = 1/( x+1) Dr Ben Dudson Introduction to Programming - Lecture 2 (9 of 35)

Precedence and brackets What about h = 1 2x + 1? Can we write this as h = 1/2 x+1 Dr Ben Dudson Introduction to Programming - Lecture 2 (10 of 35)

Precedence and brackets What about h = 1 2x + 1? Can we write this as h = 1/2 x+1 No: The computer goes through this as before, but here the divide and multiply have the same precedence. In this case, the computer does the operations from left to right so interprets this as h = (1/2) x+1 i.e. h = 1 2 x + 1 Dr Ben Dudson Introduction to Programming - Lecture 2 (10 of 35)

Precedence and brackets What about h = 1 2x + 1? Can we write this as h = 1/2 x+1 No: The computer goes through this as before, but here the divide and multiply have the same precedence. In this case, the computer does the operations from left to right so interprets this as h = (1/2) x+1 i.e. h = 1 2 x + 1 What we want is to first multiply 2 by x, so put that in brackets h = 1/(2 x)+1 Highest precedence operations done first: ** then *,/ then +,-. If the same precedence, then goes from left to right. If in doubt, put brackets around it Dr Ben Dudson Introduction to Programming - Lecture 2 (10 of 35)

Scientific notation How do we represent very large or small numbers? For example, mass of the sun (in kg) m S = 1.98892 10 30 Dr Ben Dudson Introduction to Programming - Lecture 2 (11 of 35)

Scientific notation How do we represent very large or small numbers? For example, mass of the sun (in kg) m S = 1.98892 10 30 how about? mass = 1.98892 10 30 Dr Ben Dudson Introduction to Programming - Lecture 2 (11 of 35)

Scientific notation How do we represent very large or small numbers? For example, mass of the sun (in kg) how about? mass = 1.98892 m S = 1.98892 10 30 10 30 This will (probably) give the correct answer, but is very inefficient: it s telling the computer to do a calculation, rather than giving it a number. Instead, programming languages use e notation mass = 1.98892 e30 where the e stands for exponent or times ten to the Dr Ben Dudson Introduction to Programming - Lecture 2 (11 of 35)

Handling numbers The way computers handle numbers is mostly quite straightforward, but has some quirks. Why for instance does p r i n t 7/2 produce the answer 3? Dr Ben Dudson Introduction to Programming - Lecture 2 (12 of 35)

Handling numbers The way computers handle numbers is mostly quite straightforward, but has some quirks. Why for instance does p r i n t 7/2 produce the answer 3? This is because 7 and 2 are integers, whole numbers, and so the result of the calculation is also an integer. In computing, integers are handled very differently to numbers like 3.1415 or 2.7 which are called floating point numbers or floats I can t believe you ve done this! Why?? Dr Ben Dudson Introduction to Programming - Lecture 2 (12 of 35)

Floating point numbers Why are integers different to floating point numbers? In a computer, all calculations are done in chunks of a fixed number of bits, usually 32 or 64 bits This means that in a single calculation a 32-bit computer can efficiently handle numbers up to 2 32 (about 4 billion) This is accurate, but is also limited to whole numbers. If we want to deal with very large or non-whole numbers then we can t use integers Dr Ben Dudson Introduction to Programming - Lecture 2 (13 of 35)

Floating point numbers The solution is to use some of those 32 bits to store the digits and the exponent separately 9.109381 }{{} 10 }{{} 31 digits exponent The downside is that we lose precision: we can only store about 6 or 7 significant places rather than 9 in an integer Dr Ben Dudson Introduction to Programming - Lecture 2 (14 of 35)

Floating point numbers The solution is to use some of those 32 bits to store the digits and the exponent separately 9.109381 }{{} 10 }{{} 31 digits exponent The downside is that we lose precision: we can only store about 6 or 7 significant places rather than 9 in an integer The result is that how integers and floats are represented is quite different. For example, the number 40 is Integer 0000 0000 0000 0000 0000 0000 0010 1000 Float 0100 0010 0010 0000 0000 0000 0000 0000 The electronic circuits which deal with floats are therefore different to those for integers Dr Ben Dudson Introduction to Programming - Lecture 2 (14 of 35)

Floating point numbers Most of the time you won t need to care about how this works: Python takes care of all this stuff for you. Some things to keep in mind though: If you want 7/2 to give 3.5 then make sure Python knows the numbers are floats not integers by adding a decimal point: 7./2. 3.5 Exercise: What do you think the result of this is: v a l u e = 1. 0 e12 v a l u e = v a l u e + 1. 0 Dr Ben Dudson Introduction to Programming - Lecture 2 (15 of 35)

Floating point numbers Most of the time you won t need to care about how this works: Python takes care of all this stuff for you. Some things to keep in mind though: If you want 7/2 to give 3.5 then make sure Python knows the numbers are floats not integers by adding a decimal point: 7./2. 3.5 Exercise: What do you think the result of this is: v a l u e = 1. 0 e12 v a l u e = v a l u e + 1. 0 Should get 1 trillion and 1, but actually get just 1 trillion. Adding 1 has no effect! This is because float can t store enough digits so can t store 1.000000000001e12 Dr Ben Dudson Introduction to Programming - Lecture 2 (15 of 35)

Outputting results Of course there s no point doing calculations without a way to tell anyone the result. To output a result, Python has the print command h = 2 p r i n t h Dr Ben Dudson Introduction to Programming - Lecture 2 (16 of 35)

Outputting results Of course there s no point doing calculations without a way to tell anyone the result. To output a result, Python has the print command h = 2 p r i n t h Why print? Nothing is coming out the printer... Dr Ben Dudson Introduction to Programming - Lecture 2 (16 of 35)

Outputting results Of course there s no point doing calculations without a way to tell anyone the result. To output a result, Python has the print command h = 2 p r i n t h Why print? Nothing is coming out the printer... Historical reasons: now on screen rather than printer Dr Ben Dudson Introduction to Programming - Lecture 2 (16 of 35)

Outputting results When printing out results, it s good to add some text to explain what the numbers mean and what your program is doing. In Python, text is put in quotation marks, either like this, or like this. As is traditional, printing Hello, World! is done using p r i n t Hello, World! You can print several things out at the same time by separating them with commas p r i n t The v a l u e h i s :, h Dr Ben Dudson Introduction to Programming - Lecture 2 (17 of 35)

Outputting results When printing out results, it s good to add some text to explain what the numbers mean and what your program is doing. In Python, text is put in quotation marks, either like this, or like this. As is traditional, printing Hello, World! is done using p r i n t Hello, World! You can print several things out at the same time by separating them with commas p r i n t The v a l u e h i s :, h Chunks of text in programming are called strings, and they can be treated like variables too s = The v a l u e h i s : p r i n t s, h These strings can be searched through, chopped up, and combined together. More on this later in the course... Dr Ben Dudson Introduction to Programming - Lecture 2 (17 of 35)

Getting input To get values from the user, Python has the input function (we ll come back to what functions are next time) x = i n p u t ( Enter x : ) h = 1. / ( 2. x )+1. p r i n t h This asks the user for x, calculates h and prints it out. Enter x: Dr Ben Dudson Introduction to Programming - Lecture 2 (18 of 35)

Getting input To get values from the user, Python has the input function (we ll come back to what functions are next time) x = i n p u t ( Enter x : ) h = 1. / ( 2. x )+1. p r i n t h This asks the user for x, calculates h and prints it out. Enter x:2 1.25 Dr Ben Dudson Introduction to Programming - Lecture 2 (19 of 35)

Case sensitive revisited As with variable names, Python commands are case sensitive. Therefore, although P r i n t h looks fine to a human, but to Python it s incomprehensible. Dr Ben Dudson Introduction to Programming - Lecture 2 (20 of 35)

Case sensitive revisited As with variable names, Python commands are case sensitive. Therefore, although P r i n t h looks fine to a human, but to Python it s incomprehensible. Humans are very good at seeing patterns and filling in gaps. Computers are still very bad at these things so need precise input. In programming you have to be very picky about small details. Even a little misplaced comma or capital letter can break your program When something like this happens, the computer will try to help and tell you where it thinks the mistake is. Often some detective work is needed. Dr Ben Dudson Introduction to Programming - Lecture 2 (20 of 35)

Making decisions One of the important things we want an algorithm to do is make decisions Yes Is A > 6? A greater than 6 No A less than or equal to 6 Dr Ben Dudson Introduction to Programming - Lecture 2 (21 of 35)

Making decisions One of the important things we want an algorithm to do is make decisions Yes Is A > 6? A greater than 6 No A less than or equal to 6 In Python, this is done using if clauses i f A > 6 : p r i n t A i s g r e a t e r than 6 e l s e : p r i n t A i s l e s s than or e q u a l to 6 Dr Ben Dudson Introduction to Programming - Lecture 2 (21 of 35)

Making decisions The format is i f c o n d i t i o n : commands e l s e : commands where condition is what you want to test, and commands is one or more lines of commands, called a code block. For example i f A > 6 : B = 2 p r i n t Got spam e l s e : B = 2 p r i n t Got eggs Dr Ben Dudson Introduction to Programming - Lecture 2 (22 of 35)

Making decisions The format is i f c o n d i t i o n : commands e l s e : commands where condition is what you want to test, and commands is one or more lines of commands, called a code block. Most important: Note that the code blocks are indented Indentation is crucial in Python, and is how it knows where blocks start and end Dr Ben Dudson Introduction to Programming - Lecture 2 (23 of 35)

Making decisions Exercise: Draw the flow diagram for the following Python code i f A > 0 : p r i n t p o s i t i v e i f A > 100: p r i n t Over 100 e l s e : p r i n t L e s s than or e q u a l to 100 e l s e : p r i n t L e s s than or e q u a l to z e r o Dr Ben Dudson Introduction to Programming - Lecture 2 (24 of 35)

Making decisions Exercise: Draw the flow diagram for the following Python code i f A > 0 : p r i n t p o s i t i v e i f A > 100: p r i n t Over 100 e l s e : p r i n t L e s s than or e q u a l to 100 e l s e : p r i n t L e s s than or e q u a l to z e r o A > 0? Yes Positive Yes A > 100? Over 100 No No Less than or equal to zero Less than or equal to 100 Dr Ben Dudson Introduction to Programming - Lecture 2 (24 of 35)

More complicated decisions So far we ve only used > to test if one number is greater than another. You can use the following comparisons A greater than B A less than B A greater than or equal to B A less than or equal to B A equal to B A > B A < B A >= B A <= B A == B A = B sets A equal to B, but A == B tests if A is equal to B Dr Ben Dudson Introduction to Programming - Lecture 2 (25 of 35)

More complicated decisions What about our original percentage to grade problem? % mark < 0 or > 100? no > 70? yes A grade yes no Error > 40? yes B grade no C grade Dr Ben Dudson Introduction to Programming - Lecture 2 (26 of 35)

More complicated decisions In Python, this can be written as m = i n p u t ( Enter p e r c e n t a g e mark : ) i f m < 0 or m > 100: p r i n t E r r o r e x i t ( ) i f m > 7 0 : p r i n t A e l s e : i f m > 4 0 : p r i n t B e l s e : p r i n t C Note that if doesn t need an else - you can just miss it out Also you can combine tests using and, or and not Dr Ben Dudson Introduction to Programming - Lecture 2 (27 of 35)

More complicated decisions A shorthand way to check for several possibilities is to use elif instead of else and if m = i n p u t ( Enter p e r c e n t a g e mark : ) i f m < 0 or m > 100: p r i n t E r r o r e x i t ( ) i f m > 7 0 : p r i n t A e l i f m > 4 0 : p r i n t B e l s e : p r i n t C Dr Ben Dudson Introduction to Programming - Lecture 2 (28 of 35)

Going around in circles Another common task we want is to be able to repeat commands while some condition is true. Dr Ben Dudson Introduction to Programming - Lecture 2 (29 of 35)

Going around in circles Another common task we want is to be able to repeat commands while some condition is true. From last time: find the lowest number m in a list of N numbers Result Xm Yes Input X1... XN i = 1, m = 1 i = N? No i = i + 1 m = i Yes Xi < Xm? No Dr Ben Dudson Introduction to Programming - Lecture 2 (29 of 35)

Going around in circles Another common task we want is to be able to repeat commands while some condition is true. From last time: find the lowest number m in a list of N numbers Input X1... XN i = 1, m = 1 Result Xm Yes i = N? m = i No Yes i = i + 1 Xi < Xm? i = 0 m = 0 while i < N: i = i + 1 i f X[ i ] < X[m] : m = i p r i n t Min i s, X[m] No Dr Ben Dudson Introduction to Programming - Lecture 2 (30 of 35)

Going around in circles A few new things in this example i = 0 m = 0 while i < N: i = i + 1 i f X[ i ] < X[m] : m = i p r i n t Min i s, X[m] while repeats the commands in its block (indented) as long as its condition is true. In this case, keeps going until i is equal to N In programming, lists of numbers X 1... X N called arrays can be used. X 1 is written X[1] so X m is X[m] In Python, arrays start from 0, so in an array of N numbers, the first one is X[0] and the last is X[N 1] Dr Ben Dudson Introduction to Programming - Lecture 2 (31 of 35)

Going around in circles Exercise: Try writing down the Python code for this loop which calculates the factorial N! of a number N Input N R = 1 N > 1? Yes R = R N, N = N 1 No Output R Dr Ben Dudson Introduction to Programming - Lecture 2 (32 of 35)

Going around in circles Exercise: Try writing down the Python code for this loop which calculates the factorial N! of a number N Input N R = 1 N > 1? Yes R = R N, N = N 1 No Output R N = i n p u t ( Enter N: ) R = 1 while N > 1 : R = R N N = N 1 p r i n t R e s u l t i s, R Dr Ben Dudson Introduction to Programming - Lecture 2 (32 of 35)

More advanced topics We have covered the most basic parts of programming, and almost everything can be written with just if and while blocks For bigger programs though this would become very unwieldy, slow to write and difficult to understand Dr Ben Dudson Introduction to Programming - Lecture 2 (33 of 35)

More advanced topics We have covered the most basic parts of programming, and almost everything can be written with just if and while blocks For bigger programs though this would become very unwieldy, slow to write and difficult to understand There are many more abstract ideas in programming, most of which are ways to handle increasingly complicated programs In this course we won t be able to cover all of them, but you will come across some of the more common ones Next time (lab 1): more loops, lists, arrays, and functions Dr Ben Dudson Introduction to Programming - Lecture 2 (33 of 35)

Summary Python is an efficient way to express algorithms, easy to read but also a proper language Dr Ben Dudson Introduction to Programming - Lecture 2 (34 of 35)

Summary Python is an efficient way to express algorithms, easy to read but also a proper language Programming languages have some quirks due to how computers work Dr Ben Dudson Introduction to Programming - Lecture 2 (34 of 35)

Summary Python is an efficient way to express algorithms, easy to read but also a proper language Programming languages have some quirks due to how computers work Computers are very picky about small details such as punctuation (commas, colons etc.) and upper vs. lower case Dr Ben Dudson Introduction to Programming - Lecture 2 (34 of 35)

Summary Python is an efficient way to express algorithms, easy to read but also a proper language Programming languages have some quirks due to how computers work Computers are very picky about small details such as punctuation (commas, colons etc.) and upper vs. lower case Python is particularly picky about indentation: changes in indentation mark the beginning and end of blocks of code Dr Ben Dudson Introduction to Programming - Lecture 2 (34 of 35)

Summary Python is an efficient way to express algorithms, easy to read but also a proper language Programming languages have some quirks due to how computers work Computers are very picky about small details such as punctuation (commas, colons etc.) and upper vs. lower case Python is particularly picky about indentation: changes in indentation mark the beginning and end of blocks of code See the blue boxes in the slides for the most important things to watch out for Dr Ben Dudson Introduction to Programming - Lecture 2 (34 of 35)

Enough! http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2 (35 of 35)