Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Programming for Engineers in Python Sawa 2015 Lecture 1: Introduction to Python 1."— Presentation transcript:

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

2 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!

3 3 Course Objectives Develop basic programming and algorithmic skills

4 4 Administration Lectures Lena Dankin lenadank at tau.post.ac.il Recitations Aviad Panhi Web Sites: Moodle

5 5 Administration Website via Moodle: http://moodle.tau.ac.ilhttp://moodle.tau.ac.il Everything is there: Lectures Practical sessions Homework assignments, submission, grading Code examples Forum Announcements Make sure you are updated.

6 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 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 8 Homework Submission in singles via Moodle It is allowed (and encouraged) to talk, share ideas, and help friends. No code-sharing!

9 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

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

11 11 Working Environment Lab 008 Home versus lab VS.

12 12 Syllabus Python programming basics Recursion Sort & Search algorithms Runtime Analysis Error Handling Object-Oriented Programming Image Processing Scientific Calculations Simulations Data analysis

13 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 ) http://greenteapress.com/thinkpython/thinkpython.html Manual: Python 2.x documentation http://docs.python.org// (the official language manual)http://docs.python.org// Course’s website

14 14 Questions?

15 15 Preface We assume no prior knowledge in programming. However, we advance fast. The only way to keep on track is to practice!

16 16 Today Brief background Python basics: Variables numbers Strings

17 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 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 19 There are Many Programming Languages Over 500 different computer languages are listed by Wikipedia

20 20

21 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 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 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/ 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 http://www.youtube.com/watch?v=lBkcDFRA958

24 24 Hello World!

25 25 My First Python Program: Hello World!

26 26 Hands On

27 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

28 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 handled 28

29 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

30 30 Why Do We Need Different Types? Saving memory Execution speed

31 Numbers and their Types >>> 4 4 >>> type(4) # integers type >>> 3.14159 3.14159 >>> type(3.14159) # floating point ("reals") type Arithmetic operations: +, -, *, /, % (modulo), ** (power) What type is 8/5 ? And 8/5.0 ? Let’s check…

32 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 70 nm VariableExpression

33 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

34 Variables and Assignments – Cont. Referring to undefined variables leads to runtime error >>> check_this Traceback (most recent call last): File " ", line 1, in check_this NameError: name 'check_this' is not defined

35 35 Arithmetic Operators OperatorUseDescription +x + yAdds x to y -x - ySubtracts x from y *x * yMultiplies x by y **x ** yX to the power y /x / yDivides x by y %x % yComputes the remainder of dividing x by y

36 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

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

38 38 String Type

39 Strings Access >>> a = ‘Hello’ >>> a[1:3] 'el' >>> a[1:] 'ello' >>> a[-4:-2] 'el' >>> a[:-3] 'He' >>> a[-3:] 'llo’

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

41 41 Strings Structure

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

43 43 Comparison Operators OperatorNameDescription x < y Less thantrue if x is less than y, otherwise false. x > y Greater thantrue 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 Equaltrue if x equals y, otherwise false. x != y Not Equaltrue if x is not equal to y, otherwise false. Compares two variables and returns a Boolean type result/variable

44 Comparison Operators >>> 5 == 5.0 True >>> 6 != 2*3 False >>> -2 >= 1 False >>> 3 <= 3 True >>> x = 3 < 3 >>> x False

45 45 Logical Operators Operates on two Booleans and returns a Boolean OperatorDescription 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

46 46 And, or, not 01 0 00 1 01 01 0 01 1 11 01 10 and or not

47 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 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

49 Conditional Statements

50 >> 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

51 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 52 if-else if condition 1 : statement 1 elif condition 2 : statement 2 else: statement 3 condition 1 is true  execute statement 1 condition 1 false and condition 2 true  execute statement 2 both conditions are false  execute statement 3

53 if-else

54

55 55 if-else a = 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 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. 57

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. 58 wsma_string Not informative: word_countsum_of_expensesstudent_name Informative:

59 Class Example Donuts: 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. 59

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! 60

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

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.ilstackoverflow.comunderwar.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. 62

63 Understanding Errors Traceback (most recent call last): File "C:\Users\John\Desktop\blah.py", line 2, in b = 2 / a ZeroDivisionError: integer division or modulo by zero 63 Where in your program? The last line of the error is most informative.


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

Similar presentations


Ads by Google