Top Banner
Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1
63

Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Dec 29, 2015

Download

Documents

Oscar Lee
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Programming for Engineers

in Python

Sawa 2015

Lecture 1: Introduction to Python1

Page 2: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

2

Welcome to Programming for Engineers course!

• We will learn to program in Python.

• Goal: enable you to use programming as a tool to solve "real world" problems.

• Hard work is required!

Page 3: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

3

Course Objectives

Develop basic programming and algorithmic skills

Page 4: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

4

Administration

Lectures

Lena Dankin lenadank at tau.post.ac.il

Recitations

Aviad Panhi

Web Sites:

Moodle

Page 5: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

5

Administration

Website via Moodle: http://moodle.tau.ac.il

Everything is there:• Lectures• Practical sessions• Homework assignments, submission, grading• Code examples• Forum• Announcements

Make sure you are updated.

Page 6: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

6

Recitations

• Purposes:• Practice topics presented in class.• Learn practical tools.• Help in overcoming trivial difficulties

• Lectures will be harder to understand, and it is OK.

Page 7: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

7

Home Assignments

• Short assignments every day.• 3-4 home assignments that should be

submitted. • Some more assignments to practice the

material, no need to submit.

Page 8: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

8

Homework • Submission in singles via Moodle • It is allowed (and encouraged) to talk, share

ideas, and help friends. • No code-sharing!

Page 9: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

9

A Personal Note on HW

It will take time and effort to make the code work.

But

There is no other way to learn how to program

Page 10: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

10

Exam

• Written exam• Includes all course material• You must pass the exam to pass the course.

Page 11: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

11

Working Environment

• Lab 008• Home versus lab

VS.

Page 12: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

12

Syllabus

• Python programming basics• Recursion• Sort & Search algorithms• Runtime Analysis• Error Handling• Object-Oriented

Programming• Image Processing

• Scientific Calculations• Simulations • Data analysis

Page 13: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

13

Resources

• Course slides and pointers to relevant bibliography.• Many Python references, tutorials or manuals.• Recommended resources:

• Book: Think Python, by Allen B. Downey (http://greenteapress.com/thinkpython/thinkpython.html)

• Manual: Python 2.x documentation http://docs.python.org// (the official language manual)

• Course’s website

Page 14: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

14

Questions?

Page 15: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

15

Preface

• We assume no prior knowledge in programming.

• However, we advance fast.• The only way to keep on track is to practice!

Page 16: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

16

Today

• Brief background• Python basics:

• Variables • numbers • Strings

Page 17: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

17

Computers understand only machine language.

Basically looks like a sequence of 1’s and 0’s.

Very inconvenient to work with and non-intuitive.

All other computer languages were created for human convenience.

The computer does not understand C/Python/Java, it must be "translated" into machine language

Machine Code (Language)

Page 18: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

18

Programming Languages Basics

• A computer program is a sequence of instructions (text) that can be "understood" by a computer and executed.

• A programming language is a machine-readable artificial language designed to express computations that can be performed by a computer.

Page 19: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

19

There are Many Programming Languages

Over 500 different computer languages are listed by Wikipedia

Page 20: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

20

Page 21: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

21

Language Selection and Python

Consider: Goal Runtime vs. Development time Operating systems

Python: Quick development, small to medium tasks:Experiments / Data analysis / Small projects Short development-execution rounds

Page 22: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

22

Computer Program(more technically)

• A sequence of processor instructions designed to achieve a specific purpose

• Unless otherwise specified, the instructions are executed sequentially, in the order they’re written in the program.

• In this course, we assume that no two instructions can execute simultaneously.

Page 23: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

23

Installing and Running Python 2.7• Python 2.7 is already installed in the computers’

classroom• Install:

• Anaconda: https://store.continuum.io/cshop/anaconda/

• A “Anaconda" folder will be created in you Start Menu:• IDLE (Python GUI) - recommended working environment• Python (command line) - textual Python interpreter (faster, less

convenient)• A Working with IDLE video:

http://www.youtube.com/watch?v=lBkcDFRA958

Page 25: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

25

My First Python Program: Hello World!

Page 26: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

26

Hands On

