Week 1 Introduction To Programming And Python

1y ago
17 Views
3 Downloads
3.44 MB
56 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Azalea Piercy
Transcription

ENGG1811 Computing for EngineersWeek 1Introduction to Programmingand PythonENGG1811 UNSW, CRICOS Provider No: 00098GW4

Computers have changed engineering http://www.noendexport.com/en/contents/48/410.html

Computers have changed engineering

How computing is used in engineering? Automation is a major application of computing inengineering– There are many other applications of computing in engineering.More to come.– Message: Computing will play a key role in addressing grandchallenges in engineering, e.g. aging infrastructure, etc.– http://www.engineeringchallenges.org Automation: Computers/machines repeatedly performingthe same procedure– Procedure: a sequence of instructions

Problem solving Engineering: invention, problem solving, Problem solving requires you to understand howthings work, test out ideas etc. How can you use computers to solve problems foryou?– How can you use computers to understand, investigate,test and design?– A key idea is abstraction. You can use the samecomputing method to count the number of heart beats,the breathing rate, number of walking steps

Programming If you come out with a method for thecomputer to solve a problem, you need to beable to tell the computer how to do it.– You need to give instructions to computers Programming skill: The ability to giveinstructions to computers to perform theintended tasksENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 6

A role-play game We will play a game on giving instructions We need a volunteer or two volunteersworking together The lecturer will give you the instructions ofthis gameENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 7

Python Python will be the programming language that youwill use to learn how to give instructions tocomputers It is a popular programming language and itcomes with a lot of extra packages that help youto do engineering work There are two versions of Python. We will beusing Python 3, not Python 2.ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 8

Spyder We will use a program called Spyder to develop,test and run Python programs Spyder is available on all UNSW CSE computers You will also use Spyder in the lab If you want to use Spyder on your computer, youroptions are:– Install Anaconda on your computer– Use the UNSW CSE computers remotely. Thisrequires Internet access.– More details on the course websiteENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 9

The Spyder EnvironmentButtonsEditor for developingPython programsENGG1811iPython Console‘i’ is short for interactive UNSW, CRICOS Provider No: 00098GW4 slide 10

Using the iPython Console We will simply call it the console You can use the console to do some simpleprogramming You do that by typing commands at the prompt– Commands are instructions to tell the computers to dosomethingThepromptENGG1811You type the command at the blinking cursor. Afteryou’ve finished typing, use the Enter key to tell theconsole to execute the commands. UNSW, CRICOS Provider No: 00098GW4 slide 11

If you haven’t got Spyder yet, You can use iPython Console online at:– https://www.pythonanywhere.com/try-ipython/– https://trinket.io/console We will only be using iPython Console today butwe will use the editor from tomorrow. So make sureyou install Anaconda before that.– Instructions on installing Anaconda for Python 3.6 can befound under Resources on the course websiteENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 12

Using console to do arithmetic Type 3 4 at the console, as follows: And then type the Enter key The computer execute the instruction, whichis to add 3 and 4 The console returns the answerENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 13

Arithmetic Operators in PythonOperator Addition or unary plus–Subtraction or unary minus*Multiplication/Floating point division//%**ENGG1811DescriptionInteger division (fraction discarded)Integer modulus (remainder)Exponentiation (power) UNSW, CRICOS Provider No: 00098GW4 slide 14

Exercises: Type the following at the prompt and thenexecute the command, observe what you getand try to understand the meaning of thearithmetic operators2*42 ** 410 / 710 // 710 % 710 - -7ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 15

Unary and binary operations and – can be unary or binary For example,10 - -7Binary minus Subtract 2 numbersENGG1811 UNSW, CRICOS Provider No: 00098GUnary minus Negative signW4 slide 16

Precedence You can use the arithmetic operators to calculatecomplicated expressions You can type: 1 2 * 3 – 4– Should this be 3 or 5? The computers evaluate arithmetic expressionsaccording to the rule of precedenceENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 17

Precedence When evaluating arithmetic expressions, order ofevaluating operations determined by precedenceHigher precedenceOperator( )** – (unary: sign)* / % // - (binary)Lower precedence You do not need to memorise this. Look it up when youneed. We will give this to you in the exam.ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 18

Evaluating Expressions –Rules of Precedence When evaluating expressions, operations ofhigher precedence are performed before thoseof lower precedence2 3 * 4 2 (3 * 4) 14 Otherwise operations performed from left toright2 ** 3 ** 4 (2 ** 3)** 4 409630 // 4 % 2 (30 // 4) % 2 7 % 2 1 Use parentheses if in any doubtENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 19

Quiz: You want to calculate: Which one can you not use?a) 20 / 5 / 2b) 20 / 5 * 2c) 20 / (5 * 2)ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 20

Quiz What is -2**2 in Python?a) 4b) -4i.e. (-2)**2i.e. –(2**2)Higher precedenceOperator( )** – (unary: sign)* / % // - (binary)ENGG1811Lower precedence UNSW, CRICOS Provider No: 00098GW4 slide 21

