Some text, some maths and going loopy. This is a fun chapter as we get to start real programming!

Similar documents
Figure 2. So it is very likely that the Babylonians attributed 60 units to each side of the hexagon. Its resulting perimeter would then be 360!

Chapter 3 Savings, Present Value and Ricardian Equivalence

The LCOE is defined as the energy price ($ per unit of energy output) for which the Net Present Value of the investment is zero.

est using the formula I = Prt, where I is the interest earned, P is the principal, r is the interest rate, and t is the time in years.

Symmetric polynomials and partitions Eugene Mukhin

The Binomial Distribution

AN IMPLEMENTATION OF BINARY AND FLOATING POINT CHROMOSOME REPRESENTATION IN GENETIC ALGORITHM

Episode 401: Newton s law of universal gravitation

How to create RAID 1 mirroring with a hard disk that already has data or an operating system on it

Skills Needed for Success in Calculus 1

Continuous Compounding and Annualization

BIOS American Megatrends Inc (AMI) v02.61 BIOS setup guide and manual for AM2/AM2+/AM3 motherboards

Module Availability at Regent s School of Drama, Film and Media Autumn 2016 and Spring 2017 *subject to change*

UNIT CIRCLE TRIGONOMETRY

Converting knowledge Into Practice

The Role of Gravity in Orbital Motion

Gravitation. AP Physics C

Left- and Right-Brain Preferences Profile

Problem Set # 9 Solutions

Do Vibrations Make Sound?

Quantity Formula Meaning of variables. 5 C 1 32 F 5 degrees Fahrenheit, 1 bh A 5 area, b 5 base, h 5 height. P 5 2l 1 2w

Semipartial (Part) and Partial Correlation

Ilona V. Tregub, ScD., Professor

CHAPTER 10 Aggregate Demand I

Questions & Answers Chapter 10 Software Reliability Prediction, Allocation and Demonstration Testing

Lab #7: Energy Conservation

How to create a default user profile in Windows 7

Definitions and terminology

Week 3-4: Permutations and Combinations

Database Management Systems

How to SYSPREP a Windows 7 Pro corporate PC setup so you can image it for use on future PCs

Valuation of Floating Rate Bonds 1

Experiment 6: Centripetal Force

Graphs of Equations. A coordinate system is a way to graphically show the relationship between 2 quantities.

A r. (Can you see that this just gives the formula we had above?)

Coordinate Systems L. M. Kalnins, March 2009

Open Economies. Chapter 32. A Macroeconomic Theory of the Open Economy. Basic Assumptions of a Macroeconomic Model of an Open Economy

How To Change V1 Programming

Voltage ( = Electric Potential )

Instituto Superior Técnico Av. Rovisco Pais, Lisboa virginia.infante@ist.utl.pt

Instructions to help you complete your enrollment form for HPHC's Medicare Supplemental Plan

Pipelined MIPS Processor. Dmitri Strukov ECE 154A

STUDENT RESPONSE TO ANNUITY FORMULA DERIVATION

Statistics and Data Analysis

1240 ev nm 2.5 ev. (4) r 2 or mv 2 = ke2

2 r2 θ = r2 t. (3.59) The equal area law is the statement that the term in parentheses,

Automatic Testing of Neighbor Discovery Protocol Based on FSM and TTCN*

Physics HSC Course Stage 6. Space. Part 1: Earth s gravitational field

Reduced Pattern Training Based on Task Decomposition Using Pattern Distributor

Lesson 7 Gauss s Law and Electric Fields

Gauss Law. Physics 231 Lecture 2-1

Financing Terms in the EOQ Model

PY1052 Problem Set 8 Autumn 2004 Solutions

Chapter 30: Magnetic Fields Due to Currents

2. TRIGONOMETRIC FUNCTIONS OF GENERAL ANGLES

FI3300 Corporate Finance

AMB111F Financial Maths Notes

Gravitational Mechanics of the Mars-Phobos System: Comparing Methods of Orbital Dynamics Modeling for Exploratory Mission Planning

CONCEPT OF TIME AND VALUE OFMONEY. Simple and Compound interest

Lecture 16: Color and Intensity. and he made him a coat of many colours. Genesis 37:3

Alarm transmission through Radio and GSM networks

SELF-INDUCTANCE AND INDUCTORS

Lab M4: The Torsional Pendulum and Moment of Inertia

