Intro toprogramming part2
Transcript of Intro toprogramming part2
Introduction to Programming
Part Deux
1
“My Bads” from last week
• If I wasn’t clear, this is the Intro. – Not intended to be specific to PHP– Conceptual, so have a base for PHP, JS, MySQL
• Pseudo code, (python), and PHP– Oh, my!
• Using a concept before defining it– Casting: “many helper functions for casting”– Function: A named group or set of functions that perform
a specific task. • Built-in functions: print, echo, round(), floor(), etc.• User defined functions• Functions can take arguments and return values
2
10 second review
• Technology Stack• Servers• Our test jig• Programming cycle• Variables• Variable assignment• Variable manipulation• Basic Math• Data type conversion
3
Homework review
• Past Homework: Limited Participation, Late Submissions, Joe Away…
• http://jamesmarcus.net/bwa/introprog/exercise1.php– Note the two approaches to printing variables and
formatting
• http://jamesmarcus.net/bwa/introprog/exercise2.php– Only change the value of one variable and then it’s
basically cut and paste
4
Decisions, decisions
• In order to build complex programs, we need to be able to control what the program does.
• Program Control– Testing and branching– Execution blocks– More than one condition
5
Testing, testing• Programs need to be able to do different things based on input or the
value of certain variables during execution. – If Tim got the right answer, (then) add 10 points to his score. – If Jane hit the alien, (then) make an explosion sound. – If the file isn’t there, (then) display an error message.
• To make decisions, programs check (do a test) to see if a certain condition is true or not. – Above, the test is “got the right answer” and is either True or False
6
Testing, testing
• A programming language can test only a finite number of basic things:– Are two things equal? – Is one thing less than another? – Is one thing greater than another?
• Doing tests and making decisions based on the results is called branching. – The program decides which way to go, or which
branch to follow, based on the result of the test.
7
Execution Blocks
• Special “comparison” operators are used for testing: ==, !=, <, >, <=, >=
• Some languages use { } to create execution blocks8<6branch1.php>
Bad bug story
{ …$someVariable == $thisVariable + $thatVariable;
…
print $someVariable;
} 9
6badbug1.php
<6badbug1.php>
What happens if the test result is false?
10
• If the first test comes out false, we can test something else. Most languages have an “else if” keyword. (PHP: elseif; C: elsif; Python: elif)
if ($answer >= 10) {print “You got at least 10!”;
} elseif ($answer >= 5) {print “You got at least 5!”;
} elseif ($answer >= 3) {print “Your got at least 3!”;
}
11
<6branch2.php>
• If the other tests come out false, we can do something else. Most/all languages have an “else” keyword.
if ($answer >= 10) {print “You got at least 10!”;
} elseif (answer >= 5) {print “You got at least 5!”;
} elseif (answer >= 3) {print “You got at least 3!”;
} else {print “You got less than 3.”;
}
12
<6branch3.php>
Move on
• If there is no other test or default block after the if, the program will move on. (no else)
13
Testing for more than one condition
• Scenario: We are coding a game that must check that the user is at least 8 years old and at least in the third grade
• One solution
if ($age >= 8) {if ($grade >= 3) {
print “You can play this game.”;}
} else {print “Sorry, you can’t play the game.”;
}
14
<7compound1.php>
BUT this has a bug!
Testing for more than one condition
• A better way … Compound testing
if ($age >= 8 && $grade >= 3) {print “You can play this game.”;
} else {print “Sorry, you can’t play this game.”;
}
• Comparison operators are also called relational operators. A comparison is also called a conditional test or logical test.
• In programming, logical test refers to something where the answer is either true or false.
15
Testing for more than one condition
• Compound tests are created with logical operators– “and” [PHP: &&]– “or” [PHP:||]– “not” [PHP: !] 16
Using “or”
if ($color == ”red” || $color == ”blue” || $color == ”green”) {
print ”You are allowed to play this game.”;} else {
print "Sorry, you can't play the game.”;}
17
<7compound3.php>
<7compound4.php>
A better way!
Using “not”
• You can also flip around a comparison to mean the opposite, using not.
if ( !($age < 8) ) {print ”You are allowed to play this game.”;
} else {print ”Sorry, you can't play the game.”;
}
18
Quiz
• What is the output of the following:$my_number = 7;if ($my_number < 20) {
print ‘Under 20’;
} else {print ‘20 or over’;
}
• What kind of if statement would you use to check if a number was greater than 30 but less than or equal to 40?
19
Here we go loop de loop, here we go loop de li
• Doing the same thing over and over again, could lead to …– repetitive stress injury, insanity… for humans, – but is what the computer does best
• Programs often repeat the same steps over and over again– looping
• There are two main kinds of loops: – counting loops – repeat a specified number of times– conditional loops - repeat until a some condition is true
20
Counting loops
• This is often called a “for” loop and uses a for keyword
for ($i = 1; $i < 5; $i = $i + 1) {print “Loop $i”;print “<br>”;
}
• Each time through the loop is called an iteration• If you are not careful, runaway, infinite, or endless
loops will occur!
21
<8loop1.php>
A matter of style – loop variable names
• A loop variable is no different from any other variable.
• Recall, we want contextual meaning for variables. – What to call loop variables?
• Convention: For loop variables, the names $i, $j, $k, $l, $m, and $n are used.
22
Conditional loops
• The for loop is great • if you know ahead of time how many times you
want the loop to run. • But sometimes you want a loop to run until
something happens– while loops let you do that
• Figuring out when something happens requires testing for a condition – The while loop keeps asking “Am I done yet? … Am I
done yet? … Am I done yet? …” until its done!
23
While loop
$i = 1;while ($i <= 10) {
print “Number $i <br>”;$i = $i + 1;
}•Gotchas:–No loop variable initialization–Bad test–Missing increment or decrement
24
<8loop3.php>
Bailing out of a loopbreak and continue
• There are times when we must get out of a loop before the for loop is finished counting or before a while loop has found its end condition
• Jumping ahead – continue– If you want to stop executing the current loop
iteration and skip to the next iteration, use continue
• Bailing out – break– If we want to jump out of a loop completely, never
finish counting, give up on an end condition, use break
25
Continue and break
for ($i = 1; $i < 10; $i = $i + 1) {if ($i == 3 || ($i % 2 == 0)) continue;
if ($i == 7) break;
print $i;
print “<br>”;
}
26
<8loop4.php>
Quiz
• How many times would the following loop run?for ($i=1; $i < 6; $i = $i+1) {
print ‘Hello James’;
}
• What keyword do you use to stop the current iteration of a loop and jump ahead to the next iteration?
27
Comments
• Use them!• Comments should be treated as part of the
program’s documentation
28
Comments
• Single line comments// This is comment line in a PHP program.print “This is not a comment line.”;• Multiline comments/* This is a multiline comment.
Look what it can be used for (commenting out)*/
/* $complexStuff = $moreComplexStuff * 2;$print $complexStuff; */$knowThisWorks = 2;print $knowThisWorks;
29
Collecting things together - Lists
• We’ve seen that the computer can store things in its memory and retrieve them, using names. – So far, we have stored strings and numbers (both integers
and floats).• Sometimes it’s useful to store a bunch of things
together in a kind of “group” or “collection.” – Work with or perform operations on the whole collection
at once. • One kind of collection is a list. – Lists are used often. In fact, information passed to PHP
from a web page and MySQL query responses are returned as a list or a list of lists…
30
What is a list?
• My family list: Lori, James, Olivia, and Sami• In PHP, this list is created as
$family = array(‘Lori’, ‘James’, ‘Olivia’, ‘Sami’);• Most programming languages have built in support for
arrays–An array variable is a normal variable, but works like a container – you can put other variables in it–Each variable inside an array is called an element. Each element has a key and a value, which itself can be a variable–$family_member = $family[ $index ]–There are many predefined array functions
$size = count($family);
31<9lists1.php>
Looping through a list
print “This is my family:<br>”;
foreach ($family as $var => $val) {print “$var = $val<br>”;
}
32
Power user: List processing
$myfamily = array(“Mom”=>”Lori”, “Dad”=>”James”, “Kid1”=>”Olivia”, “Kid2”=>”Sami”);
foreach ($myfamily as $var => $val) {print “$var = $val<br>”;
}
33
Functions, Objects, & Modules, oh my
• Over time, programs get bigger and more complicated. • We need some organization. • Best practice is to keep “like” pieces together in
relative small groups• There are three main ways to break programs into
smaller parts.– Functions are like building blocks of code that you can use
over and over again. – Objects are a way of describing pieces of your program as
self-contained units. – Modules are just separate files that contain parts of your
program.
34
Functions – software Lego
• In the simplest of terms, a function is just a chunk of code that does something. – A small piece that you can use to build a bigger program.
• There are built in functions – count(), print(), echo() – or you create or define a custom function.
• Functions can be called with variables, called passing arguments or parameters, and can return information back to the caller, called return values or results
35
Objects
• Good programming is highlighted by good information organization and collecting things together.
• Lists are a way to collect variables (data) together.• Functions are a way to collect some code together into
a unit that you can use over and over again. • Objects are a way to collect functions and data
together.– In programming terms, we say a programming language is
object oriented. It’s possible (in fact, quite easy) to create and use objects, but you don’t have to.
36
Modules
• A module is a piece or part of something. – A program is modular if it comes in pieces or you can
easily separate it into pieces.
• Each module, or piece, is a separate file on your hard drive. – You can take a big program and split it up into more
than one module, or file. – Or you can go the other way—start with one small
module and keep adding pieces to make a big program.
37
And in conclusion
38
• Exercises
39
Exercise 1
• A store is having a sale. They are giving 10% off purchases or $10 or lower and 20% off purchases of greater that $10. Write a short program that displays the discount (10% or 20%) and the final price.– Use a variable for the item’s cost, run as many
cases necessary to test the program.
40
Exercise 2
• Write a short program to print a multiplication or times table. Your program should output something like:– Here is the 5’s table:– 5 x 1 = 5– 5 x 2 = 10– …– 5 x 10 = 50
41