An exception to the rule If a unary – or is to the right of **, then theunary is evaluated first 10**-2 0.01ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 22

Variables and the assignment operator Type the following at the prompt and enter You can use y again to do computation We say we assign thevalue of 5 to thevariable named y We call theassignment operator Each input you type inis a Python statementENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 23

Programming element: Variables Variables are stored in computer memory A variable has a name and a value A mental picture is:yVariable name5Value of variableA program manipulates variables to achieve its goalNote: This is a simplified view. We will introduce themore accurate view later in the course.ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 24

Expressions of variables You can combine variables in an expression Try this in the console:Old value of thevariable d isoverwrittenENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 25

Execution of arithmetic expressionsName of variables Variables arestored inmemoryd Value of variablesbcd2510c ** b1. Look up the value of c and b2. Compute c to the power of b3. Store the result in the memory for dENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 26

Assignment errorsYou must assign avalue to a variablebefore using itOrder is important.Destination sourceENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 27

Variable names are case sensitive / debugging You should read the error message and try to understand what it meansso that you can fix your own code later on– Programmers use the term debugging to mean fixing the code. See below fora discussion on the origin of the term and a picture of the moth whichapparently stopped a computer program from its execution– https://en.wikipedia.org/wiki/Debugging Don’t get upset if you get bugs in your code. It’s a fact of life in computerprogramming. What is important is you learn how to debug.ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 28

Don’t interpret assignment as equal sign In mathematics, the expression x x 10 is acontradiction In computer programming, is the assignmentoperator, so x x 10 means the followingoperationsTake the value of the variable x(which is 7), add 10 to it andassign the result (which is 17)to the variable xENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 29

Quiz What is the value of the variable x afterexecuting the following statements?x 10x x 2x x 2x x 2ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 30

Try yourselves You can also try thesex 10x x*xx x%3x 2 / (x 7)ENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 31

Numbers and text Computers can handle numbers– Engineering data are often in numbers– Data processing is important in Engineering– Numbers can also be used to represent Images: Photos, X-ray images, medical images Videos, music, speeches etc. Computers can also handle text– Data can also be in textENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 32

Strings In Python, text is represented as strings Strings are always enclosed within a pair ofmatching single quotes or double quotesENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 33

Strings: examples The variable s is a string of one character The variable my uni is a string with 4 charactersENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 34

String manipulations You can– Concatenate strings using – Repeat strings using * Try the following yourselvesENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 35

Limitation of the console You have used the console to– Assign variables– Perform some simple computation– Manipulate strings The console is good for testing one or few linesof statement A more powerful method is to put the Pythonstatements into a file, or a Python programENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 36

Program to convert Fahrenheit to Celsius We will write a program to convert atemperature F in Fahrenheit to its equivalenttemperature C in Celsius The temperatures F and C are related by We will develop the program step by step We will type the program using the editor inSpyderENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 37

The Spyder editorNew fileSave fileRun fileStart typing in program hereENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 38

F to C conversion (version 1) Tip for typing: the Tab key can complete variable name foryou After typing the program, you can run the program using therun button– Spyder will ask you to save the file first. Do give the program ameaning name.– Note that Python programs have the extension .py– Don’t forget to save the file regularly when you work on Spyder Results will be displayed in the consoleENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 39

The print function print is a function in Python to display results Any text within single quotes will be displayed as is– You can also use double quotes. They are strings. If print sees a variable name, it will display thevalue of the variable The displayed output is the concatenation of theparts separated by commasENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 40

Program execution This program consists of 3 statements– At lines 9, 11 and 13 The statements are executed in the order that theyappearENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 41

IdentifiersWords like temp celsius in the exampleprogram are called identifiers– Identifiers are used for names of variables– Identifiers are sequences of letters (a-z, A-Z),digits (0-9) and underscores ( )– Identifier can only begin with a letter– Examples of valid identifiersmodule1x42tempy originQuiz: Which of the following identifiersare valid?day 2day day of the week day2 24 see-sawENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 42

Keywords Python has a number of keywords or reserved words You cannot use them as variable names Don’t worry about memorising them now, you will seethem a lot later on and will know them as your friends ords-identifierENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 43

Rules for choosing identifiers Rule 1: Must be valid Rule 2: Avoid keywords The program will run if it doesn’t violate Rules1 and 2 Rule 3: Choose meaningful identifiersENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 44

Identifier Conventions Identifier conventions have been devised to makeprograms more readable– Use meaningful variable names, most Pythonprogrammers use lower case words separated byunderscore for readabilitytemperaturenum countmass in kgis within normal range– OK to use short names for minor or short-lived dataENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 45

Notes Software readability is an important issue.Here is a style guide to writing Pythonprogram, known as PEP8:– https://www.python.org/dev/peps/pep-0008/– Note that for some other computerlanguages, programmers use camel case asthe style for identifiers– Camel case: first word is all lower case, the firstletter of subsequent words in upper case, e.g.isWithinNormalRange, thisYearENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 46

F to C conversion (Version 2) Comments are added to explain how a program works– All text after the # symbol is comment Comments are ignored when a program is executed Comments are for people to readENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 47

