2 Three Rules of Programming Rule 1: Think before you programRule 2: A program is a human-readable set of instructions that solve a problem and can be executed on a computerRule 3: The best way to improve your programming and problem solving skills is to practice.
3 A program is a sequence of instructions. To run a program is to: Computer ProgramsA program is a sequence of instructions.To run a program is to:Create the sequence of instructions according to your design and the language rulesTurn that program into the binary code that the computer understandsGive the binary code to the Operating System (OS), so it can pass it to the processor for executionOS and processor together, execute the program
5 Python is an interpreted language Interpreted means that Python looks at each instruction, one at a time, and translate it into machine language.That allows you to enter instructions one-at-a-time.You can also create a file with several instructions called a script, load it, and execute all the instruction one after the other.To rerun an script, reload it.
7 Two ways to work: Interactive and scripting One of the benefits of working with an interpreted language is that you can test bits of code in interactive mode before you put them in a script.But there are differences between interactive mode and script mode that can be confusing.
8 For example, if you are using Python as a calculator, you might type Interactive modeFor example, if you are using Python as a calculator, you might type>>> miles = 26.2>>> miles * 1.6142.182
9 Scripting modeBut if you type the same code into a script and run it, you get no output at all.In script mode an expression, all by itself, has no visible effect.Python actually evaluates the expression, but it doesn’t display the value unless you tell it to do so:miles = 26.2print miles * 1.61
12 One thing we did was to import the math module with import math Import of MathOne thing we did was to import the math module with import mathThis imported python math statementsWe precede all operations of math with math.OPERATIONe.g. math.pi, math.pow(x, y)
13 Getting InputThe function:input(“Give me a value”)Prints “Give me a value” on the python screen and waits until the user types anything and presses EnterAfter pressing enter, the result is a string even for numbers
14 Assignment Statements The ‘=‘ is the assignment statementThe value to the right is associated with the variable name on the leftIt does not stand for equality!
15 Convert from string to integer To do math, Python requires converting the sequence of characters into an integer
16 Printing Output myVar = 12 print (‘My var has a value of:’,myVar) print takes a list of elements to print, separated by commasIf the element is a string, prints it as isIf the element is a variable, prints the value associated with the variableAfter printing, moves on to a new line of output
17 Save as a scriptWhen you save a file, such as our first program, and place a .py suffix on it, it becomes a python module or scriptYou “run” the module from the IDLE menu to see the results of the operationA module is just a file with a bunch of python commandsPython provides a lot modules for common tasks such as math, databases, networking, etc.
18 Errors!!!If Python interpreter does not understand your code you will get an error (or errors)Check the syntax and fix itYou can them import the program again until there are no more errors
19 Common ErrorWhen using IDLE, if you save a file without a .py extension, it will not colorize and format the file.Resave with the .py extension
20 Formal Elements of Programming These apply to any computer programming language
21 Statements Statements are commands. n = n + n ** 3 n = 3 They perform some actionn = n + n ** 3n = 3print ‘Hello!’
22 Expressions Expressions perform some operation and have a value 3 Typically do not modify values in the interpreter3n + 3n ** 3
23 Comments Code is what actually executes Comments do not execute but they make the programs easier to understand, improving readability.n #this an expressionn = n ** 3 #this is an statementprint ‘Hello!’ #this is another statement
24 Literals Literal is a programming notation for a fixed value. Integer numbers are literals because they have fixed valuese.g. 123, 999, 1000.
26 VariablesA variable is a location in memory where we store data in our program.We assign names to variables to make our program more readable.
27 Variables Name Value X 7 X = 7 Python maintains a list of pairs for every variable:variable’s namevariable’s valueA variable is created when a value is assigned the first time. It associates a name and a valueSubsequent assignments update the associated value.We say the variable name references the valueA variable type depends on the value assigned to it.NameValueX7X = 7
29 Python Naming Conventions Must begin with a letter or _Ab123 is OK, but 123ABC is not.May contain letters, digits, and underscoresthis_is_an_identifier_123May be of any lengthUpper and lower case letters are differentLengthOfRope is not the same as lengthofropeNames starting with _ have special meaning.
30 When = Doesn’t Mean Equal It is most confusing at first to see the following kind of expression:myInt = myInt + 7What’s looks strange here is that the = doesn’t mean equal, but assignment
31 = sign means assignment In many computer languages, = means assignment.myInt = myInt + 7lhs = rhsWhat assignment means is:Evaluate the expression on the right-hand-size of the equal signTake the resulting value and store it in the variable indicated on the left-hand-sizeOnly variables go into the left-hand side of an assignment statement
32 More on Assignment Example: x = 3 * 5 + 2 evaluate expression (3*5 + 2) = 17change the value of x to 17Example (if y has value 2): y = y + 3evaluate the expression (y+3): 5change the value of y to 5
34 Variables and TypesPython does not require you to pre-define the data type of a variableThe data type of a variable can changeNonetheless, knowing the data type can be important for using the correct operation on a variable. Thus proper naming is important!
35 What is a Type? A Python data type essentially defines two things: The internal structure of the type (what it contains)The operations you can perform on it.You can capitalize letter, and add numbersYou cannot capitalize numbers or add letter.
36 Python Data Types Integer: 5 Float: 1.2 Boolean: True, False String: “anything” or ‘something’List: [,]: [‘a’,1,1.3]Others
37 Fundamental Types Integers Floating Point 1, -27Floating Point3.14, 10.0, .001, 3.14e-10, 0e0Boolean (True or False values)True, False (notice the use of caps)
38 Converting Types A character ‘1’ is NOT the same as the integer 1 You need to convert the value returned by the input command (characters) into an integerint(“123”) yields the integer 123
39 Type Conversion int(someVar) converts to an integer float(someVar) converts to a floatstr(someVar) converts to a stringshould check out what works:int(2.1) 2, int(‘2’) 2, but int(‘2.1’) failsfloat(2) 2.0, float(‘2.0’) 2.0, float(‘2’) 2.0, float(2.0) 2.0str(2) ‘2’, str(2.0) ‘2.0’, str(‘a’) ‘a’
40 Types and DivisionPython does binary operations on two values of the same type, yielding a value of that type:2/3, integer types, yield integer (0).2%3 is the remainder, an integer (2)2.0/3.0, float types, yield float ( )
41 Mixed Types 4/3 results is 1 under integer division 4.0/3.0 results in under float divisionWhat is the result of 4/3.0?Python will automatically convert to the most detailed type. Thus 4 4.0, and the result is