Page 27: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

27

Memory

• The computer memory is composed of a long list of bits (0 and 1)

• Bits are grouped into bytes (8 bits) and words (4 bytes, 8 on 64-bit systems)

• Every byte is numbered sequentially• This number is called an address

Page 28: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

What are Variables ?

A location in the computer’s memory.

A variable:- has a name - holds a value- has type – according to its

value (“duck typing”)

This is how data is handled28

Page 29: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

29

Why do We Need Variables?

• Computer programs manipulate data• Data is given as input or calculated throughout

the program• To access them later, variables must be

remembered• Thus, variables are stored in the memory• Variable name memory address

Page 30: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

30

Why Do We Need Different Types?

• Saving memory• Execution speed

Page 31: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Numbers and their Types

>>> 4

4

>>> type(4)

<class 'int'> # integers type

>>> 3.14159

3.14159

>>> type(3.14159)

<class 'float'> # floating point ("reals") type

Arithmetic operations: +, -, *, / , % (modulo), ** (power)

What type is 8/5 ? And 8/5.0 ?

Let’s check…

Page 32: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Variables and Assignments

>>> n = 10 >>> m = (n+4)*5

The variable's name is a sequence of letters

and digits, starting with a letter.

The interpreter:

1. evaluates the expression

2. assigns its value to the variable.

10 70n m

Variable

Expression

Page 33: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Variables and Assignments: An Example

Changing the value of a variable:

>>> n = 11

>>> n

11

Changing the type of a variable:

>>> n = 1.3141

>>> n

1.3141

Variables can be used in expressions:

>>> pi = 3.14159

>>> pi * 2 + 1

7.28318

Page 34: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Variables and Assignments – Cont.

Referring to undefined variables leads to runtime error

>>> check_this

Traceback (most recent call last):

File "<pyshell#16>", line 1, in <module>

check_this

NameError: name 'check_this' is not defined

Page 35: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

35

Arithmetic Operators

Operator Use Description

+ x + y Adds x to y

- x - y Subtracts x from y

* x * y Multiplies x by y

** x ** y X to the power y

/ x / y Divides x by y

% x % y Computes the remainder of dividing x by y

Page 36: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

36

Playing with Variables >>> a = 3

>>> a

3

>>> b = 5

5

>>> c = a + b

>>> c

8

>>> c = c * 2

16

>>> b**a

125

>>> first = (a + b) * 2

>>> second = a + b * 2

>>> first, second

(16, 13)

>>> b / a

1

>>> b % a

2

Page 37: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Strings

• Strings are text sequences. • An ordered list of characters

37

Page 38: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

38

String Type

Page 39: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Strings Access>>> a = ‘Hello’

>>> a[1:3]

'el'

>>> a[1:]

'ello'

>>> a[-4:-2]

'el'

>>> a[:-3]

'He'

>>> a[-3:]

'llo’

H e l l o

0 1 2 3 4 5

-5 -4 -3 -2 -1

Page 40: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

40

Strings concatenation

>>> s1 = "He">>> s2 = "llo">>> s3 = s1 + s2>>> s3'Hello'>>> s4 = s3 + " World">>> c = "!">>> print s4, 2014, cHello World 2014 !

Page 41: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

41

Strings Structure

Page 42: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

42

Strings Built In Methodshttp://docs.python.org/release/2.5.2/lib/string-methods.html

Page 43: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

43

Comparison Operators

Operator Name Description

x < y Less than true if x is less than y, otherwise false.

x > y Greater than true if x is greater than y, otherwise false.

x <= y Less than or equal to

true if x is less than or equal to y, otherwise false.

x >= y Greater than or equal to

true if x is greater than or equal to y, otherwise false.

x == y Equal true if x equals y, otherwise false.

x != y Not Equal true if x is not equal to y, otherwise false.

Compares two variables and returns a Boolean type result/variable

Page 44: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Comparison Operators

>>> 5 == 5.0

True

>>> 6 != 2*3

False

>>> -2 >= 1

False

>>> 3 <= 3

True

>>> x = 3 < 3

>>> x

False

Page 45: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

45

Logical Operators

