Computers & Programming CSE 011, Level-0 PDF
Document Details
Uploaded by OrderlyGlacier5096
University of Alexandria
Tags
Summary
This document provides course details for a Computer and Systems Engineering course, CSE 011, Level 0 at the University of Alexandria. The document covers course code & policy, grades, and team information, as well as introductory materials about programming and computers.
Full Transcript
Computers & Programming CSE 011, Level-0 Computer and Systems Engineering Department Faculty of Engineering - Alexandria University Welcome We wish you a successful and fruitful semester 2 Course Code & Policy Attending the lectures...
Computers & Programming CSE 011, Level-0 Computer and Systems Engineering Department Faculty of Engineering - Alexandria University Welcome We wish you a successful and fruitful semester 2 Course Code & Policy Attending the lectures is mandatory Always use your academic email in communications with us Questions and discussions In lectures, or Office hours, or Microsoft Teams There is no Website or Social medial forums for the course. In case of vacations or days off, please attend the lecture or the lab with any other group that suits your timetable. 4 Grades Policy Online Sheets (almost Weekly) 5% -- 10 sheets Labs (Bi-Weekly) 15% -- best 5 out of 6 Midterm 20% -- MCQ Final Exam 60% -- MCQ 5 Teams Use code: 5gpa3pe 6 Teams Use code: 5gpa3pe 7 Go here to answer your Weekly Sheets Announcements Only (Grades, Timetable changes, … ) Students Discussions & Questions Download Labs 8 2 The lectures are found in the lectures folder in class materials 1 Labs Even Sections & Odd Sections in alternative weeks Please check Microsoft Teams (General Channel) for the announcements on the dates 10 References Charles R. Severance Python for Everybody Book website: https://www.py4e.com/ 11 References Understandin Deborah Morley g Computers Charles S. Parker Today & Tomorrow Available on Google Books 12 Course Contents Week Lecture Reference 1 Introduction Python for All: Chapter 1 2 Variables, expressions and statements Python for All: Chapter 2 3 Conditional Execution Python for All: Chapter 3 4 Functions Python for All: Chapter 4 5 Loops and Iterations Python for All: Chapter 5 6 Strings & Lists Python for All: Chapter 6 & 8 7 Dictionary & Tuples Python for All: Chapter 9 & 10 8 Midterm 9 Introduction to Database Systems Understanding Computers: Chapter 14 10 Using Databases & SQL Python for All: Chapter 15 11 Hardware (Processing and Memory) Understanding Computers: Chapter 2 12 Computer Networks and Internet Understanding Computers: Chapter 7 13 Introduction to Machine Learning 13 Lecture 1 Program Development & Programming Languages In this lecture Why Computer Systems main functions Computer Systems main components Program Development Life Cycle Programming Languages Translators and Compilers Algorithms Design 15 Why do we study this course? Computers are built for one purpose To do Things for Us We need to speak their language to describe what we want done If we knew this language, we could tell the computer to do tasks on our behalf that were repetitive 16 Why do we study this course? The kinds of things computers can do best are often the kinds of things that we humans find boring Delegating this boring stuff to computer, gives you more time for you can do best: creativity, intuition, and inventiveness 17 Computer Definition “A computer is an electronic device that works based on a set of instructions that are stored in its memory. It receives data and process it using programs to produce information. Furthermore, it can store data and information for later usage.” 18 Computer Functions Computers have four main functions Input Storage Processing Output 19 Computer System A computer systems has four main components Software Data Hardware Information 20 Computer System: Data vs. Information Data are the set of facts such as Data symbols, words, pictures, video, numbers that represents the inputs to the computer Information is the data after being processed such as reports, statistics, charts that are produced as outputs Information from the computer 21 Computer System: Hardware Hardware are the physical components of the computer Hardware 22 Computer System: Software Software: a set of ordered and detailed instructions that are being loaded into main memory and instruct the computer to perform the needed operations from it. Software 23 Software Types System Software are all the software that control and supervise computer components (both software and hardware). Example: Operating Systems (e.g., Windows, Unix, Mac, Android, ….) Applications Software are all the software that count on the existence of an underlying system software and the services provided by it. Examples: Games, spreadsheet editors, drawing software, music players, database management software, …. 24 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Progra Debugging & Testing m Coding 25 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Progra Debugging & Testing m Coding 26 1. Problem Analysis Clearly specify and understand the problem Programmers need accurate and detailed requirements Input You must define Inputs: the data received from the users Outputs: the desired outcomes and the Time Table screens and the formats Specs Features and specifications and approve it from the customer Time Plan to complete the development Programming Language that will be used and how the program will interact with Output other programs Programming Language 27 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Progra Debugging & Testing m Coding 28 2. Program Design In this phase, the programmer writes the Algorithm which is represented by defined logical steps that aim to find a solution for the Problem with the desired outcomes. You can write the Algorithm using Pseudocode: writing ideas in an English-like language without machine-specific details. It can then be easily transformed into a programming language Flowchart: drawing figures that explains the steps in a visual representation 29 Pseudocode vs Flowchart Example: Given a length in meter, calculate it in centimeter Flowchart Pseudocode Start Read length in meter Multiply length by 100 Read length in Write length to represent its value in meter centimetre More Length in about cm = 100 * Flowcharts at the end length in m of the lecture Write length in centimeter End 30 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Progra Debugging & Testing m Coding 31 3. Program Coding In this phase, we transform the Algorithm into a Program written using one of the Programming Languages A Programming Language is a set of rules used to write a program. Programming languages can be classified to: Low-Level Languages High-Level Languages In order to write a program using a programming language, the developer needs An application named Integrated Development Environment (IDE). The IDE helps the developer to write the program and correct the errors. An application to transform the program into machine language (Compiler or Interpreter) 32 Low-level Languages Programs written using it are machine instructions Every line is a machine instruction Can be categorized as Machine Language Assembly Language 33 Machine Language – Low Level This is the only language that the computer can understand directly. Its instructions are Bit Strings that represent the different commands A Bit is a single unit that takes one of two values: 0 or 1 Uses Registers which are small and limited memory units inside the processor. 34 Assembly Language – Low Level Limitations Each processor type has its own Assembly language. The developer must be fully aware of the processor design. Very detailed and needs long time and big effort to write. Advantages Fully utilizes the processor. Programs written using assembly languages execute faster. 35 High-level Languages Aims Increase programmers’ productivity The programmer doesn’t need to understand the hardware details. Its commands are English-like (e.g., print, input, copy). High-level languages processors are needed to transform the programs written using a high-level language into a low-level language. Examples: FORTRAN, Pascal, (C, C++, and C#), Java, Python : Advantages: Loosely coupled to hardware Easy to learn Easy to find and correct errors Save time and effort 36 Language Processor Transform the program written by any high-level language or assembly language to the equivalent program written in machine language. Source Language Object program processor program 37 Language Processor Language Processor Types Assembler: transforms the language written in assembly to its equivalent machine code. Compiler: transforms all the source program into object program before its execution. Interpreter: translates and executes the source program line by line. Each high-level language has its own Compiler or Interpreter Source Language Object program processor program 38 Language Processor What is the difference between compilers and interpreters? Programs that use interpreters are slower than the programs that use compilers because interpreters translate the program each time the program is executed. Compiled programs need more memory than the program that uses the interpreter. Interpreted programs are easy to stop at any line then resume its execution which makes it easier to test and modify. 39 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Progra Debugging & Testing m Coding 40 4. Program Debugging and Testing We need to make sure that the program is error-free and do what it was designed to do. Debugging: make sure the program has no errors. Errors (Bugs) can be either: Compile-Time errors Run-Time errors Logical errors Testing: The program is tested using test scenarios that have specific input data. The program is tested more than once and with all possible cases. 41 Compile-Time error X = Y * 10o0 Run-Time error Input Z X=Y/Z Logical error Input x Input y z=x-y Print “sum =”, z 42 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Progra Debugging & Testing m Coding 43 5. Program Maintenance This is done after the customer starts using the software, and this includes: Fixing errors and bugs that were not discovered during the development Addressing new customer needs Handling any changes to the problem that the program is solving Updating the program with any technology changes 44 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Progra Debugging & Testing m Coding 45 Program Development Life Cycle (PDLC) Problem Analysis Progra Program Maintenance m Design Documentation Progra Debugging & Testing m Coding 46 Documentation Done in all the Program Development Life Cycle. Useful for the programmer, as this can serve as a reminder of the basic idea of the program whenever the programmer returns back to it. Useful for any other programmer to continue the development or doing the maintenance of the program. 47 Flowcharts 48 Flowcharts One of the common methods in Algorithms design. Set of shapes with specific meaning (e.g., circle, rectangle, ellipse, parallelogram, rhombus, … ). Shapes are connected with arrows represent the flow. 49 Main Flowchart symbols start end Terminal Z=X+Y Computational Step (process) Input X Input / Output X>Y Decision Making Abs(x) Predefined Process 1 2 Connector 50 Flowcharts Control Structures All algorithms can be written T F T using Sequential Structure F Optional Structure.. Repetitive Structure.. T F For I=1 to 10 T T F T T Next I Read length in F F meter F Length in cm = 100 * length in m 51 Flowcharts Guidelines Make it clear and easy to trace. The symbols order needs to be logical. The flow of Arrows needs to be from Up-to-Down and from Left-to-Right. The Computational step has only one in-arrow to it and one out-arrow. The Decision Making step has only one in-arrow and two out-arrows. The Terminals have either one in-arrow and one out-arrow. Use Connectors in large flowcharts. There must be Start and End nodes. 52 Example Start Input A, B X=A Write an algorithm that SUM=0 prints the sum of numbers that are divisible by 5 No starting from a number A X>> What next? csev$ python3 Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwinType "help", "copyright", "credits" or "license" for more information. >>> x = 1 >>> print(x) 1 >>> x = x + 1 This is a good test to make sure that you have >>> print(x) Python correctly installed. Note that quit() also 2 works to end the interactive session. >>> exit() What Do We Say? Elements of Python Vocabulary / Words - Variables and Reserved words (Chapter 2) Sentence structure - valid syntax patterns (Chapters 3-5) Story structure - constructing a program for a purpose Reserved Words You cannot use reserved words as variable names / identifiers False class return is finally None if for lambda continue True def from while nonlocal and del global not with as elif try or yield assert else import pass break except in raise Sentences or Lines x = 2 Assignment statement x = x + 2 Assignment with expression print(x) Print statement Variable Operator Constant Function Programming Paragraphs Python Scripts Interactive Python is good for experiments and programs of 3-4 lines long. 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 a convention, we add “.py” as the suffix on the end of these files to indicate they contain Python. 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 execute 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 is to be repeated. Sometimes we store a set of steps to be used over and over as needed several places throughout the program (Chapter 4). Sequential Steps x=2 Program: Output: print(x) x = 2 print(x) 2 x=x+2 x = x + 2 4 print(x) print(x) When a program is running, it flows from one step to the next. As programmers, we set up “paths” for the program to follow. x=5 Conditional Steps Yes x < 10 ? print('Smaller') Program: No Output: x = 5 Yes if x < 10: Smaller x > 20 ? print('Smaller') Finis if x > 20: print('Bigger') print('Bigger') No print('Finis') print('Finis') n=5 Repeated Steps No Yes Output: n>0? Program: 5 print(n) n = 5 4 while n > 0 : print(n) 3 n = n -1 n = n – 1 2 print('Blastoff!') 1 Blastoff! Loops (repeated steps) have iteration variables that print('Blastoff') change each time through a loop. name = input('Enter file:') Sequential handle = open(name, 'r') Repeated counts = dict() for line in handle: Conditional words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count print(bigword, bigcount) name = input('Enter file:') A short Python “Story” handle = open(name, 'r') about how to count words in a file counts = dict() for line in handle: words = line.split() A word used to read for word in words: data from a user counts[word] = counts.get(word,0) + 1 bigcount = None A sentence about bigword = None updating one of the for word,count in counts.items(): many counts if bigcount is None or count > bigcount: bigword = word bigcount = count A paragraph about how to find the largest item print(bigword, bigcount) in a list Constants Fixed values such as numbers, letters, and strings, are called “constants” because their value does not change Numeric constants are as you expect >>> print(123) String constants use single quotes (') 123 or double quotes (") >>> 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 x = 12.2 x 12.2 y = 14 y 14 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 x = 12.2 x 12.2 100 y = 14 x = 100 y 14 Python Variable Name Rules Must start with a letter or underscore _ Must consist of letters, numbers, and underscores Case Sensitive Good: spam eggs spam23 _speed Bad: 23spam #sign var.12 Different: spam Spam SPAM 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) What is this bit of code doing? x1q3z9ocd = 35.0 a = 35.0 x1q3z9afd = 12.50 b = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b print(x1q3p9afd) print(c) What are these bits of code doing? x1q3z9ocd = 35.0 a = 35.0 x1q3z9afd = 12.50 b = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b print(x1q3p9afd) print(c) hours = 35.0 What are these bits rate = 12.50 of code doing? pay = hours * rate print(pay) Sentences or Lines x = 2 Assignment statement x = x + 2 Assignment with expression print(x) Print statement Variable Operator Constant Function 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 ) A variable is a memory location x 0.6 used to store a value (0.6) 0.6 0.6 x = 3.9 * x * ( 1 - x ) 0.4 The right side is an expression. 0.936 Once the expression is evaluated, the result is placed in (assigned to) x. A variable is a memory location used to store a value. The value stored in a x 0.6 0.936 variable can be updated by replacing the old value (0.6) with a new value (0.936). 0.6 0.6 x = 3.9 * x * ( 1 - x ) 0.4 The right side is an expression. Once the expression is evaluated, the result is placed in (assigned to) the variable on the 0.936 left side (i.e., x). Expressions… Numeric Expressions Operator Operation Because of the lack of mathematical + Addition symbols on computer keyboards - we - Subtraction use “computer-speak” to express the classic math operations * Multiplication / Division Asterisk is multiplication ** Power Exponentiation (raise to a power) looks % Remainder different than in math // Quotient Numeric Expressions >>> xx = 2 >>> jj = 23 >>> xx = xx + 2 >>> kk = jj % 5 Operator Operation >>> print(xx) >>> print(kk) + Addition 4 3 >>> yy = 440 * 12 >>> print(4 ** 3) - Subtraction >>> print(yy) 64 * Multiplication 5280 >>> zz = yy / 1000 4R3 / Division >>> print(zz) 5 23 ** Power 5.28 20 % Remainder 3 // Quotient 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: Parentheses are always respected Parenthesis Power Exponentiation (raise to a power) Multiplication Addition Multiplication, Division, and Remainder Left to Right Addition and Subtraction Left to right 1 + 2 ** 3 / 4 * 5 >>> x = 1 + 2 ** 3 / 4 * 5 >>> print(x) 11.0 1 + 8 / 4 * 5 >>> 1 + 2 * 5 Parenthesis Power Multiplication 1 + 10 Addition Left to Right 11 Operator Precedence Parenthesis Power Remember the rules top to bottom Multiplication Addition When writing code - use parentheses Left to Right 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 What Does “Type” Mean? In Python variables, literals, and constants have a “type” >>> ddd = 1 + 4 >>> print(ddd) Python knows the difference between 5 an integer number and a string >>> eee = 'hello ' + 'there' >>> print(eee) hello there For example “+” means “addition” if something is a number and “concatenate” if something is a string concatenate = put together Type Matters Python knows what “type” >>> eee = 'hello ' + 'there' everything is >>> eee = eee + 1 Traceback (most recent call last): File "", line 1, in Some operations are TypeError: Can't convert prohibited 'int' object to str implicitly >>> type(eee) You cannot “add 1” to a string >>> type('hello') We can ask Python what type >>> type(1) something is by using the type() function >>> Several Types of Numbers >>> xx = 1 Numbers have two main types >>> type (xx) - Integers are whole numbers: >>> temp = 98.6 -14, -2, 0, 1, 100, 401233 >>> type(temp) - Floating Point Numbers have >>> type(1) decimal parts: -2.5 , 0.0, 98.6, 14.0 >>> type(1.0) There are other number types - they are variations on float and integer >>> Type Conversions >>> print(float(99) + 100) 199.0 When you put an integer and >>> i = 42 floating point in an >>> type(i) expression, the integer is implicitly converted to a float >>> f = float(i) >>> print(f) You can control this with the 42.0 >>> type(f) built-in functions int() and float() >>> Integer Division >>> print(10 / 2) 5.0 >>> print(9 / 2) Integer division produces a floating 4.5 point result >>> print(99 / 100) 0.99 >>> print(10.0 / 2.0) 5.0 >>> print(99.0 / 100.0) 0.99 This was different in Python 2.x String >>> sval = '123' >>> type(sval) Conversions >>> print(sval + 1) Traceback (most recent call last): File "", line 1, in TypeError: Can't convert 'int' object to str implicitly You can also use int() and >>> ival = int(sval) float() to convert between >>> type(ival) strings and integers >>> print(ival + 1) 124 You will get an error if the string >>> nsv = 'hello bob' >>> niv = int(nsv) does not contain numeric Traceback (most recent call last): characters File "", line 1, in ValueError: invalid literal for int() with base 10: 'x' User Input We can instruct Python to nam = input('Who are you? ') pause and read data from print('Welcome', nam) the user using the input() function The input() function returns a string Who are you? Chuck Welcome Chuck Converting User Input If we want to read a number from the user, we must inp = input('Europe floor?') convert it from a string to a usf = int(inp) + 1 number using a type print('US floor', usf) conversion function Later we will deal with bad Europe floor? 0 input data 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 # Get the name of the file and open it name = input('Enter file:') handle = open(name, 'r') # Count word frequency counts = dict() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 # Find the most common word bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count # All done print(bigword, bigcount) Summary Type Integer Division Reserved words Conversion between types Variables (mnemonic) User input Operators Comments (#) Operator precedence 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 Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the University of Michigan School of... Information and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Conditions Lecture 3 Sheet #2 Due Friday 18 Oct https://forms.gle/tnFaQKL8Voifkz3e6 x=5 Conditional Steps Yes x < 10 ? No print('Smaller') Program: Output: x = 5 Yes if x < 10: Smaller x > 20 ? print('Smaller') Finis if x > 20: No print('Bigger') print('Bigger') print('Finis') print('Finis') Comparison Operators Boolean expressions ask a Python Meaning question and produce a Yes or No < Less than result which we use to control program flow = Greater than or Equal to comparison operators evaluate to > Greater than True / False or Yes / No != Not equal Comparison operators look at variables but do not change the Remember: “=” is used for assignment. variables http://en.wikipedia.org/wiki/George_Boole Comparison Operators x = 5 if x == 5 : print('Equals 5') Equals 5 if x > 4 : print('Greater than 4') Greater than 4 if x >= 5 : print('Greater than or Equals 5') Greater than or Equals 5 if x < 6 and x > 3: print(Between 3 and 6') Between 3 and 6 Exclusive if x >= 6 or x 2 : print('Bigger than 2') print('Still bigger') print('Done with 2') for i in range(5) : print(i) if i > 2 : print('Bigger than 2') print('Done with i', i) print('All Done') Think About begin/end Blocks x = 5 if x > 2 : print('Bigger than 2') print('Still bigger') print('Done with 2') for i in range(5) : print(i) if i > 2 : print('Bigger than 2') print('Done with i', i) print('All Done') Nested x>1 yes Decisions no print('More than one’) x = 42 if x > 1 : yes print('More than one') x < 100 if x < 100 : no print('Less than 100') print('Less than 100') print('All done') print('All Done') Two-way Decisions x=4 Sometimes we want to do one thing if a logical no yes x>2 expression is true and something else if the expression is false print('Not bigger') print('Bigger') It is like a fork in the road - we must choose one or the other path but print('All Done') not both Two-way Decisions x=4 with else: no yes x = 4 x>2 if x > 2 : print('Bigger') print('Not bigger') print('Bigger') else : print('Smaller') print('All done') print('All Done') Visualize Blocks x=4 no yes x = 4 x>2 if x > 2 : print('Bigger') print('Not bigger') print('Bigger') else : print('Smaller') print('All done') print('All Done') Multi-way yes x0? n = 5 while n > 0 : print(‘Start') print(Start') print(‘End') print(‘End') print(‘Goodbye!') What is wrong with this loop? print(‘Goodbye!') What happens if we start with n = 0? Breaking Out of a Loop The break statement ends the current loop and > hello there jumps to the statement immediately following hello there the loop > hello again It is like a loop test that can happen anywhere hello again in the body of the loop > get me out get me out while True: > hello line = input('> ') hello if line == 'done' : > done break print(line) Goodbye! print(‘Goodbye!') Finishing an Iteration with continue > hello there The continue statement ends the current hello there iteration and jumps to the top of the loop > # hello again and starts the next iteration > # get me out while True: > hello line = input('> ') hello if line == '#' : > hello again continue hello again if line == 'done' : > done break Goodbye! print(line) print(‘Goodbye!') No True ? Yes while True: line=input() line = input('> ') if line == '#' : continue if line == 'done' : continue break print(line) print('Done!') break print(line) print(‘Goodbye’) Summary Comparison operators Nested Decisions == = > < != Multi-way decisions using elif Indentation Starting Loops One-way Decisions Two-way decisions: if: and else: Exercise 1 Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above 40 hours. Enter Hours: 45 Normal Overtime Enter Rate: 10 Rate Rate Pay: 475.0 475 = 40 * 10 + 5 * 15 Overtime Hours Exercise 2 Perform the pay computations for 5 employees, input both hours and rate for each employee then calculate the pay Hours: 45,60,25,90,15 Rate: 10,7,15,30,120 Pay: 475.0,..,..,..,.. Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance... (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Loops and Iteration Lecture 4 Sheet #3 Due Friday 25 Oct https://forms.gle/cD8AzeCrdtxtvuLp8 n=5 Recall: Repeated Steps Output: No Yes Program: n>0? 5 n = 5 4 print(n) while n > 0 : 3 print(n) n = n – 1 2 n = n -1 print(‘Goodbye!') 1 print(n) Goodbye! 0 Loops (repeated steps) have iteration variables that print(Goodbye') change each time through a loop. Often these iteration variables go through a sequence of numbers. n=5 Recall: An Infinite Loop No Yes n>0? n = 5 while n > 0 : print(‘Start') print(Start') print(‘End') print(‘End') print(‘Goodbye!') What is wrong with this loop? print(‘Goodbye!') What happens if we start with n = 0? Recall: Breaking Out of a Loop The break statement ends the current loop and > hello there jumps to the statement immediately following hello there the loop > hello again It is like a loop test that can happen anywhere hello again in the body of the loop > get me out get me out while True: > hello line = input('> ') hello if line == 'done' : > done break print(line) Goodbye! print(‘Goodbye!') Recall: Finishing an Iteration with continue > hello there The continue statement ends the current hello there iteration and jumps to the top of the loop > # hello again and starts the next iteration > # get me out while True: > hello line = input('> ') hello if line == '#' : > hello again continue hello again if line == 'done' : > done break Goodbye! print(line) print(‘Goodbye!') No True ? Yes while True: line=input() line = input('> ') if line == '#' : continue if line == 'done' : continue break print(line) print('Done!') break print(line) print(‘Goodbye’) Indefinite Loops While loops are called “indefinite loops” because they keep going until a logical condition becomes False The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be “infinite loops” Sometimes it is a little harder to be sure if a loop will terminate Definite Loops Quite often we have a list of items of the lines in a file - effectively a finite set of things We can write a loop to run the loop once for each of the items in a set using the Python for construct These loops are called “definite loops” because they execute an exact number of times We say that “definite loops iterate through the members of a set” A Simple Definite Loop 5 for item in [5, 4, 3, 2, 1] : print(item) 4 print(‘Finish !!') 3 2 1 Finish !! A Definite Loop with Strings Happy New Year: Joseph friends = ['Joseph', 'Glenn', 'Sally'] Happy New Year: Glenn for friend in friends : Happy New Year: Sally print('Happy New Year:', friend) print('Done!') Done! A Simple Definite Loop Yes No Done? print(item) 5 for item in [5, 4, 3, 2, 1] : 4 print(item) 3 Move item ahead print('Blastoff!') 2 1 Blastoff! Definite loops (for loops) have explicit iteration variables print('Blast off!') that change each time through a loop. These iteration variables move through the sequence or set. Looking at in... The iteration variable “iterates” through the Five-element sequence (ordered set) sequence Iteration variable The block (body) of code is executed once for each for item in [5, 4, 3, 2, 1] : value in the sequence print(item) The iteration variable moves through all of the values in the sequence No The iteration variable “iterates” Yes Done? print(item) through the sequence (ordered set) Move item ahead The block (body) of code is executed once for each value in the sequence The iteration variable moves through all of the values in the for item in [5, 4, 3, 2, 1] : print(item) sequence item = 5 No print(item) Yes Done? print(item) item = 4 print(item) Move item ahead item = 3 print(item) item = 2 for item in [5, 4, 3, 2, 1] : print(item) print(item) item = 1 print(item) Making “smart” loops Set some variables to initial values for thing in data: The trick is “knowing” something Look for something or about the whole loop when you do something to each are stuck writing code that only entry separately, sees one entry at a time updating a variable Look at the variables Looping Through a Set $ python basicloop.py print('Before') Before for thing in [9, 41, 12, 3, 74, 15] : 9 print(thing) 41 print('After') 12 3 74 15 After Algorithms Set #1: Searching [9, 41, 3, 50, 9, 12, 3, 74, 9, 15, 1, 4, 8] Find an element in a loop with specific value and its index Example: 9 exists in the list at index 0 9 exists in the list at indexes 0, 4, 8 Find all elements greater/smaller than a value Example: elements greater than 30 are 41, 50 and 74 Find count of elements with a specific value Example: 9 exists three times in the list Searching for a value $ python search1.py >> Find: 3 found = False x = int(input(‘Find: ‘)) Before False print('Before', found) False 9 for value in [9, 41, 12, 3, 74, 15] : False 41 if value == x : False 12 found = True True 3 print(found, value) True 74 print('After', found) True 15 After True If we just want to search and know if a value was found, we use a variable that starts at False and is set to True as soon as we find what we are looking for. Searching for a value found = False Self Study left for Students: x = int(input(‘Find: ‘)) print('Before', found) Modify the program to for value in [9, 41, 12, 3, 74, 15] : - Find the index as well if value == x : found = True - Find all indexes of it print(found, value) - Find numbers greater or smaller print('After', found) - How many times the value exists Algorithms Set #2: Counting [9, 41, 3, 50, 9, 12, 3, 74, 9, 15, 1, 4, 8] Count the numbers in this list Example: count of the elements is 13 Sum the numbers in this list Example: summation of the elements is 238 Find the average of numbers in this list Example: average of the elements is 18.3 Counting in a Loop $ python countloop.py count = 0 Before 0 print('Before', count) 19 for thing in [9, 41, 12, 3, 74, 15] : 2 41 count = count + 1 print(count, thing) 3 12 print('After’, count) 43 5 74 6 15 After 6 To count how many times we execute a loop, we introduce a counter variable that starts at 0 and we add one to it each time through the loop. Counting in a Loop count = 0 print('Before', count) Self Study left for Students: for thing in [9, 41, 12, 3, 74, 15] : count = count + 1 Modify the program to print(count, thing) - Sum the numbers print('After’, count) - Find the average - Find numbers larger than average Algorithms Set #3: Max/Min [9, 41, 3, 50, 9, 12, 3, 74, 9, 15, 1, 4, 8] What is the maximum number in the list Example: the maximum number in the list is 74 at index 7 What is the minimum number in the list Example: the minimum number in the list is 1 at index 10 Finding the Largest Value $ python largest.py largest_so_far = -1 Before -1 print('Before', largest_so_far) for the_num in [9, 41, 12, 3, 74, 15] : 9 9 if the_num > largest_so_far : 41 41 largest_so_far = the_num 41 12 print(largest_so_far, the_num) 41 3 74 74 print('After', largest_so_far) 74 15 After 74 We make a variable that contains the largest value we have seen so far. If the current number we are looking at is larger, it is the new largest value we have seen so far. Finding the Largest Value largest_so_far = -1 print('Before', largest_so_far) for the_num in [9, 41, 12, 3, 74, 15] : Self Study left for Students : if the_num > largest_so_far : Modify the program to largest_so_far = the_num - Find the index of the largest value print(largest_so_far, the_num) - Find the smallest value print('After', largest_so_far) - Find the most repeated number Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance... (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Nested Loops Output: Loops can be nested, i.e. you can repeat steps with repeated steps. What if you want to print a square as shown Nested Loops Output: # Drawing a square using nested loops side_length = 5 for i in range(side_length): for j in range(side_length): print("*", end = '') print() Nested Loops Output: # Drawing a triangle using nested loops for i in range(1, side_length + 1): for j in range(1, i + 1): print("*", end=" ") print() # Newline after each row Nested Loops # Drawing a triangle using nested loops Output: height =5 for i in range(1, height + 1): for j in range(1, height -i + 1): print (" " ,end='') for k in range(0, 2 *i -1 ): print ("*" ,end='') print() Nested Loops # Multiplication Table (1 to 5) for i in range(1, 6): Output: for j in range(1, 6): print(i * j, end="\t") print() # Newline after each row Nested Loops ❖ Sorting a list of numbers is an example of using a nested loop. ❖ Bubble Sort is the simplest sorting algorithm. ❖ Works by repeatedly swapping the adjacent elements if they are in the wrong order. Nested Loops arr= [64, 34, 25, 12, 22, 11, 90] Lists and Strings next lecture n = len(arr) # Traverse through all array elements for i in range(n-1): # Last i elements are already sorted, so no need to check them for j in range(0, n - i - 1): # Swap if the element found is greater than the next element if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] print("Sorted list:", arr) Summary While loops (indefinite) For loops (definite) Infinite loops Iteration variables Using break Loop idioms Using continue Largest or smallest None constants and variables Nested Loops Strings & Lists Lecture 5 Sheet #4 Due Friday Nov. 1st https://forms.gle/Vaw7khLQ6TSJziFt7 String Data Type >>> str1 = "Hello" >>> str2 = 'there' >>> bob = str1 + str2 >>> print(bob)) A string is a sequence of characters Hellothere >>> str3 = '123' A string literal uses quotes >>> str3 = str3 + 1 'Hello' or "Hello" Traceback (most recent call last): File "", line 1, For strings, + means “concatenate” in TypeError: cannot concatenate When a string contains numbers, it is 'str' and 'int' objects still a string >>> x = int(str3) + 1 >>> print(x)) 124 We can convert numbers in a string >>> into a number using int() Reading and >>> name = input('Enter:') Enter:Chuck Converting >>> print(name) Chuck >>> apple = input('Enter:') We prefer to read data in using Enter:100 strings and then parse and >>> x = apple – 10 convert the data as we need Traceback (most recent call last): File "", line 1, This gives us more control over in error situations and/or bad user TypeError: unsupported operand input type(s) for -: 'str' and 'int' >>> x = int(apple) – 10 Input numbers must be >>> print(x) converted from strings 90 Looking Inside Strings We can get at any single character in a b a n a n a string using an index specified in 0 1 2 3 4 5 square brackets >>> fruit = 'banana' The index value must be an integer >>> >>> letter = fruit print(letter) and starts at zero a >>> x = 3 The index value can be an expression >>> w = fruit[x - 1] that is computed >>> print(w) n A Character Too Far You will get a python error >>> zot = 'abc' >>> print(zot) if you attempt to index Traceback (most recent call beyond the end of a string last): File "", line 1, in So be careful when IndexError: string index out constructing index values of range and slices >>> Strings Have Length b a n a n a The built-in function len gives 0 1 2 3 4 5 us the length of a string >>> fruit = 'banana' >>> print(len(fruit)) 6 len Function >>> fruit = 'banana' A function is some stored >>> x = len(fruit) code that we use. A >>> print(x) function takes some 6 input and produces an output. 'banana' len() 6 (a number) (a string) function Looping Through Strings Using a while statement, fruit = 'banana' 0b an iteration variable, and index = 0 1a the len function, we can while index < len(fruit): 2n letter = fruit[index] 3a construct a loop to look at print(index, letter) each of the letters in a 4n index = index + 1 string individually 5a Looping Through Strings A definite loop using a b for statement is much a fruit = 'banana' more elegant n for letter in fruit: a The iteration variable is print(letter) n completely taken care of a by the for loop Looping Through Strings A definite loop using a fruit = 'banana' for letter in fruit : b for statement is much a print(letter) more elegant n a The iteration variable is index = 0 n completely taken care of while index < len(fruit) : a by the for loop letter = fruit[index] print(letter) index = index + 1 Looping and Counting word = 'banana' This is a simple loop that count = 0 loops through each letter in a for letter in word : string and counts the number if letter == 'a' : of times the loop encounters count = count + 1 the 'a' character print(count) More String Operations Slicing Strings M o n t y P y t h o n 0 1 2 3 4 5 6 7 8 9 10 11 We can also look at any continuous section of a string using a colon operator >>> s = 'Monty Python' >>> print(s[0:4]) The second number is one Mont beyond the end of the slice - >>> print(s[6:7]) “up to but not including” P >>> print(s[6:20]) If the second number is Python beyond the end of the string, it stops at the end Slicing Strings M o n t y P y t h o n 0 1 2 3 4 5 6 7 8 9 10 11 >>> s = 'Monty Python' If we leave off the first number >>> print(s[:2]) or the last number of the slice, Mo it is assumed to be the >>> print(s[8:]) beginning or end of the string thon respectively >>> print(s[:]) Monty Python String Concatenation >>> a = 'Hello' >>> b = a + 'There' When the + operator is >>> print(b) applied to strings, it means HelloThere “concatenation” >>> c = a + ' ' + 'There' >>> print(c) Hello There >>> Lists Python Collections There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable. Allows duplicate members. Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members. Dictionary is a collection which is ordered** and changeable. No duplicate members. What is Not a “Collection”? Most of our variables have one value in them - when we put a new value in the variable, the old value is overwritten $ python >>> x = 2 >>> x = 4 >>> print(x) 4 A List is a Kind of Collection A collection allows us to put many values in a single “variable” A collection is nice because we can carry all many values around in one convenient package. friends = [ 'Joseph', 'Glenn', 'Sally' ] carryon = [ 'socks', 'shirt', 'perfume' ] List Constants List constants are surrounded by >>> print([1, 24, 76]) [1, 24, 76] square brackets and the elements >>> print(['red', 'yellow', in the list are separated by 'blue']) commas ['red', 'yellow', 'blue'] >>> print(['red', 24, 98.6]) A list element can be any Python ['red', 24, 98.6] >>> print([ 1, [5, 6], 7]) object - even another list [1, [5, 6], 7] >>> print([]) A list can be empty [] We Already Use Lists! 5 for i in [5, 4, 3, 2, 1] : print(i) 4 print('finish!') 3 2 1 finish! Lists and Definite Loops - Best Pals friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : Happy New Year: Joseph print('Happy New Year:', friend) print('Done!') Happy New Year: Glenn Happy New Year: Sally Done! z = ['Joseph', 'Glenn', 'Sally'] for x in z: print('Happy New Year:', x) print('Done!') Properties of Lists 1. List items are ordered, changeable, and allow duplicate values. 2. List items are indexed, the first item has index , the second item has index etc. 3. Ordered, when we say that lists are ordered, it means that the items have a defined order, and that order will not change. 4. If you add new items to a list, the new items will be placed at the end of the list. Looking Inside Lists Just like strings, we can get at any single element in a list using an index specified in square brackets >>> friends = [ 'Joseph', 'Glenn', 'Sally' ] Joseph Glenn Sally >>> print(friends) Glenn 0 1 2 >>> How Long is a List? The len() function takes a list as a >>> greet = 'Hello Bob' parameter and returns the number >>> print(len(greet)) of elements in the list 9 >>> x = [ 1, 2, 'joe', 99] Actually len() tells us the number of >>> print(len(x)) elements of any set or sequence 4 (such as a string...) >>> Concatenating Lists Using + >>> a = [1, 2, 3] We can create a new list >>> b = [4, 5, 6] by adding two existing >>> c = a + b >>> print(c) lists together [1, 2, 3, 4, 5, 6] >>> print(a) [1, 2, 3] Is Something in a List? >>> some = [1, 9, 21, 10, 16] Python provides two operators >>> 9 in some that let you check if an item is True in a list >>> 15 in some False These are logical operators >>> 20 not in some that return True or False True >>> They do not modify the list Built-in Functions and Lists >>> nums = [3, 41, 12, 9, 74, 15] There are a number of >>> print(len(nums)) functions built into Python 6 that take lists as >>> print(max(nums)) parameters 74 >>> print(min(nums)) Remember the loops we 3 >>> print(sum(nums)) built? These are much 154 simpler. >>> print(sum(nums)/len(nums)) 25.6 append Function To add an item to the end of the list, use the append() method: Example: Using the append() method to append an item: thislist = ["apple", "banana", "cherry"] thislist.append("orange") print(thislist) Output: ['apple', 'banana', 'cherry', 'orange'] Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance... (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Dictionaries Lecture 6 Sheet 5 Friday Nov. 8th https://forms.gle/AL1jkHm2iQzKm6TY7 What is a Collection? A collection is nice because we can put more than one value in it and carry them all around in one convenient package We have a bunch of values in a single “variable” We do this by having more than one place “in” the variable We have ways of finding the different places in the variable A Story of Two Collections.. List - A linear collection of values that stay in order Dictionary - A “bag” of values, each with its own label Dictionaries Lists index their entries >>> purse = dict() based on the position in the >>> purse['money'] = 12 >>> purse['candy'] = 3 list >>> purse['tissues'] = 75 >>> print(purse) {'money': 12, 'tissues': 75, 'candy': 3} Dictionaries are like bags - >>> print(purse['candy']) no order 3 >>> purse['candy'] = purse['candy'] + 2 >>> print(purse) So we index the things we {'money': 12, 'tissues': 75, 'candy': 5} put in the dictionary with a “lookup tag” Comparing Lists and Dictionaries Dictionaries are like lists except that they use keys instead of numbers to look up values >>> lst = list() >>> ddd = dict() >>> lst.append(21) >>> ddd['age'] = 21 >>> lst.append(183) >>> ddd['course'] = 182 >>> print(lst) >>> print(ddd) [21, 183] {'course': 182, 'age': 21} >>> lst = 23 >>> ddd['age'] = 23 >>> print(lst) >>> print(ddd) [23, 183] {'course': 182, 'age': 23} >>> lst = list() List >>> lst.append(21) >>> lst.append(183) Key Value >>> print(lst) 21 [21, 183] lst >>> lst = 23 183 >>> print(lst) [23, 183] >>> ddd = dict() Dictionary >>> ddd['age'] = 21 >>> ddd['course'] = 182 Key Value >>> print(ddd) {'course': 182, 'age': 21} ['course'] 182 >>> ddd['age'] = 23 ddd >>> print(ddd) ['age'] 21 {'course': 182, 'age': 23} Dictionary Literals (Constants) Dictionary literals use curly braces and have a list of key : value pairs You can make an empty dictionary using empty curly braces >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> print(jjj) {'jan': 100, 'chuck': 1, 'fred': 42} >>> ooo = { } >>> print(ooo) {} >>> Example: Most Common Name? Most Common Name in these names? marquard cwen cwen zhen marquard zhen csev csev zhen marquard zhen csev zhen Most Common Name? marquard cwen cwen zhen marquard zhen csev csev zhen marquard zhen csev zhen Many Counters with a Dictionary Key Value One common use of dictionaries is counting how often we “see” something >>> ccc = dict() >>> ccc['csev'] = 1 >>> ccc['cwen'] = 1 >>> print(ccc) {'csev': 1, 'cwen': 1} >>> ccc['cwen'] = ccc['cwen'] + 1 >>> print(ccc) {'csev': 1, 'cwen': 2} Dictionary Tracebacks It is an error to reference a key which is not in the dictionary We can use the in operator to see if a key is in the dictionary >>> ccc = dict() >>> print(ccc['csev']) Traceback (most recent call last): File "", line 1, in KeyError: 'csev' >>> 'csev' in ccc When We See a New Name When we encounter a new name, we need to add a new entry in the dictionary and if this the second or later time we have seen the name, we simply add one to the count in the dictionary under that name counts = dict() names = ['csev', 'cwen', 'csev', 'zqian', 'cwen'] for name in names : if name not in counts: {'csev': 2, 'zqian': 1, 'cwen': 2} counts[name] = 1 else : counts[name] = counts[name] + 1 print(counts) Definite Loops and Dictionaries Even though dictionaries are not stored in order, we can write a for loop that goes through all the entries in a dictionary - actually it goes through all of the keys in the dictionary and looks up the values >>> counts = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> for key in counts:... print(key, counts[key])... jan 100 chuck 1 fred 42 >>> Retrieving Lists of Keys and Values >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} You can get a list >>> print(list(jjj)) ['jan', 'chuck', 'fred'] of keys, values, or >>> print(list(jjj.keys())) items (both) from ['jan', 'chuck', 'fred'] a dictionary >>> print(list(jjj.values())) [100, 1, 42] >>> print(list(jjj.items())) [('jan', 100), ('chuck', 1), ('fred', 42)] >>> What is a “tuple”? - coming soon... Bonus: Two Iteration Variables! We loop through the key-value pairs in a jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} dictionary using *two* for aaa,bbb in jjj.items() : print(aaa, bbb) iteration variables aaa bbb Each iteration, the first [jan] 100 jan 100 variable is the key and chuck 1 [chuck] 1 fred 42 the second variable is the corresponding [fred] 42 value for the key Tuples Tuples Are Like Lists Tuples are another kind of sequence that functions much like a list - they have elements which are indexed starting at 0 >>> x = ('Glenn', 'Sally', 'Joseph') >>> for iter in y: >>> print(x)... print(iter) Joseph... >>> y = ( 1, 9, 2 ) 1 >>> print(y) 9 (1, 9, 2) 2 >>> print(max(y)) >>> 9 Constructing Tuples using Literals In Python, tuples are ordered, which means that they keep their elements in the original insertion order. >>> record = ("John", 35, "Python Developer") >>> record ('John', 35, 'Python Developer’) Here we create tuples as a series of comma-separated values surrounded by a pair of parentheses: (item_0, item_1,..., item_n) >>> jane = ("Jane Doe", 25, 1.75, "Canada") >>> point = (2, 7) >>> pen = (2, "Solid", True) Accessing Items in Tuple The items in this tuple are objects of different data types representing a record of data from a database table. If you access the tuple object, then you’ll see that the data items keep the same original insertion order. This order remains unchanged during the tuple’s lifetime. You can access individual objects in a tuple by position, or index. These indices start from zero: >>> record 'John' >>> record 35 >>> record 'Python Developer' Constructing Tuples using List Another way is to use tuple([iterable]) Here are a few examples of how to use the tuple() constructor: >>> tuple(["Jane Doe", 25, 1.75, "Canada"]) ('Jane Doe', 25, 1.75, 'Canada') >>> tuple("Pythonista") ('P', 'y', 't', 'h', 'o', 'n', 'i', 's', 't', 'a') Constructing Tuples using Dictionary Another way is to use tuple([iterable]) Here are a few examples of how to use the tuple() constructor: >>> tuple({... "manufacturer": "Boeing",... "model": "747",... "passengers": 416,}.values()) ('Boeing', '747', 416) >>> tuple() () but... Tuples are “immutable” Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string >>> x = [9, 8, 7] >>> y = 'ABC' >>> z = (5, 4, 3) >>> x = 6 >>> y = 'D' >>> z = 0 >>> print(x) Traceback:'str' Traceback:'tuple' >>>[9, 8, 6] object does object does >>> not support item not support item Assignment Assignment >>> >>> Things not to do With Tuples >>> x = (3, 2, 1) >>> x.sort() Traceback: AttributeError: 'tuple' object has no attribute 'sort' >>> x.append(5) Traceback: AttributeError: 'tuple' object has no attribute 'append' >>> x.reverse() Traceback: AttributeError: 'tuple' object has no attribute 'reverse' >>> Tuples are More Efficient Since Python does not have to build tuple structures to be modifiable, they are simpler and more efficient in terms of memory use and performance than lists So in our program when we are making “temporary variables” we prefer tuples over lists Tuples and Assignment We can also put a tuple on the left-hand side of an assignment statement We can even omit the parentheses >>> (x, y) = (4, 'fred') >>> print(y) fred >>> (a, b) = (99, 98) >>> print(a) 99 Tuples and Dictionaries >>> d = dict() >>> d['csev'] = 2 >>> d['cwen'] = 4 The items() method >>> for (k,v) in d.items(): in dictionaries returns... print(k, v) a list of (key, value)... csev 2 tuples cwen 4 >>> tups = d.items() >>> print(tups) dict_items([('csev', 2), ('cwen', 4)]) Tuples are Comparable The comparison operators work with tuples and other sequences. If the first item is equal, Python goes on to the next element, and so on, until it finds elements that differ. >>> (0, 1, 2) < (5, 1, 2) True >>> (0, 1, 2000000) < (0, 3, 4) True >>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam') True >>> ( 'Jones', 'Sally') > ('Adams', 'Sam') True Handling Errors & Users Mistakes The try / except Structure 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 x = 'Hello Bob’ y = int(x) print('First’, y) w = '123’ v = int(w) print('Second’, v) $ python3 myprogram.py Traceback (most recent call last): File “myprogram.py", line 2, in istr = int(astr)ValueError: invalid literal for int() with base 10: 'Hello Bob' x = 'Hello Bob’ y = int(x) The program stops here print('First’, y) w = '123’ v = int(w) print('Second’, v) $ python3 myprogram.py Traceback (most recent call last): File “myprogram.py", line 2, in y = int(x) ValueError: invalid literal for int() with base 10: 'Hello Bob' x = 'Hello Bob' When the first conversion fails - it try: just drops into the except: clause y = int(x) and the program continues. except: y = -1 $ python tryexcept.py print('First’, y) First -1 Second 123 w = '123' try: v = int(w) except: v = -1 When the second conversion succeeds - it just skips the except: print('Second’, v) clause and the program continues. try / except x = 'Bob' print('Hello') x = 'Bob' try: print('Hello') y = int(x) y = int(x) print('There') except: print('There') y = -1 y = -1 print('Done’, y) print('Done’, y) Safety net Sample try / except n = input('Enter a number:') try: v = int(n) $ python3 trynum.py except: Enter a number:42 v = -1 Nice work $ python3 trynum.py if v > 0 : Enter a number:forty-two print('Nice work') Not a number else: $ print('Not a number') Exercise 2 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 Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance... (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information