F to C conversion (version 3) Fixed or constant values are often required at severalplaces in a program By giving a name to the constant – The reader understands what the value means for example, only hard-core physicists would recognise 1.3806503e–23 in a calculation (it’s Boltzmann’s constant) Name format convention: ALL CAPS Define the constants at the beginning of the programENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 48

Why documenting a program Say, you’ve written a program that does somefabulous work for you. It is possible that you mayneed to modify it a few months later. You may havedifficulty figuring out how you did it earlier if youhaven’t documented it Use Python docstringsENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 49

Python docstring Docstring is enclosed a pair of tripe double quotesor triple single quotes Spyder typesets it in green The contents are comments, i.e. not executedENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 50

Documentation Begin with:– Purpose, author, date Then data dictionary– list of variables used and how they are used Then problem parameter assignments ifapplicable Program description Expectations:– Lab programs must be reasonably documented– Documentation carries marks in assignmentsENGG1811 UNSW, CRICOS Provider No: 00098GW8 slide 51

Mathematical functions Standard Python has a limited set of mathsoperators: - * / // % ** Sometimes you want to use sin(), cos(), log(),exp(), etc. In Python, these operations are found in themath libraryENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 52

Example: Solving quadratic equation We will write a program to solve the quadraticequation2ax bx c 0 using the formulab pb22a4ac We will use a function to compute the squareroot from the math libraryENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 53

Python code You must import the math library before using its functions Line 40 shows the usage of math.sqrt()– Let us try some examples in the consoleENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 54

The math library The math library also contain functions for:– Trigonometry and radian/degree conversion Radian is assumed– Exponential and log– Etc. The file math examples.py contains examples For a complete list, see– https://docs.python.org/3/library/math.html– s/mathENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 55

Summary Spyder development environment– iConsole, editor, program execution, saving files Programming––––Arithmetic operators and precedenceVariables and naming conventionAssignment operator Statements are executed one after another in acomputer program– Writing computer programs in a file– The math libraryENGG1811 UNSW, CRICOS Provider No: 00098GW4 slide 56

Python Python will be the programming language that you will use to learn how to give instructions to computers It is a popular programming language and it comes with a lot of extra packages that help you to do engineering work There are two versions of Python. We will be using Python 3, not Python 2.

Related Documents:

(prorated 13/week) week 1 & 2 156 week 3 130 week 4 117 week 5 104 week 6 91 week 7 78 week 8 65 week 9 52 week 10 39 week 11 26 week 12 13 17-WEEK SERIES* JOIN IN MEMBER PAYS (prorated 10.94/week) week 1 & 2 186.00 week 3 164.10 week 4 153.16 week 5 142.22 week 6 131.28 week 7 120.34

Week 3: Spotlight 21 Week 4 : Worksheet 22 Week 4: Spotlight 23 Week 5 : Worksheet 24 Week 5: Spotlight 25 Week 6 : Worksheet 26 Week 6: Spotlight 27 Week 7 : Worksheet 28 Week 7: Spotlight 29 Week 8 : Worksheet 30 Week 8: Spotlight 31 Week 9 : Worksheet 32 Week 9: Spotlight 33 Week 10 : Worksheet 34 Week 10: Spotlight 35 Week 11 : Worksheet 36 .

28 Solving and Graphing Inequalities 29 Function and Arrow Notation 8th Week 9th Week DECEMBER REVIEW TEST WEEK 7,8 and 9 10th Week OCTOBER 2nd Week 3rd Week REVIEW TEST WEEK 1,2 and 3 4th Week 5th Week NOVEMBER 6th Week REVIEW TEST WEEK 4,5 and 6 7th Week IMP 10TH GRADE MATH SCOPE AND SEQUENCE 1st Week

Year 4 negative numbers. digit numbers by one digit, integer Year Group Y4 Term Autumn Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9 Week 10 Week 11 Week 12 Number – place value Count in multiples of 6, 7, 9. 25 and 1000. digits using the formal writt

WRM –Year 6 –Scheme of Learning 2.0s Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9 Week 10 Week 11 Week 12 tumn Number: Place Value N

MMWR Week. Week 10: 3/29-4/4 3/1-3/7 Week 11: 3/8-3/14 Week 12: 3/15-3/21 Week 13: 3/22-3/28 Week 14: Week 15: 4/5-4/11 Week 16: 4/12-4/18 Week 17: 4/19-4/25 Week 18: 4/26-5/2 Week 19: 5/

Year 11 HSC Assessment Policy 2019 An information guide for parents and students. 2 Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9 Week 10 Week 11 . Anc History English Studies Physics Std English Adv English Drama CAFS Std Maths Adv Maths Ext Maths Visual Arts PDHPE Dance

2021 Grade 8 Life Orientation Annual Teaching Plan Term 3 52 days Week 1 Week 2 Week 3 Week 4 Week 5 Week 6 Week 7 Week 8 Week 9 Week 10 Week 11 Resources (other than textbook) to enhance learning Resources on World of W