Operates on two Booleans and returns a Boolean

Operator

Description

x and y

Both True: True, otherwise: False.

x or y

At least one is rue: True, Otherwise: False.

not x

x is False True, x is True False

Page 46: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

46

And, or, not

0 1

0 0 01 0 1

0 1

0 0 11 1 1

0 1

1 0

and or not

Page 47: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

47

Flow Control

Different inputs Different execution order–Computer games– Illegal input

Control structures– if-else– for loop–while loop

http://xkcd.com/1195/

Page 48: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

48

Conditional Statement: if

Used to execute statements conditionally

Syntax

if condition:

statement1

statement2

…• If condition is True, statements are executed

Condition = expression that evaluates to a Boolean

Indentation = determines the scope of the if block

Page 49: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Conditional Statements

Page 50: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

>> num = 54 # choose a number

>> if num % 18 == 0: # num is a multiplication of 18

…print num, “is divisible by 18“

…res = num / 18

>>> print “Goodbye”

54 is divisible by 18

Goodbye

Conditional Statements - Examples

Page 51: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

Conditional Statements

Indentation: • Following the if statement:

Open a new scope = one tab to the right. • Indicates the commands within the scope

of this if.

51

Page 52: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

52

if-else

if condition1:statement1

elif condition2:statement2

else:statement3

condition1 is true execute statement1

condition1 false and condition2 true execute statement2 both conditions are false execute statement3

Page 53: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

if-else

Page 54: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

if-else

if width == height:

print “found a square”

else:

print “found a rectangle”

width = height

print “now it is a square”

Indentation: else is not part of the if scope!

The commands under else are indented.

Page 55: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

55

if-elsea = 4

b = 5

c = 6

if a + b >= c and a + c >= b and b + c >= a:

print "Building a triangle"

else:

print "Cannot build a triangle"

Page 56: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

56

elif = else-if

if price < 100:

print "too cheap"

elif price > 200:

print "too expensive“

else:

print "reasonable price"

Page 57: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

57

Program Readability

• Real computer programs include thousands of code lines, lots of variables.

• Readability is very important for code maintenance,it is a requirement in this course!

• The next slide list some programming conventions that are crucial for readability.

Page 58: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

58

Program Readability – Cont.

• Choose informative variable names:

– Are i, j, m , n informative names? Depends on context.

• Comments:– option 1: begin with # (until end of line)– option 2: surrounded by """ (3 double quotes) when spanned

over multiple lines

• Documentation is most important before ‘logical units’ or complex implementation.

w sm a_string Not informative:

word_count sum_of_expenses student_name Informative:

Page 59: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

59

Class ExampleDonuts:

Input: Define a variable named donuts and assign to it some number (of donuts).

Output:• If donuts is no more than 5, print 'Number of donuts: donuts.'• Otherwise, if donuts is no more than 10, print

'Number of donuts: donuts...'

• Otherwise, print 'Number of donuts: a lot!'

Note: the trailing ‘.’ / ‘…’ / ‘!’ must be printed without any space before them.

Run your program. Examples are in the next slide.

Page 60: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

60

Class Example – Cont.Examples:

For 5 donuts you should get:

Number of donuts: 5.For 9 donuts you should get:

Number of donuts: 9...For 23 donuts you should get:

Number of donuts: a lot!

Page 61: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

61

Solution to Class Exampledonuts = 7if donuts <= 5: print 'Number of donuts:', str(donuts) + '.'elif donuts <= 10: print 'Number of donuts:', str(donuts) + '...'else: print 'Number of donuts: a lot!'

Page 62: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

62

“My Code doesn’t Work!”

• Go over your code carefully.• Consult course slides.

• Google (a useful and legitimate source).• Good forums to ask questions online:

stackoverflow.com, underwar.co.il

• Check the public forum in Moodle.• Submit a question to forum (reply within 48 hours).

– Please never paste solution code in the forum.

Page 63: Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1.

63

Understanding Errors

Traceback (most recent call last): File "C:\Users\John\Desktop\blah.py", line 2, in <module> b = 2 / aZeroDivisionError: integer division or modulo by zero

Where in your program?

The last line of the error is most informative.