programming for engineers in python sawa 2015 lecture 1: introduction to python 1
TRANSCRIPT
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!
4
Administration
Lectures
Lena Dankin lenadank at tau.post.ac.il
Recitations
Aviad Panhi
Web Sites:
Moodle
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.
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.
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.
8
Homework • Submission in singles via Moodle • It is allowed (and encouraged) to talk, share
ideas, and help friends. • No code-sharing!
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
12
Syllabus
• Python programming basics• Recursion• Sort & Search algorithms• Runtime Analysis• Error Handling• Object-Oriented
Programming• Image Processing
• Scientific Calculations• Simulations • Data analysis
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
15
Preface
• We assume no prior knowledge in programming.
• However, we advance fast.• The only way to keep on track is to practice!
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)
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.
19
There are Many Programming Languages
Over 500 different computer languages are listed by Wikipedia
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
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.
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
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
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
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
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…
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
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
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
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
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
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
40
Strings concatenation
>>> s1 = "He">>> s2 = "llo">>> s3 = s1 + s2>>> s3'Hello'>>> s4 = s3 + " World">>> c = "!">>> print s4, 2014, cHello World 2014 !
42
Strings Built In Methodshttp://docs.python.org/release/2.5.2/lib/string-methods.html
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
Comparison Operators
>>> 5 == 5.0
True
>>> 6 != 2*3
False
>>> -2 >= 1
False
>>> 3 <= 3
True
>>> x = 3 < 3
>>> x
False
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
47
Flow Control
Different inputs Different execution order–Computer games– Illegal input
Control structures– if-else– for loop–while loop
http://xkcd.com/1195/
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
>> 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
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
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
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.
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"
56
elif = else-if
if price < 100:
print "too cheap"
elif price > 200:
print "too expensive“
else:
print "reasonable price"
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.
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:
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.
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!
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!'
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.