PHYSICS 111 HOMEWORK SOLUTION #13. May 1, 2013

An Introduction to Omega

Displacement, Velocity And Acceleration

Review Graph based Online Store Review Spammer Detection

How Much Should a Firm Borrow. Effect of tax shields. Capital Structure Theory. Capital Structure & Corporate Taxes

Voltage ( = Electric Potential )

How to recover your Exchange 2003/2007 mailboxes and s if all you have available are your PRIV1.EDB and PRIV1.STM Information Store database

Problems of the 2 nd and 9 th International Physics Olympiads (Budapest, Hungary, 1968 and 1976)

Hitachi Virtual Storage Platform

Software Engineering and Development

A Comparative Analysis of Data Center Network Architectures

Effect of Contention Window on the Performance of IEEE WLANs

Chapter 1: Introduction BELSORP analysis program Required computer environment... 8

INITIAL MARGIN CALCULATION ON DERIVATIVE MARKETS OPTION VALUATION FORMULAS

F G r. Don't confuse G with g: "Big G" and "little g" are totally different things.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

VISCOSITY OF BIO-DIESEL FUELS

DOCTORATE DEGREE PROGRAMS

The force between electric charges. Comparing gravity and the interaction between charges. Coulomb s Law. Forces between two charges

ON THE (Q, R) POLICY IN PRODUCTION-INVENTORY SYSTEMS

How To Get A Tax Credit From Illinois

Supplementary Material for EpiDiff

Comparing Availability of Various Rack Power Redundancy Configurations

Anti-Lock Braking System Training Program

Spirotechnics! September 7, Amanda Zeringue, Michael Spannuth and Amanda Zeringue Dierential Geometry Project

Things to Remember. r Complete all of the sections on the Retirement Benefit Options form that apply to your request.

YARN PROPERTIES MEASUREMENT: AN OPTICAL APPROACH

Define What Type of Trader Are you?

A framework for the selection of enterprise resource planning (ERP) system based on fuzzy decision making methods

Transcription:

Chapte Two Some text, some maths and going loopy In this Chapte you ae going to: Lean how to do some moe with text. Get Python to do some maths fo you. Lean about how loops wok. Lean lots of useful opeatos. This is a fun chapte as we get to stat eal pogamming! Going loopy? I ve go that coveed! This wok is licensed unde the Ceative Commons Attibution-NonCommecial-ShaeAlike 3.0 Unpoted License. To view a copy of this license, visit http://ceativecommons.og/ licenses/by-nc-sa/3.0/ o send a lette to Ceative Commons, 444 Casto Steet, Suite 900, Mountain View, Califonia, 94041, USA.

Text Ty opening IDLE in inteactive mode and ente the text in Code Box 2. [ Code Box 2 ] If you have not pessed you ente key yet to see what happens, do so now. You should have discoveed \n has a special pupose. It is called an escape sequence. Table 1 shows some moe. Ty witing a vaiety of little pogams in IDLE using them and then in you own wods fill in the the ight-hand column. If you do not like witing in books you could use a pencil! escape sequence what they do \n \t \\ \ [ Table 1 escape sequences ] If you ae a bit confused about the last two, ty unning this code: pint( Hee is a speech mak: \ and hee is a slash: \\ ) [ Code Box 3 ] The backslash is used to escape chaactes that ae used in Python: When we want to pint some text to the sceen we wap it in speech maks. This means thee is a poblem if you want to type some speech maks. Well, now you know what to do about it put a backslash befoe it. So what do you do if you want to actually pint a backslash to the sceen? Put a backslash befoe it! l

Maths Using Python as a calculato is easy if you emembe two things. In compute pogamming, in almost all languages, the multiplication symbol is an asteisk and the division symbol is a fowad slash: [ figue 6 - some sums using Python ] W Thee is anothe way of dividing. If you use two fowad slashes instead of one, Python will poduce an intege as an answe. An intege is a whole numbe (a decimal such as 2.5 is called a float). You can now find the emainde with anothe mathematical opeato called modulus. This is epesented by a % sign. [ figue 7 - kinds of division ] It is also possible to combine text (o stings) and numbes like this: [ figue 8 - combining text and maths into output ] d Ooh Maths! i Ooh Text!

