pythonUnit_1forprogrammin launguage.pptx

bharathece1 60 views 147 slides May 09, 2024
Slide 1
Slide 1 of 147
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147

About This Presentation

python


Slide Content

Dr.S.Gowrishankar, Associate Professor, Department of Computer Science and Engineering, Dr.Ambedkar Institute of Technology, Bengaluru. Python Programming 1

2 Welcome To Python Programming

Course Objectives 3 To Learn Syntax and Semantics and create Functions in Python. To Handle Strings and Files in Python. To Understand Lists, Dictionaries and Regular expressions in Python. To Implement Object Oriented Programming concepts in Python To Build Web Services and Introduction to Network Programming in Python.

Course Outcomes 4 CO1: Examine Python syntax and semantics and be fluent in the use of Python flow control and functions. CO2: Demonstrate proficiency in handling Strings and File Systems. CO3: Create, run and manipulate Python Programs using core data structures like Lists, Dictionaries and use Regular Expressions. CO4: Interpret the concepts of Object-Oriented Programming as used in Python. CO5: Implement exemplary applications related to Network Programming and Web Services in Python.

Course Textbook 5 Charles R. Severance, “Python for Everybody: Exploring Data Using Python 3”, 1 st Edition, CreateSpace Independent Publishing Platform, 2016. (http://do1.dr-chuck.com/pythonlearn/EN_us/pythonlearn.pdf ) Allen B. Downey, "Think Python: How to Think Like a Computer Scientist, 2 nd Edition, Green Tea Press, 2015. (http://greenteapress.com/thinkpython2/thinkpython2.pdf)

Class Format 6 Lots of Code to Write (You and Me). Keep a Separate Book. You need to check the contents back and forth as Class progresses. You need to make note of points written on slides Q & A sessions at the end of each chapter. This gives you confidence to face campus interviews.

Slides and Live Code 7 The best system for me is to have a series of PowerPoint slides “lead” our discussion This allows me to present the material in an organized way Also, we shall discuss code snippets. It’s the most important part of the overall code. Then will show you how this Code snippet fits in the overall picture. Read from Textbook. Slides are only to convey the information as I deem fit.

People Basics 8 Lets have Interactive Sessions Questions are always welcome No discussions among yourselves Class room sanity should be strictly maintained (Avoid Noise). All cell phones (including my own) must be turned off. If your phone does accidentally go off, I expect you to turn it off immediately. Please be respectful of other students’ time and commitment to their studies by not breaching this policy so that we don’t end up in the embarrassing position of having to ask you to leave the class

Pre-Requisite: Please Install Python

How To Obtain Python 10 Make sure that you have Python 3.5 installed. All the examples in the Textbooks and class is in Python 3.5.

What is PyCharm 11 PyCharm is an Integrated Development Environment (IDE) used for programming in Python . It provides code analysis, a graphical debugger, an integrated unit tester, integration with version control systems ( VCSes ), and supports web development with Django . PyCharm is developed by the Czech company JetBrains .

Lab Programs https://github.com/csedrait 12 Click Here Click on Program Name to see the Code

IEEE Programming Language Ranking - 2017 13

Unit 1 Review 14 Why should you learn to write programs Variables, expressions and statements Conditional execution Functions

Computers want to be helpful... Computers are built for one purpose - to do things for us But we need to speak their language to describe what we want done Users have it easy - someone already put many different programs (instructions) into the computer and users just pick the ones we want to use What Next? What Next? What Next? What Next? What Next? What Next? What Next?

Users .vs. Programmers Users see computers as a set of tools - word processor, spreadsheet, map, todo list, etc. Programmers learn the computer “ ways ” and the computer language Programmers have some tools that allow them to build new tools Programmers sometimes write tools for lots of users and sometimes programmers write little “ helpers ” for themselves to automate a task

Why be a programer? To get some task done - we are the user and programmer Clean up survey data To produce something for others to use - a programming job Fix a performance problem in the software Add guestbook to a web site

What is Code? Software? A Program? A sequence of stored instructions It is a little piece of our intelligence in the computer It is a little piece of our intelligence we can give to others - we figure something out and then we encode it and then give it to someone else to save them the time and energy of figuring it out A piece of creative art - particularly when we do a good job on user experience

Hardware Architecture

http://upload.wikimedia.org/wikipedia/commons/3/3d/RaspberryPi.jpg

Software Input and Output Devices Central Processing Unit Main Memory Secondary Memory Generic Computer What Next?

Definitions Central Processing Unit : Runs the Program - The CPU is always wondering “ what to do next ” ? Not the brains exactly - very dumb but very very fast Input Devices : Keyboard, Mouse, Touch Screen Output Devices : Screen, Speakers, Printer, DVD Burner Main Memory : Fast small temporary storage - lost on reboot - aka RAM Secondary Memory : Slower large permanent storage - lasts until deleted - disk drive / memory stick What Next?

Software Input and Output Devices Central Processing Unit Main Memory Secondary Memory Generic Computer What Next? if x< 3: print

Software Input and Output Devices Central Processing Unit Main Memory Secondary Memory Machine Language What Next? 01001001 00111001

Totally Hot CPU http://www.youtube.com/watch?v=y39D4529FM4 What Next?

Hard Disk in Action http://www.youtube.com/watch?v=9eMWG3fwiEU

Python as a Language

Python is the language of the Python Interpreter and those who can converse with it. An individual who can speak Python is known as a Pythonista . It is a very uncommon skill, and may be hereditary. Nearly all known Pythonistas use software inititially developed by Guido van Rossum .

Early Learner: Syntax Errors We need to learn the Python language so we can communicate our instructions to Python. In the beginning we will make lots of mistakes and speak gibberish like small children. When you make a mistake, the computer does not think you are “ cute ” . It says “ syntax error ” - given that it *knows* the language and you are just learning it. It seems like Python is cruel and unfeeling. You must remember that *you* are intelligent and *can* learn - the computer is simple and very fast - but cannot learn - so it is easier for you to learn Python than for the computer to learn English...

Talking to Python

csev $ python Python 3.5.2 |Anaconda 4.1.1 (64-bit)|(default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> What next?

csev $ python Python 3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> x = 1 >>> print(x) 1 >>> x = x + 1 >>> print(x) 2 >>> exit() This is a good test to make sure that you have Python correctly installed. Note that quit() also works to end the interactive session.

Lets Talk to Python...

Elements of Python Vocabulary / Words - Variables and Reserved words Sentence structure - valid syntax patterns

Reserved Words You can not use reserved words as variable names / identifiers and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print

Sentences or Lines x = 2 x = x + 2 print (x) Variable Operator Constant Reserved Word Assignment Statement Assignment with expression Print statement

Programming Paragraphs

Python Scripts Interactive Python is good for experiments and programs of 3-4 lines long But most programs are much longer so we type them into a file and tell python to run the commands in the file. In a sense we are “ giving Python a script ” As convention, we add “ .py ” as the suffix on the end of these files to indicate they contain Python

Writing a Simple Program

Interactive versus Script Interactive You type directly to Python one line at a time and it responds Script You enter a sequence of statements (lines) into a file using a text editor and tell Python to execut the statements in the file

Program Steps or Program Flow Like a recipe or installation instructions, a program is a sequence of steps to be done in order Some steps are conditional - they may be skipped Sometimes a step or group of steps are to be repeated Sometimes we store a set of steps to be used over and over as needed several places throughout the program

Sequential Steps Program: x = 2 print (x) x = x + 2 print (x) Output: 2 4 x = 1 print(x) x = x + 1 print(x) When a program is running, it flows from one step to the next. We as programmers set up “ paths ” for the program to follow.

Conditional Steps Output: Smaller Finish Program: x = 5 if x < 10: print ('Smaller’) if x > 20: print ('Bigger‘) print ('Finish‘) x = 5 X < 10 ? print('Smaller‘) X > 20 ? print('Bigger‘) print('Finish‘) Yes Yes

Variables, Expressions, and Statements

Constants Fixed values such as numbers, letters, and strings are called “ constants ” - because their value does not change Numeric constants are as you expect String constants use single-quotes (') or double-quotes (") >>> print (123) 123 >>> print (98.6) 98.6 >>> print (‘ Hello world‘) Hello world

Variables A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable “ name ” Programmers get to choose the names of the variables You can change the contents of a variable in a later statement 12.2 x 14 y x = 12.2 y = 14 100 x = 100

Python Variable Name Rules Must start with a letter or underscore _ Must consist of letters and numbers and underscores Case Sensitive Good: spam eggs spam23 _speed Bad: 23spam #sign var.12 Different: spam Spam SPAM

Reserved Words You can not use reserved words as variable names / identifiers and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print

Sentences or Lines x = 2 x = x + 2 print( x ) Variable Operator Constant Reserved Word Assignment Statement Assignment with expression Print statement

Assignment Statements We assign a value to a variable using the assignment statement (=) An assignment statement consists of an expression on the right hand side and a variable to store the result x = 3.9 * x * ( 1 - x )

x = 3.9 * x * ( 1 - x ) 0.6 x Right side is an expression. Once expression is evaluated , the result is placed in (assigned to) x. 0.6 0.6 0.4 0.93 A variable is a memory location used to store a value (0.6).

x = 3.9 * x * ( 1 - x ) 0.6 0.93 x Right side is an expression. Once expression is evaluated , the result is placed in (assigned to) the variable on the left side (i.e. x). 0.93 A variable is a memory location used to store a value. The value stored in a variable can be updated by replacing the old value (0.6) with a new value (0.93).

Numeric Expressions Because of the lack of mathematical symbols on computer keyboards - we use “ computer-speak ” to express the classic math operations Asterisk is multiplication Exponentiation (raise to a power) looks different from in math. Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder

Numeric Expressions >>> xx = 2 >>> xx = xx + 2 >>> print ( xx ) 4 >>> yy = 440 * 12 >>> print ( yy ) 5280 >>> zz = yy / 1000 >>> print ( zz ) 5.28 >>> jj = 23 >>> kk = jj % 5 >>> print ( kk ) 3 >>> print (4 ** 3) 64 Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder 5 23 4 R 3 20 3

Order of Evaluation When we string operators together - Python must know which one to do first This is called “ operator precedence ” Which operator “ takes precedence ” over the others x = 1 + 2 * 3 - 4 / 5 ** 6

Operator Precedence Rules Highest precedence rule to lowest precedence rule Parenthesis are always respected Exponentiation (raise to a power) Multiplication, Division, and Remainder Addition and Subtraction Left to right Parenthesis Power Multiplication Addition Left to Right

Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print(x) 11 >>>

Parenthesis Power Multiplication Addition Left to Right >>> x = 1 + 2 ** 3 / 4 * 5 >>> print(x) 11 >>> 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11 Note 8/4 goes before 4*5 because of the left-right rule.

Operator Precedence Remember the rules top to bottom When writing code - use parenthesis When writing code - keep mathematical expressions simple enough that they are easy to understand Break long series of mathematical operations up to make them more clear Parenthesis Power Multiplication Addition Left to Right Question: x = 1 + 2 * 3 - 4 / 5

Python Integer Division is Weird! Integer division yield float Floating point division produces floating point numbers >>> print( 10 / 2 ) 5.0 >>> print( 9 / 2 ) 4.5 >>> print (99 / 100) 0.99 >>> print (10.0 / 2.0) 5.0 >>> print (99.0 / 100.0) 0.99

Mixing Integer and Floating When you perform an operation where one operand is an integer and the other operand is a floating point the result is a floating point >>> print (99 / 100) 0.99 >>> print (99 / 100.0) 0.99 >>> print (99.0 / 100) 0.99 >>> print 1 + 2 * 3 / 4.0 - 5 -2.5 >>>

What does “ Type ” Mean? In Python variables, literals, and constants have a “ type ” Python knows the difference between an integer number and a string For example “ + ” means “ addition ” if something is a number and “ concatenate ” if something is a string >>> ddd = 1 + 4 >>> print( ddd ) 5 >>> eee = 'hello ' + 'there' >>> print( eee ) hellothere concatenate = put together

Type Matters Python knows what “ type ” everything is Some operations are prohibited You cannot “ add 1 ” to a string We can ask Python what type something is by using the type () function. >>> eee = 'hello ' + 'there' >>> eee = eee + 1 Traceback (most recent call last): File "< stdin >", line 1, in <module> TypeError : Can't convert ' int ' object to str implicitly >>> type ( eee ) <class ' str '> >>> type ('hello') <class ' str '> >>> type (1) <class ' int '> >>>

Several Types of Numbers Numbers have two main types Integers are whole numbers: -14, -2, 0, 1, 100, 401233 Floating Point Numbers have decimal parts: -2.5 , 0.0, 98.6, 14.0 There are other number types - they are variations on float and integer >>> xx = 1 >>> type ( xx ) <class ' int '> >>> temp = 98.6 >>> type ( temp ) <class 'float'> >>> type (1) <class ' int '> >>> type (1.0) <class 'float'> >>>

Type Conversions When you put an integer and floating point in an expression the integer is implicitly converted to a float You can control this with the built in functions int () and float() >>> print ( float (99) / 100) 0.99 >>> i = 42 >>> type ( i ) <class ' int '> >>> f = float ( i ) >>> print (f) 42.0 >>> type (f) <type 'float'> >>> print (1 + 2 * float (3) / 4 – 5) -2.5 >>>

String Conversions You can also use int () and float() to convert between strings and integers You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type ( sval ) <class ' str '> >>> print ( sval + 1) Traceback (most recent call last): File "< stdin >", line 1, in <module> TypeError : Can't convert ' int ' object to str implicitly >>> ival = int ( sval ) >>> type ( ival ) <class ' int '> >>> print ( ival + 1) 124 >>> nsv = 'hello bob' >>> niv = int ( nsv ) Traceback (most recent call last): File "< stdin >", line 1, in <module> ValueError : invalid literal for int () with base 10: 'hello bob'

User Input We can instruct Python to pause and read data from the user using the input function The input function returns a string >>> name = input ( ‘ Who are you? ’ ) Who are you? Chuck >>> print ('Welcome', name) Welcome Chuck Even If you enter a number input considers it as string by default

Converting User Input If we want to read a number from the user, we must convert it from a string to a number using a type conversion function Later we will deal with bad input data >>> inp = input ( ‘ Europe floor? ’ ) Europe floor? >>> usf = int ( inp ) + 1 >>> print ('US floor', usf ) US floor 1

Comments in Python Anything after a # is ignored by Python Why comment? Describe what is going to happen in a sequence of code Document who wrote the code or other ancillary information Turn off a line of code - perhaps temporarily

String Operations Some operators apply to strings + implies “ concatenation ” * implies “ multiple concatenation ” Python knows when it is dealing with a string or a number and behaves appropriately >>> print (' abc ' + '123’) abc123 >>> print ('Hi' * 5) HiHiHiHiHi >>>

Mnemonic Variable Names Since we programmers are given a choice in how we choose our variable names, there is a bit of “ best practice ” We name variables to help us remember what we intend to store in them ( “ mnemonic ” = “ memory aid ” ) This can confuse beginning students because well named variables often “ sound ” so good that they must be keywords http://en.wikipedia.org/wiki/Mnemonic

x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print(x1q3p9afd) hours = 35.0 rate = 12.50 pay = hours * rate print(pay) a = 35.0 b = 12.50 c = a * b print(c) What is this code doing?

Exercise Write a program to prompt the user for hours and rate per hour to compute gross pay. Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25

Summary Type Resrved words Variables (mnemonic) Operators Operator precedence Integer Division Conversion between types User input Comments (#)

Conditional Execution

Conditional Steps Output: Smaller Finish Program: x = 5 if x < 10: print ('Smaller’) if x > 20: print ('Bigger‘) print ('Finish‘) x = 5 X < 10 ? print('Smaller‘) X > 20 ? print('Bigger‘) print('Finish‘) Yes Yes

Comparison Operators Boolean expressions ask a question and produce a Yes or No result which we use to control program flow Boolean expressions using comparison operators evaluate to - True / False - Yes / No Comparison operators look at variables but do not change the variables http://en.wikipedia.org/wiki/George_Boole Remember: “ = ” is used for assignment. Python Meaning < Less than <= Less than or Equal == Equal to >= Greater than or Equal > Greater than != Not equal

Comparison Operators x = 5 if x == 5 : print('Equals 5‘) if x > 4 : print('Greater than 4’) if x >= 5 : print('Greater than or Equal 5‘) if x < 6 : print('Less than 6‘) if x <= 5 : print('Less than or Equal 5’) if x != 6 : print('Not equal 6‘) Equals 5 Greater than 4 Greater than or Equal 5 Less than 6 Less than or Equal 5 Not equal 6

One-Way Decisions x = 5 print('Before 5’) if x == 5 : print('Is 5’) print('Is Still 5’) print('Third 5’) print('Afterwards 5’) print('Before 6’) if x == 6 : print('Is 6’) print('Is Still 6’) print('Third 6’) print('Afterwards 6‘) Before 5 Is 5 Is Still 5 Third 5 Afterwards 5 Before 6 Afterwards 6 X == 5 ? print('Is 5‘) Yes print('Still 5‘) print('Third 5‘) No

Indentation Increase indent indent after an if statement or for statement (after : ) Maintain indent to indicate the scope of the block (which lines are affected by the if/for ) Reduce indent to back to the level of the if statement or for statement to indicate the end of the block Blank lines are ignored - they do not affect indentation Comments on a line by themselves are ignored w.r.t. indentation

x = 5 if x > 2 : print('Bigger than 2‘) print('Still bigger‘) print('Done with 2‘) x = 5 if x > 2 : # comments print(‘Bigger than 2’) # don ’ t matter print(‘Still bigger’) # but can confuse you print('Done with 2‘) # if you don ’ t line # them up increase / maintain after if or for decrease to indicate end of block blank lines and comment lines ignored

x > 1 print(‘More than one’) x < 100 print(‘Less than 100’) print('All Done‘) yes yes no no x = 42 if x > 1 : print(‘More than one’) if x < 100 : print(‘Less than 100’) print 'All done' Nested Decisions

x > 1 print('More than one‘) x < 100 print('Less than 100‘) print('All Done‘) yes yes no no x = 42 if x > 1 : print('More than one‘) if x < 100 : print('Less than 100‘) print 'All done' Nested Decisions

x > 1 print('More than one‘) x < 100 print('Less than 100‘) print('All Done‘) yes yes no no x = 42 if x > 1 : print('More than one‘) if x < 100 : print('Less than 100‘) print 'All done' Nested Decisions

Two Way Decisions Sometimes we want to do one thing if a logical expression is true and something else if the expression is false It is like a fork in the road - we must choose one or the other path but not both x > 2 print('Bigger‘) yes no X = 4 print('Not bigger‘) print('All Done‘)

Two-way using else : x = 4 if x > 2 : print('Bigger‘) else : print('Smaller‘) print('All done‘) x > 2 print('Bigger‘) yes no X = 4 print('Smaller‘) print('All Done‘)

Two-way using else : x = 4 if x > 2 : print('Bigger‘) else : print('Smaller‘) print 'All done' x > 2 Print('Bigger‘) yes no X = 4 print('Smaller‘) print('All Done‘)

Multi-way if x < 2 : print ('Small‘) elif x < 10 : print ('Medium‘) else : print ('LARGE‘) print ('All done‘) x < 2 print('Small‘) yes no print('All Done‘) x<10 Print('Medium‘) yes print('LARGE‘) no

Multi-way x = 0 if x < 2 : print('Small‘) elif x < 10 : print('Medium‘) else : print('LARGE‘) Print('All done‘) x < 2 print('Small‘) yes no X = 0 print('All Done‘) x<10 print('Medium‘) yes print('LARGE‘) no

Multi-way x = 5 if x < 2: print 'Small' elif x < 10 : print('Medium‘) else : print('LARGE‘) print('All done‘) x < 2 print('Small‘) yes no X = 5 print('All Done‘) x<10 print('Medium‘) yes print('LARGE‘) no

Multi-way x = 20 if x < 2 : print('Small‘) elif x < 10 : print('Medium‘) else : print('LARGE‘) Print('All done‘) x < 2 print('Small‘) yes no X = 20 print('All Done‘) x<10 print('Medium‘) yes print('LARGE‘) no

Boolean Expressions 92 A boolean expression is an expression that is either true or false. The following examples use the operator == , which compares two operands and produces True if they are equal and False otherwise:

Boolean Expressions 93 True and False are special values that belong to the type bool ; they are not strings:

Logical Operators 94 There are three logical operators: and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English. For example, is true only if x is greater than 0 and less than 10. is true if either of the conditions is true, that is, if the number is divisible by 2 or 3. the not operator negates a boolean expression a is true if x > y is false, that is, if x is less than or equal to y Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as “true.” a This flexibility can be useful but confusing. You might want to avoid it

The try / except Structure 95 Earlier we saw a code segment where we used the raw_input and int functions to read and parse an integer number entered by the user. We also saw how treacherous doing this could be: When we are executing these statements in the Python interpreter (in interactive session), we get a new prompt from the interpreter, think “oops” and move on to our next statement. a Traceback However if this code is placed in a Python script and this error occurs, your script immediately stops in its tracks with a traceback . It does not execute the following statement.

96 Consider a sample program to convert a Fahrenheit temperature to a Celsius temperature: If we execute this code and give it invalid input, it simply fails with an unfriendly error message: Invalid Input The try / except Structure

The try / except Structure There is a conditional execution structure built into Python to handle these types of expected and unexpected errors called “try / except”. You surround a dangerous section of code with try and except . If the code in the try works - the except is skipped If the code in the try fails - it jumps to the except section The idea of try and except is that you know that some sequence of instruction(s) may have a problem and you want to add some statements to be executed if an error occurs. These extra statements (the except block) are ignored if there is no error. You can think of the try and except feature in Python as an “insurance policy” on a sequence of statements.

98 Python starts by executing the sequence of statements in the try block. If all goes well, it skips the except block and proceeds. If an exception occurs in the try block, Python jumps out of the try block and executes the sequence of statements in the except block. The try / except Structure

99 Handling an exception with a try statement is called catching an exception. In this example, the except clause prints an error message. In general, catching an exception gives you a chance to fix the problem, or try again, or at least end the program gracefully. The try / except Structure

astr = 'Hello Bob' try: istr = int ( astr ) except: istr = -1 print('First', istr ) astr = '123' try: istr = int ( astr ) except: istr = -1 print('Second', istr ) $ python tryexcept.py First -1 Second 123 When the first conversion fails - it just drops into the except: clause and the program continues. When the second conversion succeeds - it just skips the except: clause and the program continues. File Name is tryexcept.py

try / except astr = 'Bob' astr = 'Bob' try: print('Hello‘) istr = int ( astr ) print('There‘) except: istr = -1 print('Done', istr ) print('Hello‘) print('There‘) istr = int(astr) print('Done', istr ) istr = -1 Safety net

Short circuit evaluation of logical expressions 102 When Python is processing a logical expression such as x >= 2 and (x/y) > 2 , it evaluates the expression from left-to-right. Because of the definition of and , if x is less than 2, the expression x >= 2 is False and so the whole expression is False regardless of whether (x/y) > 2 evaluates to True or False When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it stops its evaluation and does not do the computations in the rest of the logical expression. When the evaluation of a logical expression stops because the overall value is already known, it is called short-circuiting the evaluation.

Short circuit evaluation of logical expressions 103 While this may seem like a fine point, the short circuit behavior leads to a clever technique called the guardian pattern. Consider the following code sequence in the Python interpreter: Not Executed due to Short Circuit This is False

Short circuit evaluation of logical expressions 104 The third calculation failed because Python was evaluating (x/y) and y was zero which causes a runtime error. But the second example did not fail because the first part of the expression x >= 2 evaluated to False so the (x/y) was not ever executed due to the short circuit rule and there was no error.

Guard Evaluation 105 We can construct the logical expression to strategically place a guard evaluation just before the evaluation that might cause an error as follows:

Guard Evaluation 106 In the first logical expression, x >= 2 is False so the evaluation stops at the and . In the second logical expression x >= 2 is True but y != 0 is False so we never reach (x/y) . In the third logical expression, the y != 0 is after the (x/y) calculation so the expression fails with an error. In the second expression, we say that y != 0 acts as a guard to insure that we only execute (x/y) if y is non-zero.

107 Exercise

Exercise Rewrite your pay program using try and except so that your program handles non-numeric input gracefully. Enter Hours: 20 Enter Rate: nine Error, please enter numeric input Enter Hours: forty Error, please enter numeric input

Summary Comparison operators == <= >= > < != Logical operators: and or not Indentation One Way Decisions Two way Decisions if : and else : Nested Decisions Multiway decisions using elif Try / Except to compensate for errors

Functions

Function Definition In Python a function is some reusable code that takes arguments (s) as input does some computation and then returns a result or results We define a function using the def reserved word We call/invoke the function by using the function name, parenthesis and arguments in an expression Once we define a function, we can reuse the function over and over throughout our program

Python Functions There are two kinds of functions in Python. Built-in functions that are provided as part of Python - input(), type(), float(), int () ... Functions that we define ourselves and then use We treat the user defined function names as "new" reserved words (i.e. we avoid them as variable names)

Built-in functions 113 Python provides a number of important built-in functions that we can use without needing to provide the function definition. The creators of Python wrote a set of functions to solve common problems and included them in Python for us to use. The max and min functions give us the largest and smallest values in a list, respectively: The max function tells us the “largest character” in the string (which turns out to be the letter “w”) The min function shows us the smallest character which turns out to be a space.

Built-in functions 114 Another very common built-in function is the len function which tells us how many items are in its argument. If the argument to len is a string, it returns the number of characters in the string. These functions are not limited to looking at strings, they can operate on any set of values. You should treat the names of built-in functions as reserved words (i.e. avoid using “max” as a variable name).

Type conversion functions 115 Python also provides built-in functions that convert values from one type to another. The int function takes any value and converts it to an integer, if it can, or complains otherwise:

Type conversion functions 116 int can convert floating-point values to integers, but it doesn’t round off; it chops off the fraction part: float converts integers and strings to floating-point numbers: str converts its argument to a string:

Random numbers 117 Given the same inputs, most computer programs generate the same outputs every time, so they are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious example, but there are more.

Random numbers 118 Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers. Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from random.

Random numbers 119 The random module provides functions that generate pseudorandom numbers (which I will simply call “random” from here on). The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you call random , you get the next number in a long series.

Random numbers 120 The random function is only one of many functions which handle random numbers. The function randint () takes parameters low and high and returns an integer between low and high (including both). To choose an element from a sequence at random, you can use choice :

Math functions Python has a math module that provides most of the familiar mathematical functions. Before we can use the module, we have to import it: This statement creates a module object named math. If you print the module object, you get some information about it: The module object contains the functions and variables defined in the module. To access one of the functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as a period). This format is called dot notation. 121

Math functions The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module also provides a function called log that computes logarithms base e . The second example finds the sine of radians . The name of the variable is a hint that sin and the other trigonometric functions ( cos , tan , etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2π: a 122

Math functions The expression math.pi gets the variable pi from the math module. The value of this variable is an approximation of π, accurate to about 15 digits . If you know your trigonometry, you can check the previous result by comparing it to the square root of two divided by two: 123

Building our Own Functions We create a new function using the def keyword followed by optional parameters in parenthesis. We indent the body of the function This defines the function but does not execute the body of the function The rules for function names are the same as for variable names: letters, numbers and some punctuation marks are legal, but the first character can’t be a number. You can’t use a keyword as the name of a function, You should avoid having a variable and a function with the same name. The empty parentheses after the name indicate that this function doesn’t take any arguments. def print_lyrics (): print ("I'm a lumberjack, and I'm okay.”) print ('I sleep all night and I work all day.‘)

Building our Own Functions The first line of the function definition is called the header; the rest is called the body. The header has to end with a colon and the body has to be indented. By convention, the indentation is always four spaces. The body can contain any number of statements. The strings in the print statements are enclosed in double quotes. Single quotes and double quotes do the same thing; 125

Building our Own Functions If you type a function definition in interactive mode, the interpreter prints ellipses (...) to let you know that the definition isn’t complete: To end the function, you have to enter an empty line (this is not necessary in a script or python file). 126

Building our Own Functions Defining a function creates a variable with the same name. The value of print_lyrics is a function object, which has type ' function '. 127

Building our Own Functions The syntax for calling the new function is the same as for built-in functions: 128

Building our Own Functions Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeat_lyrics 129

Definitions and uses Pulling together the code fragments from the previous section, the whole program looks like this: This program contains two function definitions: print_lyrics and repeat_lyrics . Function definitions get executed just like other statements, but the effect is to create function objects. The statements inside the function do not get executed until the function is called, and the function definition generates no output. 130

Flow of execution In order to ensure that a function is defined before its first use, you have to know the order in which statements are executed, which is called the flow of execution. Execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom. Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called. A function call is like a detour in the flow of execution. Instead of going to the next statement, the flow jumps to the body of the function, executes all the statements there, and then comes back to pick up where it left off. 131

Flow of execution That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to execute the statements in another function. But while executing that new function, the program might have to execute yet another function! Fortunately, Python is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates. When you read a program, you don’t always want to read from top to bottom. Sometimes it makes more sense if you follow the flow of execution. 132

Arguments An argument is a value we pass into the function as its input when we call the function We use arguments so we can direct the function to do different kinds of work when we call it at different times We put the arguments in parenthesis after the name of the function big = max ( 'Hello world' ) Argument

Parameters A parameter is a variable which we use in the function definition that is a “ handle ” that allows the code in the function to access the arguments for a particular function invocation. >>> def greet ( lang ): ... if lang == ' es ': ... print (' Hola ’) ... elif lang == ' fr ': ... print ('Bonjour’) ... else : ... print ('Hello’) ... >>> greet ( ' en ' ) Hello >>> greet ( ' es ' ) Hola >>> greet ( ' fr ' ) Bonjour >>> Parameter Argument

Arguments and Parameters Here is an example of a user-defined function that takes an argument This function assigns the argument to a parameter named param1. When the function is called, it prints the value of the parameter (whatever it is) twice. 135

Arguments and Parameters You can also use a variable as an argument: 136

Fruitful functions and void functions A “ fruitful ” function is one that produces a result (or return value ) Some functions perform an action but don’t return a value. They are called void functions The return statement ends the function execution and “ sends back ” the result of the function When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression: 137

Fruitful functions and void functions When you call a function in interactive mode, Python displays the result: But in a script, if you call a fruitful function and do not store the result of the function in a variable, the return value vanishes This script computes the square root of 5, but since it doesn’t store the result in a variable or display the result, it is not very useful. Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None a 138

return Statement The value None is not the same as the string ' None '. It is a special value that has its own type: To return a result from a function, we use the return statement in our function. For example, we could make a very simple function called addtwo that adds two numbers together and return a result. a 139

return Statement When this script executes, the print statement will print out “8” because the addtwo function was called with 3 and 5 as arguments. Within the function the parameters a and b were 3 and 5 respectively. The function computed the sum of the two numbers and placed it in the local function variable named added and used the return statement to send the computed value back to the calling code as the function result which was assigned to the variable x and printed out. 140

Return Values Often a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression . The return keyword is used for this. def greet (): return “Hello” print ( greet() , "Glenn” ) print ( greet() , "Sally“ ) Hello Glenn Hello Sally

Return Value A “ fruitful ” function is one that produces a result (or return value ) The return statement ends the function execution and “ sends back ” the result of the function >>> def greet ( lang ): ... if lang == ' es ': ... return ' Hola ’ ... elif lang == ' fr ': ... return 'Bonjour’ ... else: ... return 'Hello’ ... >>> print ( greet ( 'en' ),'Glenn’) Hello Glenn >>> print ( greet ( ' es ' ),'Sally’) Hola Sally >>> print ( greet ( ' fr ' ),'Michael’) Bonjour Michael >>>

Multiple Parameters / Arguments We can define more than one parameter in the function definition We simply add more arguments when we call the function We match the number and order of arguments and parameters def addtwo ( a, b ): added = a + b return added x = addtwo ( 3, 5 ) print (x)

Void (non-fruitful) Functions When a function does not return a value, we call it a " void " function Functions that return values are "fruitful" functions Void functions are "not fruitful"

To function or not to function... Organize your code into “ paragraphs ” - capture a complete thought and “ name it ” Don ’ t repeat yourself - make it work once and then reuse it If something gets too long or complex, break up logical chunks and put those chunks in functions Make a library of common stuff that you do over and over - perhaps share this with your friends...

Exercise Rewrite your pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters ( hours and rate). Enter Hours: 45 Enter Rate: 10 Pay: 475.0 475 = 40 * 10 + 5 * 15

Summary Functions Built-In Functions Type conversion ( int , float) Math functions (sin, sqrt ) Try / except (again) Arguments Parameters
Tags