CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007
Course Web Site http://www.nps.navy.mil/cs/facultypages/squire/cs2900 All course related materials will be posted there Syllabus Notes Copies of the text Examples K. Squire - LtCol J. Young - CS2900 2
Text How to Think like a Computer Scientist Python and C++ versions Available here: http://www.greenteapress.com/ Order it if you like Download pdf or html version We will cover most of chapters 1-8 before moving on to C++ K. Squire - LtCol J. Young - CS2900 3
Other References The definitive source http://docs.python.org/ref/ Other documentation http://docs.python.org/ http://www.python.org/doc/ K. Squire - LtCol J. Young - CS2900 4
Reading Please read the Foreword and Preface Provide interesting insight into the language selection rationale Chapters 1 and 2 K. Squire - LtCol J. Young - CS2900 5
Introduction Introduction to Computer Programming Introduction Introductory programming with Python Introduction to C++ Assumes no prior programming experience K. Squire - LtCol J. Young - CS2900 6
Programming Languages Various categories/subcategories High Level Languages Compiled C/C++, Ada, Fortran, Interpreted Perl, Ruby, Python, Basic, Hybrid Java, C#, Assembly Language Machine Language Low Level Languages K. Squire - LtCol J. Young - CS2900 7
Machine Language The lowest level a programmer can use Computer engineers may go even lower The ONLY language a CPU understands Unique to each class of CPU Ones and Zeros They represent the Ons and Offs or High and Low voltages used by the transistors within a computer K. Squire - LtCol J. Young - CS2900 8
Machine Language (cont) Different sequences of 1s and 0s have different meanings Assigned by the designers of the CPU A small program, how readable is this? 0011000000111000 0000000100000000 1101000001111000 0000000100000010 0011000111000000 0000000100000100 Very tough to find errors K. Squire - LtCol J. Young - CS2900 9
Assembly Language Human readable form of machine language Each meaningful sequence of 1s and 0s is assigned a name called a mnemonic Easier for humans to remember Same program in Motorola 68000 Assembly MOVE BASEPAY, D0 ADD OVERTIME, D0 MOVE D0, GROSSPAY K. Squire - LtCol J. Young - CS2900 10
Assembly Language (cont) Easier to find errors Like machine language, assembly language unique to each CPU Not understood by CPU Because it is really just text A special program called an assembler translates assembly language into 1s and 0s The first assembler had to be written in machine language! K. Squire - LtCol J. Young - CS2900 11
High Level Languages Many different types Attempt to be native language like Closer to english than assembly Independent of CPU Some type of program must translate your program into assembly/machine language before it can run GrossPay = BasePay + Overtime; K. Squire - LtCol J. Young - CS2900 12
High Level Languages (cont) Three main types Compiled C++, Pascal, Ada, Fortran, Cobol, Interpreted Lisp, Basic, Perl, Python, Hybrid Java, C#, In all cases, the author enters text containing programming statements that conform to a specific language K. Squire - LtCol J. Young - CS2900 13
Compiled Languages A program called a compiler translates high level statements into assembly/machine language Think of a compiler as an assembler on steroids The ultimate output of the compilation process is what we often called an executable file The executable is a machine language equivalent If a programmer makes a change to a program, it must be re-compiled before the changes can take effect K. Squire - LtCol J. Young - CS2900 14
Compiled Languages (cont) cpu independent cpu dependent Program File (text) Compiler (machine language) Executable File (machine language) Operating System CPU K. Squire - LtCol J. Young - CS2900 15
Interpreted Languages A machine language version of the program is never generated A special program called an interpreter carries out a program s steps one at a time The interpreter is a machine language program It provides a layer of insulation between the programmer and the CPU Any change to a program takes affect the next time the program is interpreted K. Squire - LtCol J. Young - CS2900 16
Interpreted Languages (cont) cpu independent cpu dependent Program File (text) Interpreter (machine language) Operating System CPU K. Squire - LtCol J. Young - CS2900 17
Hybrid Languages Compiled but NOT to machine language Compiler generates an intermediate language In the case of Java, we call this Java Byte Code The intermediate language file is then interpreted In the case of Java, the interpreter is called the Java Virtual Machine The virtual machine is like a software CPU Compiled programs can run on any CPU for which a virtual machine exists K. Squire - LtCol J. Young - CS2900 18
Hybrid Languages (cont).java file.class file cpu independent Program File (text) Intermediate File (intermediate language) cpu dependent Compiler (machine language) Interpreter (machine language) java Operating System javac CPU K. Squire - LtCol J. Young - CS2900 19
Things For You To Do Windows users Download and install cygwin, making sure you install the Python package. Unix/Mac users Make sure you have a Python interpreter for your flavor of Unix/Mac Good starting point for all things Python http://www.python.org/download/ Windows users, we recommend cygwin s Python over the standalone Python offered here K. Squire - LtCol J. Young - CS2900 20
Editing Programs Program text (also called source code) is just that, text As such it can be edited with ANY text editor Most python installations come with an editor named IDLE Allow you to run python programs from within the editor The combination of editing features with execution capabilities is often called an Integrated Development Environment or IDE for short K. Squire - LtCol J. Young - CS2900 21
Interactive vs. Batch Execution Or, as the text calls it command line vs. script mode Interactive mode Enter your program statements one at a time at a command prompt Each statement is processed after you type it Batch mode Enter your entire program into a text file Invoke the interpreter to process statements from your file rather than from the command line K. Squire - LtCol J. Young - CS2900 22
Getting Started A simple Python program (interactive mode) # python Shell prompt Command to invoke Python interpreter Python 2.4.4 (#1, Oct 23 2006, 13:58:00) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print 'Welcome to Python' Welcome to Python >>> Python interpreter prompt Version info Python statement Statement output K. Squire - LtCol J. Young - CS2900 23
Batch Mode Example Use a text editor (notepad, vi, ) to create a file (welcome.py) containing the single line print 'Welcome to Python' Sample run # python welcome.py Welcome to Python # K. Squire - LtCol J. Young - CS2900 24
Additional Resources http://www.python.org http://www.python.org/doc/ http://www.python.org/about/gettingstarted/ K. Squire - LtCol J. Young - CS2900 25
What is a Program From the text A program is a sequence of instructions that specifies how to perform a computation Generally composed of statements that Perform input or output (keyboard, disk, network, ) Perform a computation (mathematical or otherwise) Conditionally perform some actions as a result of a test (if it is raining, stand on your head) Repeat some action (As long as you are not tired run around in circles) K. Squire - LtCol J. Young - CS2900 26
Learning to Program Involves Learning the statements allowed by the language and correct ways to link them together The previous example shows a simple use of the print statement Learning how to manipulate data using those statements The previous example outputs the string data "Welcome to Python" K. Squire - LtCol J. Young - CS2900 27
Learning to Program also involves Learning how to recognize and correct mistakes Three broad categories of errors in programming Syntax errors Semantic errors Runtime errors K. Squire - LtCol J. Young - CS2900 28
Syntax Errors The programming equivalent of a typo The compiler/interpreter fails to recognize something as a valid statement in the language These prevent a program from running and must be corrected before moving on Compilers/interpreters often do their best to show you the problem Their best may not help you at all They can t guess your intent K. Squire - LtCol J. Young - CS2900 29
Semantic Errors A valid program does not always do what you want Computers only do what you tell them to do, not always what you wanted them to do If you fail to properly express yourself you will often be surprised by the results K. Squire - LtCol J. Young - CS2900 30
Runtime Errors Generally the result of some problem that occurs during program execution May result from something as drastic as hardware failures to something as simple as failing to check the validity of a user input How might a program behave if it asks for a number but you enter a letter? K. Squire - LtCol J. Young - CS2900 31
Debugging Debugging is the act of locating and correcting all semantic errors and understanding and properly reacting to the cause of any runtime errors you may encounter As such, debugging centers around observing/understanding the behavior of a running program K. Squire - LtCol J. Young - CS2900 32
What s Next The remainder of the course deals with how to put these pieces together Defining/describing/manipulating data Defining functions What functions do for us How to interact with functions Finding and fixing problems with our programs Software reuse Leveraging the work of others to make your life easier K. Squire - LtCol J. Young - CS2900 33
A Note Please don t ever judge the quality of a programming language by the simplicity of the Hello World program! K. Squire - LtCol J. Young - CS2900 34
Reading Please continue with Text chapter 3 Text chapter 4 K. Squire - LtCol J. Young - CS2900 35
Data No useful program exists without data Programmer s main challenge Identify data requirements Model appropriate data Define relationships between data Define interactions with data Obtain data Display/store data K. Squire - LtCol J. Young - CS2900 36
Some Common Data Values Numbers Integers: -1, 0, 1, Floating point: 3.14159 Strings Sequences of characters: "Hello World!" How many characters in the string above? Enclosed in single or double quotes Let's use double quotes as a convention, many other languages do K. Squire - LtCol J. Young - CS2900 37
Literals A literal is a specific instance of a type of data The examples on the previous slide were literal integers, floating point numbers, and strings If something is not a literal what is it? K. Squire - LtCol J. Young - CS2900 38
Variables Variables are symbolic names given to program items that may take on many values during program execution Similar to the variables you may be familiar with from mathematical expressions y = 10x + 15 (not a Python statement!!!) y and x are variables in the expression above 10 and 15 are literals K. Squire - LtCol J. Young - CS2900 39
Choosing Variable Names Programmers can choose (almost) any name they like to represent their data items Restrictions Names consist only of letters, numbers, and the underscore character Names can only begin with a letter or an underscore Python has a set of reserved words or keywords, none of which can be used as variable names (see text p. 14) K. Squire - LtCol J. Young - CS2900 40
Example Variable Names x name daysperyear (preferred for multi-word) months_per_year _total What values are associated with these variables? In the interpreter try: print x K. Squire - LtCol J. Young - CS2900 41
What Can You Store in Variables? In python, almost anything you want The interpreter keeps track of the type of data that a variable is representing at any given moment Try >>> z = 3 >>> type (z) >>> z = "hello" >>> type (z) K. Squire - LtCol J. Young - CS2900 42
Assignment The act of assigning a value to a variable You can t assign a value to a literal can you? One of the simplest of Python s statements Indicated using the = operator Examples x = 3 name = "John" daysperweek = 7 r = x Now what happens if you print x? How about r? K. Squire - LtCol J. Young - CS2900 43
Statements From the text A statement is an instruction that the Python interpreter can execute Statements typically carry out some action, and may or may not produce a visible result You have seen two statements so far print statement Assignment statement K. Squire - LtCol J. Young - CS2900 44
Operators Operators are one of the fundamental building blocks of expressions and statements Instruct the interpreter to perform a specific operation on one or more pieces of data (operands) K. Squire - LtCol J. Young - CS2900 45
Arithmetic Operators Addition/Subtraction: + - x + y 3 Multiplication/Division: * / z * 20 / g Exponentiation: ** 2 ** 8 Modulus: % 9 % 6 Parenthesis can be used to override operator precedence (see section 2.7 p 16) K. Squire - LtCol J. Young - CS2900 46
Important Note on Division Division of integers yields an integer Try: 16 / 5 Try: 16.0 / 5 The results of integer division are TRUNCATED NOT ROUNDED The // operator forces integer division >>> 7 // 3.0 2.0 K. Squire - LtCol J. Young - CS2900 47
How About Strings? Consider "3" + "6" "3" + 6 "3" * "6" "3" * 6 "Addition" of two strings performs string concatenation "Multiplication" of a string by an integer performs string repetition K. Squire - LtCol J. Young - CS2900 48
Relational Operators Used to compare two values, result is either True or False (Section 4.2) Test for equality: == x == 3 Common mistake is to forget an = x = 3 is very different Test for inequality:!= a!= b response!= "quit" K. Squire - LtCol J. Young - CS2900 49
More Relational Operators Greater than: > month > 7 Greater than or equal: >= day >= "tuesday" Less than: < "Help" < "help" Less than or equal: <= percent <= 90 K. Squire - LtCol J. Young - CS2900 50
Expressions Expressions are programming constructs whose evaluation yields a value Simple expressions 1 + 2 3 * 4 / 9 7.2 "Just a string" color == "red" K. Squire - LtCol J. Young - CS2900 51
Types of Expressions Arithmetic Expressions Yield a numeric value Boolean Expressions Yield a truth value (True/False, note the capitalization here, it is important!!) K. Squire - LtCol J. Young - CS2900 52
Logical Operators (4.3) Applied to one or more boolean expressions and, or, not These also happen to be keywords and, or are binary operators Take two boolean operands (a!= b) or (c < d) Results according to appropriate truth table not is a unary operator Result is boolean negation not (response == "yes") K. Squire - LtCol J. Young - CS2900 53
Dirty Little Secret Strictly speaking, when evaluating logical expressions python treats ANY non-zero value as True and 0/False as False Try the following "hello" and "cat" 1 and 9 1 and "jump" 0 and "crazy" "don't do this" and 0 K. Squire - LtCol J. Young - CS2900 54
Bitwise Operators Integers only Four operations Bitwise compliment (~), Unary operator a = ~b Bitwise And (&) a = b & c Bitwise Or ( ) a = b c Bitwise Exclusive Or (^) a = b ^ c K. Squire - LtCol J. Young - CS2900 55
Shift Operators Used to shift the bits in an integer right or left Left shift value << count value is shifted left count bits Same effect as: value * (2 ** count) Right shift value >> count value is shifted right count bits Similar effect to: value / (2 ** count) K. Squire - LtCol J. Young - CS2900 56
Interactive vs. Batch Revisited When you using python interactively, the interpreter will evaluate and display the result of any expression that you enter Python 2.4.3 (#1, May 18 2006, 07:40:45) [GCC 3.3.3 (cygwin special)] on cygwin >>> 9 * 18 / 2 + 3 84 However when executed in batch mode, the same statement, while legal will produce no output K. Squire - LtCol J. Young - CS2900 57
Comments When developing anything more than a trivial program, it is often nice to include non-executing comments within your program files to tell others just what you were thinking when you developed a particular section of code Comments are introduces by the # character and instruct the interpreter to ignore the remainder of the line K. Squire - LtCol J. Young - CS2900 58
Comment Example In the interpreter try >>> print "Hello" # print a simple message Note that the only output is: Hello The interpreter has ignored the comment Comments can occupy lines by themselves # We could provide a very detailed # explanation of an algorithm that we are # implementing so that others can easily # follow along and potentially modify # our program if they find an error K. Squire - LtCol J. Young - CS2900 59