pint() is called a function (these ae coveed in chapte 4). What pint() will do, is pint anything you thow at it inside the backets. They must be sepaated by a comma, and stings (bits of text) must be put in speech maks. Eveything inside the backets will be pinted out in ode. The esults fom sums can also be output, but without putting the calculations in speech maks. What do you think would happen if you left in the speech maks? Don t foget you can also add in escape sequences. Coding Time It is time to ty you own code now. Just expeiment in inteactive mode. It might be an idea to see what happens if you put a maths sum in speech maks in a pint() statement. Hee ae some moe Maths opeatos: opeato name example answe * multiply 2*3 6 / divide (nomal) 20/8 2.5 // divide (intege) 20//8 2 % modulus 20%8 4 + add 2+3 5 - minus 7-3 4 [ Table 2 maths opeatos ] d (2 x 0) x (3 + 5) = 0 c

Going Loopy Computes ae geat at epetitive tasks. So ae humans but we get boed easily! Computes ae not only good at them, they ae fast! Theefoe we need to know how to tell them to do epeats. To do this we use a while loop. This uns some code while something is tue and stops when it becomes false. Suppose you wee tying to wite some code in a Histoy lesson at school when you should be doing Histoy. You teache might ask you to wite fifty lines. Well no matte, Python can do that. Ty opening IDLE in inteactive mode and then ente the text in Code Box 3. You will need to pess etun twice at the end. [ Code Box 3 ] Anothe solution to the same poblem is this: [ Code Box 4 ] TO DO: add a chaacte commenting: Wow, Python can multiply stings as well! The code in Box 4 is cleve look caefully to see what is happening. Howeve, although Code Box 4 was shote, a while loop is fa moe useful. It can do fa moe complex tasks. Fo example, with a while loop you can ask a compute to count to 100. Ty enteing this code and unning it: [ Code Box 5 ]

How While Loops Wok OK so how does this wok? To stat with we ceate a vaiable and assign a value to it. A vaiable is a space in the compute s memoy whee we can stoe, fo example, a sting o an intege. We ceate a vaiable by naming it. We called ou vaiable numbe and with the equals opeato we gave it the value 1 to look afte. Impotant The equals sign is used diffeently to the way it is used in maths. In computing the equals sign means: point this vaiable at this piece of data (an intege fo example). So numbe=1 says: ceate a vaiable called numbe and point it at the intege 1. Late we may point this name at anothe value. Howeve it may now only point at integes. The next line of code says while the vaiable called numbe is less than 101 do the following. All of the code that is indented afte the colon is what is to be epeatedly pefomed by the compute. That is, it loops though these two lines of code until numbe is no longe less than 101. The last line of code! numbe=numbe+1 I like to think of numbe=1 as meaning: make the vaiable called numbe equal to 1, fo now... is in the loop. It keeps adding 1 the vaiable called numbe fo each passage though the loop. Don t foget the vaiable s value can be changed with the equals opeato at any time. QZ [ figue 9 - A While Loop ]

Thee ae seveal opeatos you can use in a while loop. I have given you some of them in Table 2. Note how we now have anothe vesion of equals ==. This fom is moe like equals in maths. It is an example of a compaative opeato which ae sometimes called logical opeatos. Thefoe! while numbe==1: means while the vaiable called numbe is equal to 1, do the following. opeato meaning == equal to!= not equal to > geate than < less than >= geate than o equal to <= less than o equal to [ Table 3 logic opeatos ] We use a double equals sign to compae two values and a single equals sign to assign a value to a vaiable. y My husband woks fo a bus opeato in Coydon.

Chapte Two Summay In this chapte you have leant: 1. How to use the pint() statement 2. How to wite and un simple maths code 3. How to output a mixtue of stings, maths o numbes 4. How to wite a while loop Chapte Two - Fun Time You have leant a lot in this chapte. It is time you pactised. This will help you emembe what you have leant. Challenge 1 Wite some code in IDLE so that the compute counts up to 20 in twos. Yay! Fun B Challenge 2 Wite some code so that the the compute outputs the 5 times table like this: 1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 Hint: You will need a counte vaiable which you could call numbe. Figue out how to wite one line, then make you loop do it 10 times. Challenge 3 See if you can e-wite the code in Code Box 5 in thee diffeent ways. Each pogam should still poduce output which counts to a hunded. In you new code you ae not allowed to use the less than opeato <. Instead you should use one of these in each pogam: <= >!=