EBook - Programming Language Using PHP - Python
EBook - Programming Language Using PHP - Python
eISBN 978-967-2285-06-9
TABLE OF CONTENT
CHAPTER 1 INTRODUCTION OF PHP
1.1 Introduction 1
1.2 PHP Installation 2
1.3 Installing and Testing Wampserver 3
1.4 Saving Your PHP Files 5
CHAPTER 4 OPERATOR
4.1 Introduction 19
4.2 Assignment Operators 20
4.3 Comparison Operators 22
4.4 PHP Logical Operators 29
i
PHP Programming Language Level 1
HTML/XHTML
JavaScript
What is PHP?
What is MySQL?
PHP + MySQL
• PHP combined with MySQL are cross-platform (you can develop in Windows and serve
on a Unix platform)
1
PHP Programming Language Level 1
Why PHP?
Where to Start?
• Install Apache (or IIS) on your own server, install PHP, and MySQL
• Or find a web hosting plan with PHP and MySQL support
http://www.wampserver.com/en/
Windows Users
Back to Wampserver and Windows. First, you need to download the software. You can get it from
here:
www.wampserver.com/en/download.php
Be sure to click the link for Presentation, as well as the link for Downloads. The Presentation page
shows you how to install the file.
2
PHP Programming Language Level 1
If the installation went well, you should have a new icon in the bottom right, where the clock is:
From here, you can stop the server, exit it, view help files, and see the configuration pages.
Click on localhost, though, and you'll see this page appear: (Localhost just refers to the server
running on your own computer. Another way to refer to your server is by using the IP address
127.0.0.1.)
3
PHP Programming Language Level 1
Click the link under Tools that says phpinfo(). If all went well, you should be looking at the following
page.
If you saw the above page, then congratulations! Your PHP server is up and running, and you can
make a start scripting PHP pages.
Troubleshooting
If you don't see the info.php page, then you will need to refer to the wampserver forums. The page
you need is here:
www.wampserver.com/phorum/list.php?2
4
PHP Programming Language Level 1
Whenever you create a new PHP page, you need to save it in your WWW directory. You can see
where this is by clicking its item on the menu:
When you click on www directory, you should see an explorer window appear.
This www folder for Wampserver is usually at this location on your hard drive:
c:/wamp/www/
Bear this in mind when you click File > Save As to save your PHP scripts.
5
PHP Programming Language Level 1
Download PHP
Download PHP for free here: http://www.php.net/downloads.php
6
PHP Programming Language Level 1
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be
placed anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with <? And end with ?>.
For maximum compatibility, we recommend that you use the standard form (<?php) rather than the
short and form.
<?php
?>
A PHP file normally contains HTML tags, just like a HTML file, and some PHP scripting code.
Below, is an example of a simple PHP script which sends the text “HI EVERYONE” to the browser:
<html>
<body>
<?php
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.
There are two basic statements to give output to text with PHP: echo and print. In the example
above we have to use the echo statement to output the text “HI EVERYONE”.
You can think of echo as a PHP command: it tells PHP to echo back the information that follows. If
you type <?php echo “Hooray!”; ?> PHP will dutifully print out “Hooray!”
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not be
executed.
7
PHP Programming Language Level 1
2.2 Semicolons
You have probably noticed that our lines of PHP code end in semicolon ( ; ). PHP requires semicolons
at the end of each statement, which is the shortest unit of standalone code. Example, echo “Hi!”; or
2 + 2;
You can think of a statement is a complete PHP. 19 + or echo are not complete, so you would put
semicolons at the end of them.
<?php echo
?>
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?/
</body>
</html>
2.4 Arithmetic
Unlike HTML and CSS, PHP can do math for you.
In PHP, we can simply type 13 * 379 and get the result 4927.
<html>
<body>
<p>
<?php
echo 17*123;
?>
</p>
</body>
</html>
8
PHP Programming Language Level 1
2.5 Strings
A string is a word or phrase between quotes, like so:
“HI EVERYONE!”
The concatenation operator is just a dot ( . ). (If you’re coming to PHP from Javascript, the dot does
the same thing for strings that + does in Javascript.)
Exercise 1
Type the PHP code below and insert ‘MY FIRST LINE OF PHP!’ BETWEEN THE “ “.
1 <html>
2 <body>
3 <p>
4 <?php
5 echo “ “;
6 ?>
7 </p>
8 </body>
9 </html>
Type your PHP code on line 4. This time, let’s try echo 40 + 20. No need for quotations marks.
1 <html>
2 <body>
3 <p>
4
5 </p>
6 </body>
7 </html>
9
PHP Programming Language Level 1
Variables in PHP
Variables are used for storing a values, like text strings, number or arrays.
When a variables is declared, it can be used over and over again in your script.
$var_name = value;
Let’s say you want to create a variables called $total. When you type:
$total = 4 + 8 + 15 + 16 + 23 + 42;
You’re telling PHP to sum these number and store that sum under the name $total. Then if you
type:
The = sign is called the assignment operator. You use it to tell PHP you want to assign a name to a
value: $year = 2013;.
New PHP programmers often forget the $ sign at the beginning of the variables. In that case it will
not work.
Let’s try creating a variable containing a string, and a variable containing a number:
<?php
echo $txt;
echo $myAge;
?>
10
PHP Programming Language Level 1
PHP automatically converts the variable to the correct data type, depending on its value. In a
strongly typed programming language, you have to declare (define) the type and name of the
variable before using it.
A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9,
and _)
A variable name should not contain spaces. If a variable name is more than one word, it
should be separated with an underscore ($my_string), or with capitalization ($myString)
In this chapter we are going to look at the most common functions and operators used to
manipulate string in PHP.
After we create a string we can manipulate it. A string can be used directly in a function or it can be
stored in a variable.
Below, the PHP script assigns the text “HI EVERYONE” to a string variable called $txt:
<?php
?>
HI EVERYONE
11
PHP Programming Language Level 1
<?php
?>
If we look at the code above you see that we used the concatenation operator two times. This is
because we had to insert a third string ( a space character ), to separate the two strings.
12
PHP Programming Language Level 1
PHP has lots of built-in functions, and we will learn some of them in this exercises. The first set of
functions we will learn is about string with manipulation functions.
<?php
?>
The length of a string is often used in loops or other functions, when it is important to know when
the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string).
Send the function the string you want to get substring of, the character in your string to start at, and
how many characters you want after your starting point. Example:
$myname = “David”;
echo $partial;
// prints “dav”
Note: the second parameter (the starting character) is based on a zero-indexed array (ie. The first
character in your string is number 0, not number 1).
13
PHP Programming Language Level 1
$uppercase = strtoupper($myname);
echo $uppercase;
// prints “DAVID”
$lowercase = strtolower($uppercase)
echo $lowercase;
// prints “david”
// prints “david”
Is a match is found, this function will return the position of the first match. If no match is found, it
will return FALSE.
<?php
?>
The position of the string “EVERYONE” in our string is position 3. The reason that it is 3 (and not 4) is
that the first position in the string is 0 and not 1.
14
PHP Programming Language Level 1
Function Description
addcslashes() Returns a string with backslashes in front of the specified characters
addslashes() Returns a string with backslashes in front of predefined characters
bin2hex() Converts a string of ASCII characters to hexadecimal values
Removes whitespace or other characters from the right end of a
chop()
string
chr() Returns a character from a specified ASCII value
chunk_split() Splits a string into a series of smaller parts
count_chars() Returns information about characters used in a string
crc32() Calculates a 32-bit CRC for a string
crypt() One-way string encryption (hashing)
echo() Outputs one or more strings
explode() Breaks a string into an array
fprintf() Writes a formatted string to a specified output stream
hebrev() Converts Hebrew text to visual text
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>
hex2bin() Converts a string of hexadecimal values to ASCII characters
html_entity_decode() Converts HTML entities to characters
htmlentities() Converts characters to HTML entities
htmlspecialchars_decode() Converts some predefined HTML entities to characters
htmlspecialchars() Converts some predefined characters to HTML entities
implode() Returns a string from the elements of an array
join() Alias of implode()
lcfirst() Converts the first character of a string to lowercase
levenshtein() Returns the Levenshtein distance between two strings
localeconv() Returns locale numeric and monetary formatting information
ltrim() Removes whitespace or other characters from the left side of a string
md5() Calculates the MD5 hash of a string
md5_file() Calculates the MD5 hash of a file
metaphone() Calculates the metaphone key of a string
money_format() Returns a string formatted as a currency string
nl_langinfo() Returns specific local information
nl2br() Inserts HTML line breaks in front of each newline in a string
number_format() Formats a number with grouped thousands
ord() Returns the ASCII value of the first character of a string
15
PHP Programming Language Level 1
16
PHP Programming Language Level 1
17
PHP Programming Language Level 1
Exercise 2
Write your own code. Get a partial string from within your own name and print it to the screen.
Then try making your name upper case and lower case and print those to the screen as well.
1 <html>
2 <body>
3 <p>
4 <?php
7 .
8 ?>
9 </p>
10 <p>
11 <?php
13 .
14 ?>
15 </p>
16 <p>
17 <?php
19 .
20 ?>
21 </p>
22 </body>
23 </html>
18
PHP Programming Language Level 1
CHAPTER 4 OPERATOR
4.1 Introduction
Example :
1. <?php
2. $x=100;
3. $y=60;
4. echo "The sum of x and y is : ". ($x+$y) ."<br />";
5. echo "The difference between x and y is : ". ($x-$y) ."<br />";
6. echo "Multiplication of x and y : ". ($x*$y) ."<br />";
7. echo "Division of x and y : ". ($x/$y) ."<br />";
8. echo "Modulus of x and y : " . ($x%$y) ."<br />";
9. ?>
Output
The sum of x and y is : 160
The difference between x and y is : 40
Multiplication of x and y : 6000
Division of x and y : 1.6666666666667
Modulus of x and y : 40
Note : In case of division, the operator returns a float value if the two operands are not integers.
19
PHP Programming Language Level 1
The basic assignment operator is "=". Your first inclination might be to think of this as "equal to".
Don't. It really means that the left operand gets set to the value of the expression on the right (that
is, "gets set to").
The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This
allows you to do some tricky things:
<?php
?>
For arrays, assigning a value to a named key is performed using the "=>" operator.
The precedence of this operator is the same as other assignment operators.
In addition to the basic assignment operator, there are "combined operators" for all of the binary
arithmetic, array union and string operators that allow you to use a value in an expression and then
set its value to the result of that expression. For example:
<?php
$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";
?>
Note that the assignment copies the original variable to the new one (assignment by value), so
changes to one will not affect the other. This may also have relevance if you need to copy something
like a large array inside a tight loop.
An exception to the usual assignment by value behavior within PHP occurs with objects, which is
assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword.
20
PHP Programming Language Level 1
Assignment by Reference
Assignment by reference is also supported, using the "$var = &$othervar;" syntax. Assignment by
reference means that both variables end up pointing at the same data, and nothing is copied
anywhere.
<?php
$a = 3;
$b = &$a; // $b is a reference to $a
$a = 4; // change $a
As of PHP 5, the new operator returns a reference automatically, so assigning the result of new by
reference results in an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in
earlier versions.
<?php
class C {}
21
PHP Programming Language Level 1
In PHP, comparison operators take simple values (numbers or strings) as arguments and evaluate to
either TRUE or FALSE.
Here is a list of comparison operators.
=== Identical $x === TRUE if $x is exactly equal to $y, and they are of the same type.
$y
22
PHP Programming Language Level 1
!== Not $x !== TRUE if $x is not equal to $y, or they are not of the same type.
identical $y
< Less than $x < $y TRUE if $x (left-hand argument) is strictly less than $y (right-hand
argument).
> Greater $x > $y TRUE if $x (left hand argument) is strictly greater than $y (right
than hand argument).
<= Less than $x <= $y TRUE if $x (left hand argument) is less than or equal to $y (right
or equal hand argument).
to
23
PHP Programming Language Level 1
The following php codes return true though the type of $x and $y are not equal (first one is integer
type and second one is character type) but their values are equal.
<?php
$x = 300;
$y = "300";
var_dump($x == $y);
?>
Output: bool(true)
The following php codes returns false as strict equal operator will compare both value and type of $x
and $y.
<?php
$x = 300;
$y = "300";
?>
Output : bool(false)
24
PHP Programming Language Level 1
The following php codes returns false though the type of $x and $y are not equal (first one is integer
type and second one is character type) but their values are equal.
<?php
$x = 150;
$y = "150";
var_dump($x != $y);
?>
The following php codes returns true though their values are equal but type of $x and $y are not
equal (first one is integer type and second one is character type).
<?php
$x = 150;
$y = "150";
?>
Output: bool(true)
25
PHP Programming Language Level 1
The following php code returns true as the value of $x is greater than $y.
<?php<br>
$x = 300;
$y = 100;
var_dump($x>$y);
?>
Output: bool(true)
26
PHP Programming Language Level 1
The following php codes returns true as the value of $x is greater than to $y.
<?php
$x = 300;
$y = 100;
var_dump($x>=$y);
?>
Output: bool(true)
The following php codesreturns true as the value of $x is less than $y.
<?php
$x = 100;
$y = 300;
var_dump($x<$y);
?>
Output: bool(true)
27
PHP Programming Language Level 1
The following PHP codes returns false as the value of $x is greater than $y.
<?php
$x = 300;
$y = 100;
var_dump($x<=$y);
?>
Output: bool(false)
28
PHP Programming Language Level 1
There's also something called Logical Operators. You typically use these when you want to test more
than one condition at a time. For example, you could check to see whether the username and
password are correct from the same If Statement. Here's the table of these Operands.
$username ='user';
$password ='password';
print("Welcome back!");
}
else {
The if statement is set up the same, but notice that now two conditions are being tested:
This says, "If username is correct AND the password is ok, too, then let them in". Both
conditions need to go between the round brackets of your if statement.
29
PHP Programming Language Level 1
The || Operator
The two straight lines mean OR. Use this symbol when you only need one of your conditions
to be true. For example, suppose you want to grant a discount to people if they have spent
more than 100 pounds OR they have a special key. Else they don't get any discount. You'd
then code like this:
$total_spent =100;
$special_key ='SK12345';
print("Discount Granted!");
}
else {
This time we're testing two conditions and only need ONE of them to be true. If either one of
them is true, then the code gets executed. If they are both false, then PHP will move on.
AND and OR
These are the same as the first two! AND is the same as && and OR is the same as ||. There
is a subtle difference, but as a beginner, you can simply replace this:
With this
And this:
With this:
It's up to you which you use. AND is a lot easier to read than &&. OR is a lot easier to read
than ||.
30
PHP Programming Language Level 1
XOR
You probably won't need this one too much. But it's used when you want to test if one value
of two is true but NOT both. If both values are the same, then PHP sees the expression as
false. If they are both different, then the value is true. Suppose you had to pick a winner
between two contestants. Only one of them can win. It's an XOR situation!
$contestant_one = true;
$contestant_two = true;
}
else {
See if you can guess which of the two will print out, before running the script.
The ! Operator
This is known as the NOT operator. You use it test whether something is NOT something
else. You can also use it to reverse the value of a true or false value. For example, you want
to reset a variable to true, if it's been set to false, and vice versa. Here's some code to try:
$test_value = false;
if ($test_value == false) {
print(!$test_value);
The code above will print out the number 1! (You'll see why when we tackle Boolean values
below.) What we're saying here is, "If $test_value is false then set it to what it's NOT." What
it's NOT is true, so it will now get this value. A bit confused? It's a tricky one, but it can come
in handy!
31
PHP Programming Language Level 1
You use Conditional Logic in your daily life all the time:
Conditional Logic uses the "IF" word a lot. For the most part, you use Conditional Logic to test what
is inside of a variable. You can then makes decisions based on what is inside of the variable. As an
example, think about the username again. You might have a variable like this:
$User_Name = "My_Regular_Visitor";
The text "My_Regular_Visitor" will then be stored inside of the variable called $User_Name. You
would use some Conditional Logic to test whether or not the variable $User_Name really does
contain one of your regular visitors. You want to ask:
"IF $User_Name is authentic, then let $User_Name have access to the site."
if ($User_Name == "authentic") {
32
PHP Programming Language Level 1
5.3 IF Statement
Without any checking, the if statement looks like this:
if ( ) {
You can see it more clearly, here. To test a variable or condition, you start with the word "if". You
then have a pair of round brackets. You also need some more brackets - curly ones. These are just to
the right of the letter "P" on your keyboard. You need the left curly bracket first { and then the right
curly bracket } at the end of your if statement. Get them the wrong way round, and PHP refuses to
work. This will get you an error:
if ($User_Name = = "authentic") }
if ($User_Name == "authentic") {
The first one has the curly brackets the wrong way round (should be left then right), while the
second one has two left curly brackets.
In between the two round brackets, you type the condition you want to test. In the example above,
we're testing to see whether the variable called $User_Name has a value of "authentic":
($User_Name = = "authentic")
Again, you'll get an error if you don't get your round brackets right! So the syntax for the if
statement is this:
if (Condition_or_Variable_to_test) {
In the next lesson, we'll use if statements to display an image on the page.
33
PHP Programming Language Level 1
We'll use the print statement to "print out" HTML code. As an example, take the following HTML
code to display an image:
Just plain HTML. But you can put that code inside of the print statement:
When you run the code, the image should display. Of course, you'll need an image called cat.jpg, and
in a folder called images.
Copy the images folder to your www (root) directory. Then try the following script:
<?PHP
?>
Save your script to the same folder as the images folder (though NOT inside the images folder). Now
restart your server, and give it a try. You'll see the cat image display.
We can use the if statement to display our image, from the previous section. If the user selected
"cat", then display the cat image. If the user selected "kitten", then display another image (the kitten
image, which is also in your images folder). Here's some code:
<?PHP
$kitten_image = 1;
$cat_image = 0;
if ($kitten_image == 1) {
?>
Type the code, and save it as testImages.php. (Notice how there's no HTML!)
34
PHP Programming Language Level 1
When you run the script, the kitten image should be displayed. Let's look at the code and see what's
happening.
$kitten_image = 1;
$cat_image = 0;
A value of 1 has been assigned to the variable called $kitten_image. A value of 0 has been assigned
to the variable called $cat_image. We then have our if statement. Here is the code without the print
statement:
if ($kitten_image == 1) {
Notice how there's no semi-colon at the end of the first line - you don't need one. After the word "if"
we have a round bracket. Then comes our variable name: $kitten_image. We want to test what's
inside of this variable. Specifically, we want to test if it has a value of 1. So we need the double
equals sign (==). The double equals sign doesn’t really mean “equals”. It means “has a value of”.
"If the variable called $kitten_image has a value of 1 then execute some code."
To complete the first line of the if statement we have another round bracket, and a left curly
bracket. Miss any of these out, and you'll probably get the dreaded parse error!
The code we want to execute, though, is the print statement, so that our kitten image will display.
This goes inside of the if statement:
if ($kitten_image == 1) {
But if your if statement only runs to one line, you can just do this:
In other words, keep everything on one line. PHP doesn't care about your spaces, so it's perfectly
acceptable code. Not very readable, but acceptable!
35
PHP Programming Language Level 1
To make use of the cat image, here's some new code to try:
<?PHP
$kitten_image = 0;
$cat_image = 1;
if ($kitten_image == 1) {
if ($cat_image == 1) {
?>
Notice that the $kitten_image variable now has a value of 0 and that $cat_image is 1. The new if
statement is just the same as the first. When you run the script, however, the cat image will display.
That's because of this line:
if ($kitten_image == 1) {
That says, "If the variable called $kitten_image has a value of 1 ... ". PHP doesn't bother reading the
rest of the if statement, because $kitten_image has a value of 0. It will jump down to our second if
statement and test that:
if ($cat_image == 1) {
Since the variable called $cat_image does indeed have a value of 1, then the code inside of the if
statement gets executed. That code prints out the HTML for the cat image:
36
PHP Programming Language Level 1
<?PHP
$kitten_image = 0;
$cat_image = 1;
if ($kitten_image == 1) {
}
else {
?>
Copy this new script, save your work, and try it out. You should find that the cat image displays in
the browser. This time, the if … else statement is being used. Let’s see how it works.
if (condition_to_test) {
}
else {
If you look at it closely, you’ll see that you have a normal If Statement first, followed by an “else”
part after it. Here’s the “else” part:
else {
Again, the left and right curly brackets are used. In between the curly brackets, you type the code
you want to execute. In our code, we set up two variables:
$kitten_image = 0;
$cat_image = 1;
37
PHP Programming Language Level 1
The variable called $kitten_image has been assigned a value of 0, and the variable called
$cat_image has been assigned a value of 1. The first line of the if statement tests to see what is
inside of the variable called $kitten_image. It’s testing to see whether this variable has a value of 1.
if ($kitten_image == 1) {
What we’re asking is: “Is it true that $kitten_image holds a value of 1?” The variable $kitten_image
holds a value of 0, so PHP sees this as not true. Because a value of “not true” has been returned
(false, if you like), PHP ignores the line of code for the if statement. Instead, it will execute the code
for the “else” part. It doesn’t need to do any testing – else means “when all other options have been
exhausted, run the code between the else curly brackets“. Following are the code:
else {
So the cat image gets displayed. Change your two variables from this:
$kitten_image = 0;
$cat_image = 1;
To this:
$kitten_image = 1;
$cat_image = 0;
38
PHP Programming Language Level 1
else if (another_condition_to_test) {
<?PHP
$kitten_image = 1;
$cat_image = 0;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
else if ($cat_image == 1) {
print ("<IMG SRC =images/cat.jpg>");
}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines
(and that there’s a space between else and if):
else if ($cat_image == 1) {
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to
evaluate the new condition. If it’s true (the $cat_image variable holds a value of 1), then the code
between the new curly brackets gets executes. If it’s false (the $cat_image variable does NOT holds a
value of 1), then the line of code will be ignored, and PHP will move on.
39
PHP Programming Language Level 1
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if,
and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
else if ($cat_image == 1) {
else {
You can add as many else if parts as you like, one for each condition that you want to test. But
change your two variables from this:
$kitten_image = 1;
$cat_image = 0;
to this:
$kitten_image = 0;
$cat_image = 0;
Below is the sample coding for you to test the script. Copy this to your own www (root) folder (by
creating the ‘selectPicture.php’ file from this code). As long as you have all the images mentioned in
the script (in your folder images), they should display. But examine the code for the script (ignore
the HTML form tags for now). What it does is to display an image, based on what the user selected
from a drop down list. If statements are being used to test what is inside of a single variable.
Don’t worry too much about the rest of the code: concentrate on the if statements. All we’re doing
is testing what is inside of the variable called $picture. We’re then displaying the image that
corresponds to the word held in the variable.
OR you can as well create your own simple script on testing the if statement.
40
PHP Programming Language Level 1
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) {
$picture = $_POST['picture'];
if ($picture == "cat") {
print ("<IMG SRC =images/cat.jpg>");
}
else if ($picture == "kitten"){
print ("<IMG SRC =images/kitten.jpg>");
}
else if ($picture == "planet"){
print ("<IMG SRC =images/planet.jpg>");
}
else if ($picture == "cartoon"){
print ("<IMG SRC =images/cartoon.jpg>");
}
else if ($picture == "space"){
print ("<IMG SRC =images/space.jpg>");
}
else if ($picture == "abstract"){
print ("<IMG SRC =images/abstract.jpg>");
}
else {
print ("No Image to Display");
}
?>
</body>
</html>
41
PHP Programming Language Level 1
6.1 Introduction
Single variable option can be tested from a drop-down list which is a different picture was displayed
on screen, depending on the value inside of the variable. For a better option, if you have only one
variable to test, it is recommended to use something called a switch statement. To see how switch
statements work, study the following code:
<?php
$picture ='cat';
switch ($picture) {
case 'kitten':
print('Kitten Picture');
break;
case 'cat':
print('Cat Picture');
break;
?>
In the code above, we place the direct text "cat" into the variable called $picture. It's this direct text
that we want to check. We want to know what is inside of the variable, so that we can display the
correct picture.
To test a single variable with a Switch Statement, the following syntax is used:
switch ($variable_name) {
case 'What_you_want_to_check_for':
//code here
break;
42
PHP Programming Language Level 1
The word 'case' is used before each value you want to check for. In code, a list of values was coming
from a drop-down list. These value were: cat and kitten, among others. These are the values we
need after the word 'case'. After the text or variable you want to check for, a colon is needed ( : ).
After the semi colon on the 'case' line, you type the code you want to execute. Needless to say,
you'll get an error if you miss out any semi-colons at the end of your lines of code!
6.5 break;
You need to tell PHP to "Break out" of the switch statement. If you don't, PHP will simply drop down
to the next case and check that. Use the word 'break' to get out of the Switch statement.
6.6 Default:
If you look at the last few lines of the Switch Statement in your coding, you'll see something else you
can add to your own code:
default:
print ("No Image Selected");
The default option is like the else from if … else. It's used when there could be other, unknown,
options. A sort of "catch all" option.
43
PHP Programming Language Level 2
1.5 Exercise 1 11
1.6 Exercise 2 11
2.4 Exercise 3 21
3.3 Exercise 4 25
3.4 Exercise 5 28
4.5 Exercise 6 34
1
PHP Programming Language Level 2
5.6 Exercise 7 41
2
PHP Programming Language Level 2
An array is a special variable, which can store multiple values in one single variable.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look
like this:
$cars1 = “Saab”;
$cars2 = “Volvo”;
$cars3 = “BMW”;
However, what if you want to loop through the cars and find a specific one? And what if you had not 3
cars, but 300?
An array can hold all your variable values under a single name. And you can access the values by
referring to the array name.
Each element in the array has its own index so that it can be easily.
Array Syntax
Have you noticed something familiar at the start of array? That’s right, it starts in the same way as a
variable, with the $ sign, and then a name, followed by =.
However, this is when things start to get different. When declaring an array, we have to use array().
This basically tells PHP that $array is an array and not something else, such as a regular old variable.
You can add any type of information to an array, and you do it in much the same way as when declaring
variables. Use “ “ when adding strings, and just enter n the number when adding integers.
3
PHP Programming Language Level 2
You must always remember, however, that each item in an array must be separated by comma:( , ) .
1. In the following example the index are automatically assigned (the index starts at 0):
$cars[0] = “Saab”;
$cars[1] = “Volvo”;
$cars[2] = “BMW”;
$cars[3] = “Toyota”;
Example
In the following example you access the variable values by referring to the array name and index:
<?php
$cars[0] = “Saab”;
$cars[1] = “Volvo”;
$cars[2] = “BMW”;
$cars[3] = “Toyota”;
4
PHP Programming Language Level 2
?>
<?php
Echo count($cars);
?>
<?php
{
echo $cars[$x];
echo “<br>”;
}
?>
5
PHP Programming Language Level 2
When storing data about specific named values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
Example 2
This example is the same as example 1, but show a different way of creating the array:
$ages[‘Peter’] = “32”;
$ages[‘Quagmire’] = “30”;
$ages[‘Joe’] = “34”;
<?php
$ages[‘Peter’] = “32”;
$ages[‘Quagmire’] = “30”;
$ages[‘Joe’] = “34”;
?>
6
PHP Programming Language Level 2
Example
$families = array
(
“Griffin”=>array
(
“Peter”,
“Lois”,
“Megan”,
),
“Quagmire”=>array
(
“Glenn”
),
“Brown”=>array
(
“Cleveland”,
“Loretta”,
“Junior”
)
);
7
PHP Programming Language Level 2
The array above would look like this if written to the output:
Array
(
[Griffin] = > Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
(
[0] => Glenn
)
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
Example 2
8
PHP Programming Language Level 2
The PHP array functions are part of the PHP core. No installation is required to use these
functions.
Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_column() Returns the values from a single column in the input array
Creates an array by using the elements from one "keys" array and
array_combine()
one "values" array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences (compare values only)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a callback function
array_flip() Flips/Exchanges all keys with their associated values in an array
array_intersect() Compare arrays, and returns the matches (compare values only)
array_merge() Merges one or more arrays into one array
array_pop() Deletes the last element of an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
Replaces the values of the first array with the values from
array_replace()
following arrays
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_sum() Returns the sum of the values in an array
array_unique() Removes duplicate values from an array
Sorts an associative array in descending order, according to the
arsort()
value
Sorts an associative array in ascending order, according to the
asort()
value
compact() Create array containing variables and their values
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Returns the current key and value pair from an array
end() Sets the internal pointer of an array to its last element
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
9
PHP Programming Language Level 2
10
PHP Programming Language Level 2
1.5 Exercise 1
Let’s try creating an array from scratch. Create an array called $friends and put the names of three of
your friends in it. Make sure each friend’s name is in quotes. ( “ or ‘ ).
<html>
<head>
</head>
<body>
<p>
<?php
?>
</p>
</body>
</html>
11
PHP Programming Language Level 2
1.6 Exercise 2
Create an array with the following values: Tokyo, Maxico City, New York City, Mumbai, Seoul, Shanghai,
Lagos, Buenos Aires, Cairo, London.
Print these values to the browser separated by commas, using a loop to iterate over the array. Sort the
array, and then print the values to the browser in an unordered list, again using a loop.
Add the following cities to the array: Los Angeles, Calcutta, Osaka, Beijing. Sort the array again, and
print it once more to the browser in an unordered list.
Your output:
Large Cities
Tokyo, Mexico City, New York City, Mumbai, Seoul, Shanghai, Lagos, Buenos Aires, Cairo, London,
Buenos Aires
Cairo
Lagos
London
Mexico City
Mumbai
New York City
Seoul
Shanghai
Tokyo
Beijing
Buenos Aires
Cairo
Calcutta
Lagos
London
Los Angeles
Mexico City
Mumbai
New York City
Osaka
Seoul
Shanghai
Tokyo
12
PHP Programming Language Level 2
Answer:
<html>
<body>
<?php
//Create array.
$cities=array(
"Tokyo",
"Mexico City",
"Mumbai",
"Seoul",
"Shanghai",
"Lagos",
"Buenos Aires",
"Cairo",
"London"
);
foreach($cities as $c){
//Sort array.
sort($cities);
13
PHP Programming Language Level 2
echo "\n<ul>\n" ;
foreach($cities as $c){
echo "<li>$c</li>\n";
echo "</ul>" ;
sort($cities);
echo "\n<ul>\n";
foreach($cities as $c){
echo "<li>$c</li>\n";
echo "</ul>";
?>
</body>
</html>
14
PHP Programming Language Level 2
A loop is a structure that tells a computer to execute a set of statements multiple times. If you have a
process that you want repeated hundreds of times, it pays to put it in a loop so you don’t need to write
hundreds of lines of code.
Loops execute a block of code a specified number of times, or while a specified condition is true.
Syntax
While (condition)
code to be executed;
15
PHP Programming Language Level 2
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as i is less
than, or equal to 5. i will increase by each time the loop runs:
<html>
<body>
<?php
$i = 1;
While ($i<=5)
$i++;
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
16
PHP Programming Language Level 2
The while loop first checks the condition and if it is true then execute the relevant code block. After the
code was executed the while loop checks the condition again and executes the code again if necessary.
This will be repeated until the condition is true.
It is important to make sure that the loop will exit at some point when writing loops. So you have to
make sure not to make a never ending loop like this:
$x=0;
while ($x<10)
echo “$x<br/>”;
$x++;
The loop will never exit and is an example of infinite loop. In this case, the x variable is never
incremented so the condition will be always true. This results an endless loop.
Time after time it can happen that you want to break the execution of the loop independent from the
original condition. You can do this by using the break keyword. With break you can terminate the loop
and the script will exit from the loop and continue the execution with the next statement after the loop
block.
$x=0;
while ($x<10)
echo “$x<br/>”;
$x++;
If ($x==5) break;
echo “Ready”;
17
PHP Programming Language Level 2
As you can see here x is smaller than 10 but the loop was ended because of break.
Beside this it can happen that you want to begin the next iteration without fully execute the actual code
block. You can do this by using the continue keyword. In case of continue the actual code execution will
be terminated and the loop immediately begins with a new iteration.
$x = 0;
$x++;
if ($x<5) continue;
echo “$x<br/>;
Using Endwhile
while (condition):
endwhile;
Note the colon after the end parenthesis and the semicolon after the endwhile statement.
When they are embedded in HTML, loops that use this endwhile syntax can be more readable than the
equivalent syntax involving curly braces.
18
PHP Programming Language Level 2
The do…while statement will always execute the block of code once, it will then check the condition,
and repeat the loop while the condition is true.
Syntax
do
code to be executed;
while (condition);
Example
The example below defines a loop that starts with i=1. It will then increment i with 1, and write some
output. Then the condition is checked, and the loop will continue to run as long as i is less than, or equal
to 5:
<html>
<body>
<?php
$i=1;
do
$i++;
19
PHP Programming Language Level 2
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
20
PHP Programming Language Level 2
{ } ( ) ; ;
1 <html>
2 <body>
3 <?php
4 $loopCond = false
5 do
6 echo “<p>The loop ran even though the loop condition is false.</p>
7 while $loopCond
9 ?>
10 </body>
11 </html>
21
PHP Programming Language Level 2
The for loop is the most complex loop in PHP but maybe it is the most used as well. In case of for loops
you makes the loop variable initialization, conditional check, loop variable in single line.
1. A for loop starts with the for keyword. This tells PHP to get ready to loop.
2. Next comes a set of parentheses (). Inside the parentheses, we tell PHP three things, separated
by semicolons (;): where to start the loop; where to end the loop; and what to do to get to the
next iteration of the loop (for instance, count up by one).
3. After the part in parentheses, the part in curly braces {} tells PHP what code to run for each
iteration of the loop.
Syntax
Parameters:
init: Mostly used to set a counter (but can be any code to be executed once at the beginning of
the loop)
condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it
evaluates to FALSE, the loop ends.
Increment: Mostly used to increment a counter (but can be any code to be executed at the end
of the loop)
Note: Each of the parameters above can be empty, or have multiple expressions (separated by
commas).
22
PHP Programming Language Level 2
Example
The example below defines a loop that start with i=1. The loop will continue to run as long as i is less
than, or equal to 5. i will increase by 1 each time the loop runs:
<html>
<body>
<?php
for ($i=1; $1<=5; $i++)
{
echo “The number is “ . $i . “<br/>”;
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
For instance, if you type $i + 1 instead of $i++ or $i = $i + 1 for the third bit of your for loop, the $i
variable will never actually get updated, and your loop will go on forever. This is called an infinite loop
and it will cause you to have to refresh the page.
23
PHP Programming Language Level 2
Simple exercise:
Try write a for loop that echo s the numbers 10 up to and including 100, counting by 10s (e.g. 10, 20,
30…).
<html>
<body>
<?php
//Write your for loop below!
?>
</body>
</html>
for loops are great for running the same code over and over, especially when you know ahead of time
how many times you’ll need to loop.
The foreach loop is used to loop through arrays iterate over each element of an object – which makes it
perfect for use with array.
Syntax
Code to be executed;
For every loop iteration, the value of the current array element is assigned to $value (and the array
pointer is moved by one) – so on the next loop iteration, you’ll be looking at the next array value.
24
PHP Programming Language Level 2
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array (“one”,”two”,”three”);
?>
</body>
</html>
Output:
one
two
three
25
PHP Programming Language Level 2
Let’s walk through the foreach syntax step-by-step. First, here’s a foreach loop that iterates over an
array and prints out each element it finds:
<?php
echo $item;
}
?>
First, we create our array using the array() syntax. Next, we use the foreach keyword to start the loop,
followed by parentheses. (This is very similar with for loops.)
Between the parentheses, we use the $numbers as $item syntax to tell PHP: “For each thing in
$numbers, assign that thing temporarily to the variable $item. “(We don’t have to use the name $item
– just with for loops, we can call our temporary variable anything we want.)
Finally, we put the code we want to execute between the curly braces. In this case, we just echo each
element in turn.
As you can see here not only $value variable is present in the foreach header but a $key as well. And
yes it contains the actual key. So you can use this to display your associative array with foreach like this:
$test = array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
26
PHP Programming Language Level 2
3.3 Exercise 4
Given you the $yardlines array in the editor. Go ahead and write a foreach loop that iterates over the
array and echo each element to the page.
1 <html>
2 <head>
3 <title></title>
4 </head>
5 <body>
6 <p>
7 <?php
11 echo "touchdown!";
12 ?>
13 </p>
14 </body>
15 </html>
27
PHP Programming Language Level 2
Use two for loops, one nested inside another. Create the following multiplication table:
Output:
Answer:
<html>
<body>
<?php
//Generate table data showing the numbers 1-7 multiplied by each other,
28
PHP Programming Language Level 2
echo "<tr>\n";
$x=$col * $row;
//Then send the value to the table with the table data tags.
echo "<td>$x</td>\n";
echo "</tr>";
echo "</table>";
?>
</body>
</html>
29
PHP Programming Language Level 2
To keep the browser from executing a script when the page loads, you can put your script into a
function.
A function will be executed by a call to the function. You may call a function from anywhere within a
page.
Syntax
function functionName()
{
Code to be executed;
}
PHP function guidelines:
Give the function a name that reflects what the function does
The function name can start with a letter or underscore (not a number)
Example
<html>
<body>
<?php
function writeName()
{
echo “Kevin James Michael”;
}
30
PHP Programming Language Level 2
</body>
</html>
Output:
Parameters are specified after the function name, inside the parentheses.
Example 1
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function writeName($fname)
writeName (“Hege”);
writeName (“Stale”);
?>
</body>
31
PHP Programming Language Level 2
</html>
Output:
Example 2
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Michael" . $punctuation . "<br />";
}
echo "My name is ";
writeName("Kevin James",".");
echo "My sister's name is ";
writeName(
"Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>
</body>
</html>
Output:
32
PHP Programming Language Level 2
Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output:
1 + 16 = 17
33
PHP Programming Language Level 2
1 <?php
4 .
5 .
6 .
7 .
9 .
11 .
12 //skip a line
13 .
16 .
17 ?>
Output:
2+4=6
10+10=20
34
PHP Programming Language Level 2
Answer:
1 <?php
5 {
7 }
11 print “2 + 4 = “ . $additionResult;
12 //skip a line
13 print “<br/>”;
17 ?>
35
PHP Programming Language Level 2
Example
The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
</body>
</html>
When a user fills out the form above and click on the submit button, the form data is sent to a PHP file,
called “welcome.php”:
<html>
<body>
</body>
</html>
36
PHP Programming Language Level 2
Welcome John!
The PHP $_GET and $_POST functions will be explained in the next chapters.
You should consider server validation if the user input will be inserted into a database. A good way to
validate a form on the server is to post the form to itself, instead of jumping to a different page. The
user will then get the error messages on the same page as the form. This makes it easier to discover the
error.
The built-in $_GET function is used to collect values in a form with method=”get”.
Information sent from a form with the GET method is visible to everyone (it will be displayed in the
browser’s address bar) and has limits on the amount of information to send (max 100 characters).
Example
<input type=”submit”>
</form>
37
PHP Programming Language Level 2
When the user clicks the “Submit” button, the URL sent to the server could look something like this:
http://...//welcome.php?fname=Peter&age=37
The “welcome.php” file can now use the $_GET function to collect form data (the names of form fields
will automatically be the keys in the $_GET array):
Note: This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can
be useful in some cases.
Note: The get method is not suitable for large variable values; the value cannot exceed 100 characters.
38
PHP Programming Language Level 2
Information sent from a form with the POST method is invisible to others and has no limits on the
amount of information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting
the post_max_size in the php.ini file).
Example
</form>
When the user clicks the “Submit” button, the URL will look like this:
http://.../welcome.php
The “welcome.php” file can now use the $_POST function to collect form data (the names of the form
fields will automatically be the keys in the $_POST array):
39
PHP Programming Language Level 2
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.
Example:
40
PHP Programming Language Level 2
5.6 Exercises 7
1. Simple Form with PHP Response
Request input from the user, and then move the user’s response from one file to another.
Create two separate files. The first will contain a form with one input fiels asking for the user’s favorite
city. Use the post method for the form. Although this file contains no PHP code on localhost but it need
the .php extension to successfully call the second file.
The second file will contain PHP code to process the user’s response. After the user click the submit
button, echo back Your favorite city is $city., where $city is the input from the form.
Hint: the variable that contains the user’s input is an array. The array variable is $_POST[‘name’], where
‘name’ is the bane of your input field.
Answer:
Form code,
<html>
<body>
<h2>Favorite City</h2>
<p />
</form>
</body>
</html>
41
PHP Programming Language Level 2
Response file,
<html>
<body>
<h2>Favorite City</h2>
<?php
$city = $_POST['city'];
?>
</body>
</html>
42
PHP Programming Language Level 2
Create a form asking the user for input about the weather the user has experienced in a month of the
user’s choice. In separate text fields, request the city, month and year in question. Below that, show a
series of checkboxes. Those values were: rain, sunshine, clouds, hail, sleet, snow, wind. Set up the form
to create an array from the checked items.
In the response section of your script, create an array using the city, month and year the user entered as
values. Print the following response “In $city in the month of $month $year, you observed the following
weather:”, where $city, $month and $year are values from the array you created.
Next, loop through the $weather[] array you received from the user to send back a bulleted list with the
user’s responses.
Output:
43
PHP Programming Language Level 2
Answer:
<html>
<body>
<?php
if (!isset($_POST['submit'])){
?>
<p>Please choose the kinds of weather you experienced from the list below.
44
PHP Programming Language Level 2
<p />
</form>
<?php
}else{
$inputLocal = array(
$_POST['city'],
$_POST['month'],
$_POST['year']
);
$weather = $_POST['weather'];
foreach($weather as $w){
echo "<li>$w</li>\n";
}
echo "</ul>";
}
?>
</body>
</html>
45
PHP Programming Language Level 2
One very useful thing you can do with PHP is include the request for user input and the response in the
same file, using conditional statements to tell PHP which one to show. For this PHP exercise, rewrite the
two files of the previous exercise into one file using an is-else conditional statement.
Hint: You’ll need some way to tell if the form has been submitted. The function to determine if a
variable has been set and is not null is isset().
Answer:
<html>
<body>
<h2>Favorite City</h2>
<?php
if (!isset($_POST['submit'])){
?>
<!--Make sure you have entered the name you gave the file as the action.-->
<p />
</form>
<?php
}else{
46
PHP Programming Language Level 2
$city = $_POST['city'];
?>
</body>
</html>
4. If-Elseif-Else Construction
For this PHP exercise, you will use the same format as the previous exercise, requesting inout in the first
part, and responding in the second, through the magic of PHP’s if else statement. In the first section,
give the user an input field and request that they enter a day of the week.
Using the else-elseif-else construction, set each line to output in response to the day the user inputs,
with a general response for any input that is not in the poem.
47
PHP Programming Language Level 2
Answer:
<html>
<body>
<?php
if (!isset($_POST['submit'])){
?>
<p />
</form>
<?php
}else{
$day = $_POST["day"];
if ($day == 'Monday'){
48
PHP Programming Language Level 2
} else {
?>
</body>
</html>
5. Switch Statement
You probably noticed that the if-elseif-else construction was repetitive and cumbersome in the last
exercise. It works best with only one or two choices. A more appropriate construction for this exercise
is the switch statement, combined with a select field in the form for the days of the week. So your
assignment in this PHP exercise is to rewrite the previous exercise using a select field for the user input
and the switch statement to process the response.
49
PHP Programming Language Level 2
Remember to include a general response for any input that is not in the poem. To make things a little
more interesting, include a ‘Back’ button on the response so that the user can go back and try different
days.
Answer:
<html>
<h2>Pick a Day</h2>
<?php
if (!isset($_POST['submit'])){
?>
<select name="day">
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
<option value="Sunday">Sunday</option>
</select>
<p />
50
PHP Programming Language Level 2
</form>
<?php
}else{
$day = $_POST['day'];
switch($day){
case 'Monday':
break;
case 'Tuesday':
break;
case 'Wednesday':
break;
case 'Thursday':
break;
case 'Friday':
51
PHP Programming Language Level 2
break;
case 'Saturday':
break;
default:
break;
?>
<p />
<form action="testing.php">
</form>
<?php
?>
</body>
</html>
52
Programming Language (Python)
Programming Language (Python) i
Table of Contents
Chapter Page
Chapter 1 Introduction 1
1.1 Introduction to Python 1
1.2 What can I with Python? 5
1.3 How is Python developed and supported? 7
1.4 What are Python’s technical strengths? 9
- Chapter 1 -
Introduction
Objectives:
• Software quality: For many, Python’s focus on readability, coherence, and software
quality in general sets it apart from other tools in the scripting world. Python code is
designed to be readable, and hence reusable and maintainable—much more so
than traditional scripting languages. The uniformity of Python code makes it easy
to understand, even if you did not write it. In addition, Python has deep support for
more advanced software reuse mechanisms, such as object-oriented (OO) and
function programming.
• Program portability: Most Python programs run unchanged on all major computer
platforms. Porting Python code between Linux and Windows, for example, is usually
just a matter of copying a script’s code between machines. Moreover, Python
Programming Language (Python) 2
offers multiple options for coding portable graphical user interfaces, database
access programs, webbased systems, and more. Even operating system interfaces,
including program launches and directory processing, are as portable in Python as
they can possibly be.
• Support libraries: Python comes with a large collection of prebuilt and portable
functionality, known as the standard library. This library supports an array of
application-level programming tasks, from text pattern matching to network
scripting. In addition, Python can be extended with both homegrown libraries and
a vast collection of third-party application support software. Python’s third-party
domain offers tools for website construction, numeric programming, serial port
access and game development. The NumPy extension, for instance, has been
described as a free and more powerful equivalent to the Matlab numeric
programming system.
• Component integration: Python scripts can easily communicate with other parts of
an application, using a variety of integration mechanisms. Such integrations allow
Python to be used as a product customization and extension tool. Today, Python
code can invoke C and C++ libraries, can be called from C and C++ programs,
can integrate with Java and .NET components, can communicate over
frameworks such as COM and Silverlight, can interface with devices over serial
ports, and can interact over networks with interfaces like SOAP, XML-RPC, and
CORBA. It is not a standalone tool.
• Enjoyment: Because of Python’s ease of use and built-in toolset, it can make the
act of programming more pleasure than chore. Although this may be an intangible
benefit, its effect on productivity is an important asset.
Still, the term “scripting” seems to have stuck to Python like glue, perhaps as a contrast with
larger programming effort required by some other tools. For example, people often use the
word “script” instead of “program” to describe a Python code file. In keeping with this
tradition, this book uses the terms “script” and “program” interchangeably, with a slight
preference for “script” to describe a simpler top-level file and “program” to refer to a more
sophisticated multifile application.
Because the term “scripting language” has so many different meanings to different
observers, though, some would prefer that it not be applied to Python at all. In fact, people
tend to make three very different associations, some of which are more useful than others,
when they hear Python labeled as such:
• Control language: To others, scripting refers to a “glue” layer used to control and
direct (i.e., script) other application components. Python programs are indeed
often deployed in the context of larger applications. For instance, to test hardware
devices, Python programs may call out to components that give low-level access
to a device. Similarly, programs may run bits of Python code at strategic points to
support end-user product customization without the need to ship and recompile
the entire system’s source code. Python’s simplicity makes it a naturally flexible
control tool. Technically, though, this is also just a common Python role; many
(perhaps most) Python programmers code standalone scripts without ever using or
knowing about any integrated components. It is not just a control language.
• Ease of use: Probably the best way to think of the term “scripting language” is that
it refers to a simple language used for quickly coding tasks. This is especially true
when the term is applied to Python, which allows much faster program
development than compiled languages like C++. Its rapid development cycle
fosters an exploratory, incremental mode of programming that has to be
experienced to be appreciated.
Programming Language (Python) 4
Don’t be fooled, though—Python is not just for simple tasks. Rather, it makes tasks simple
by its ease of use and flexibility. Python has a simple feature set, but it allows programs
to scale up in sophistication as needed. Because of that, it is commonly used for quick
tactical tasks and longer-term strategic development.
At this writing, the best estimate anyone can seem to make of the size of the Python user
base is that there are roughly 1 million Python users around the world today (plus or minus
a few). This estimate is based on various statistics, like download rates, web statistics, and
developer surveys. Because Python is open source, a more exact count is difficult—there
are no license registrations to tally. Moreover, Python is automatically included with Linux
distributions, Macintosh computers, and a wide range of products and hardware, further
clouding the user-base picture.
In general, though, Python enjoys a large user base and a very active developer
community. It is generally considered to be in the top 5 or top 10 most widely used
programming languages in the world today (its exact ranking varies per source and date).
Because Python has been around for over two decades and has been widely used, it is
also very stable and robust.
Besides being leveraged by individual users, Python is also being applied in real revenue
generating products by real companies. For instance, among the generally known
Python user base:
• ESRI uses Python as an end-user customization tool for its popular GIS mapping
products.
• Google’s App Engine web development framework uses Python as an application
language.
• The IronPort email server product uses more than 1 million lines of Python code to
do its job.
However, the most common Python roles currently seem to fall into a few broad
categories. The next few sections describe some of Python’s most common applications
today, as well as tools used in each domain.
Programming Language (Python) 6
Systems Programming
Python’s built-in interfaces to operating-system services make it ideal for writing portable,
maintainable system-administration tools and utilities (sometimes called shell tools). Python
programs can search files and directory trees, launch other programs, do parallel
processing with processes and threads, and so on.
Python’s standard library comes with POSIX bindings and support for all the usual OS tools:
environment variables, files, sockets, pipes, processes, multiple threads, regular expression
pattern matching, command-line arguments, standard stream interfaces, shell-command
launchers, filename expansion, zip file utilities, XML and JSON parsers, CSV file handlers, and
more. In addition, the bulk of Python’s system interfaces are designed to be portable; for
example, a script that copies directory trees typically runs unchanged on all major Python
platforms.
GUIs
Python’s simplicity and rapid turnaround also make it a good match for graphical user
interface programming on the desktop. Python comes with a standard object-oriented
interface to the Tk GUI API called tkinter (Tkinter in 2.X) that allows Python programs to
implement portable GUIs with a native look and feel. Python/tkinter GUIs run unchanged
on Microsoft Windows, X Windows (on Unix and Linux), and the Mac OS (both Classic and
OS X). A free extension package, PMW, adds advanced widgets to the tkinter toolkit. In
addition, the wxPython GUI API, based on a C++ library, offers an alternative toolkit for
constructing portable GUIs in Python.
Higher-level toolkits such as Dabo are built on top of base APIs such as wxPython and
tkinter. With the proper library, you can also use GUI support in other toolkits in Python, such
as Qt with PyQt, GTK with PyGTK, MFC with PyWin32, .NET with IronPython, and Swing with
Jython or JPype. For applications that run in web browsers or have simple interface
requirements, both Jython and Python web frameworks and server-side CGI scripts,
described in the next section, provide additional user interface options.
Programming Language (Python) 7
Microsoft Team
Microsoft Teams is designed for seamless efficiency and collaboration. It integrates with
Office applications like Word and SharePoint, and its design and infrastructure make it
exceptionally interactive. The company has also made it possible to integrate Skype for
Business into Microsoft Teams.
This program was designed as a response to the growing number of collaboration tools,
like Slack, that have dominated the market in the last few years. Microsoft Teams is a catch-
all chat tool for the workplace, but its video conferencing option is just as compelling and
powerful. Users can launch video conferences directly from their chats.
As a popular open source system, Python enjoys a large and active development
community that responds to issues and develops enhancements with a speed that many
commercial software developers might find remarkable. Python developers coordinate
work online with a source-control system. Changes are developed per a formal protocol,
which includes writing a PEP (Python Enhancement Proposal) or other document, and
extensions to Python’s regression testing system. In fact, modifying Python today is roughly
as involved as changing commercial software—a far cry from Python’s early days, when
an email to its creator would suffice, but a good thing given its large user base today.
The PSF (Python Software Foundation), a formal nonprofit group, organizes conferences
and deals with intellectual property issues. Numerous Python conferences are held around
the world; O’Reilly’s OSCON and the PSF’s PyCon are the largest. The former of these
addresses multiple open source projects, and the latter is a Python-only event that has
experienced strong growth in recent years. PyCon 2012 and 2013 reached 2,500 attendees
each; in fact, PyCon 2013 had to cap its limit at this level after a surprise sell-out in 2012.
Earlier years often saw attendance double —from 586 attendees in 2007 to over 1,000 in
2008, for example—indicative of Python’s growth in general, and impressive to those who
remember early conferences whose attendees could largely be served around a single
restaurant table.
Programming Language (Python) 8
Having said that, it’s important to note that while Python enjoys a vigorous development
community, this comes with inherent tradeoffs. Open source software can also appear
chaotic and even resemble anarchy at times, and may not always be as smoothly
implemented as the prior paragraphs might imply. Some changes may still manage to defy
official protocols, and as in all human endeavours, mistakes still happen despite the
process controls (Python 3.2.0, for instance, came with a broken console input function on
Windows).
Moreover, open source projects exchange commercial interests for the personal
preferences of a current set of developers, which may or may not be the same as yours—
you are not held hostage by a company, but you are at the mercy of those with spare
time to change the system. The net effect is that open source software evolution is often
driven by the few, but imposed on the many.
In practice, though, these tradeoffs impact those new releases much more than those
using established versions of the system, including prior releases in both Python 3.X and 2.X.
If you kept using classic classes in Python 2.X, for example, you were largely immune to the
explosion of class functionality and change in new-style classes that occurred in the early-
to-mid 2000s.
Programming Language (Python) 9
Python is an object-oriented language, from the ground up. Its class model supports
advanced notions such as polymorphism, operator overloading, and multiple inheritance;
yet, in the context of Python’s simple syntax and typing, OOP is remarkably easy to apply.
In fact, if you don’t understand these terms, you’ll find they are much easier to learn with
Python than with just about any other OOP language available.
Besides serving as a powerful code structuring and reuse device, Python’s OOP nature
makes it ideal as a scripting tool for other object-oriented systems languages. For example,
with the appropriate glue code, Python programs can subclass (specialize) classes
implemented in C++, Java, and C#.
Of equal significance, OOP is an option in Python; you can go far without having to
become an object guru all at once. Much like C++, Python supports both procedural and
object-oriented programming modes. Its object-oriented tools can be applied if and when
constraints allow. This is especially useful in tactical development modes, which preclude
design phases.
It’s Free
Python is completely free to use and distribute. As with other open source software, such
as Tcl, Perl, Linux, and Apache, you can fetch the entire Python system’s source code for
free on the Internet. There are no restrictions on copying it, embedding it in your systems,
or shipping it with your products. In fact, you can even sell Python’s source code, if you are
so inclined.
But don’t get the wrong idea: “free” doesn’t mean “unsupported.” On the contrary, the
Python online community responds to user queries with a speed that most commercial
software help desks would do well to try to emulate. Moreover, because Python comes
with complete source code, it empowers developers, leading to the creation of a large
team of implementation experts. Although studying or changing a programming
language’s implementation isn’t everyone’s idea of fun, it’s comforting to know that you
can do so if you need to. You’re not dependent on the whims of a commercial vendor,
because the ultimate documentation—source code—is at your disposal as a last resort.
It’s Powerful
From a features perspective, Python is something of a hybrid. Its toolset places it between
traditional scripting languages (such as Tcl, Scheme, and Perl) and systems development
languages (such as C, C++, and Java). Python provides all the simplicity and ease of use
of a scripting language, along with more advanced software-engineering tools typically
found in compiled languages. Unlike some scripting languages, this combination makes
Python useful for large-scale development projects. As a preview, here are some of the
main things you’ll find in Python’s toolbox:
Programming Language (Python) 11
• Dynamic typing: Python keeps track of the kinds of objects your program uses when
it runs; it doesn’t require complicated type and size declarations in your code. In
fact, as you’ll see in here, there is no such thing as a type or variable declaration
anywhere in Python. Because Python code does not constrain data types, it is also
usually automatically applicable to a whole range of objects.
• Built-in object types: Python provides commonly used data structures such as lists,
dictionaries, and strings as intrinsic parts of the language; as you’ll see, they’re both
flexible and easy to use. For instance, built-in objects can grow and shrink on
demand, can be arbitrarily nested to represent complex information, and more.
• Built-in tools: To process all those object types, Python comes with powerful and
standard operations, including concatenation (joining collections), slicing
(extracting sections), sorting, mapping, and more.
• Library utilities: For more specific tasks, Python also comes with a large collection of
precoded library tools that support everything from regular expression matching to
networking. Once you learn the language itself, Python’s library tools are where
much of the application-level action occurs.
- Chapter 2 -
So far, we’re mostly been talking about Python as a programming language. But, as currently
implemented, it’s also a software package called an interpreter. An interpreter is a kind of program
that executes other programs. When you write a Python program, the Python interpreter reads your
program and carries out the instructions it contains.
In effect, the interpreter is a layer of software logic between your code and the computer hardware
on your machine. When the Python package is installed on your machine, it generates a number
of components— minimally, an interpreter and a support library. Depending on how you use it, the
Python interpreter may take the form of an executable program, or a set of libraries linked into
another program. Depending on which flavor of Python you run, the interpreter itself may be
implemented as a C program, a set of Java classes, or something else. Whatever form it takes, the
Python code you write must always be run by this interpreter. And to enable that, you must install a
Python interpreter on your computer.
Programming Language (Python) 13
• Windows users fetch and run a self-installing executable file that puts Python on their
machines. Simply double-click and say Yes or Next at all prompts.
• Linux and Mac OS X users probably already have a usable Python preinstalled on their
computers—it’s a standard component on these platforms today.
• Some Linux and Mac OS X users (and most Unix users) compile Python from its full source
code distribution package.
• Linux users can also find RPM files, and Mac OS X users can find various Mac specific
installation packages.
• Other platforms have installation techniques relevant to those platforms. For instance,
Python is available on cell phones, tablets, game consoles, and iPods, but installation details
vary widely.
Python itself may be fetched from the downloads page on its main website, http://www
.python.org. It may also be found through various other distribution channels. Keep in mind that you
should always check to see whether Python is already present before installing it.
Program Execution
Programming Language (Python) 14
What it means to write and run a Python script depends on whether you look at these tasks as a
programmer, or as a Python interpreter. Both views offer important perspectives on Python
programming.
This file contains two Python print statements, which simply print a string (the text in quotes)
and a numeric expression result (2 to the power 100) to the output stream. Don’t worry about
the syntax of this code yet—for this chapter, we’re interested only in getting it to run.
Python’s View
The brief description in the prior section is fairly standard for scripting languages, and it’s usually all
that most Python programmers need to know. You type code into text files, and you run those files
through the interpreter. Under the hood, though, a bit more happens when you tell Python to “go.”
Although knowledge of Python internals is not strictly required for Python programming, a basic
understanding of the runtime structure of Python can help you grasp the bigger picture of program
execution.
When you instruct Python to run your script, there are a few steps that Python carries out before
your code actually starts crunching away. Specifically, it’s first compiled to something called “byte
code” and then routed to something called a “virtual machine.”
• Byte code compilation: Internally, and almost completely hidden from you, when you
execute a program Python first compiles your source code (the statements in your file) into
a format known as byte code. Compilation is simply a translation step, and byte code is a
lower-level, platform-independent representation of your source code. Roughly, Python
translates each of your source statements into a group of byte code instructions by
decomposing them into individual steps. This byte code translation is performed to speed
execution —byte code can be run much more quickly than the original source code
statements in your text file.
Programming Language (Python) 15
• The Python Virtual Machine (PVM): Once your program has been compiled to byte code
(or the byte code has been loaded from existing .pyc files), it is shipped off for execution to
something generally known as the Python Virtual Machine (PVM, for the more acronym-
inclined among you).
The PVM sounds more impressive than it is; really, it’s not a separate program, and it need
not be installed by itself. In fact, the PVM is just a big code loop that iterates through your
byte code instructions, one by one, to carry out their operations. The PVM is the runtime
engine of Python; it’s always present as part of the Python system, and it’s the component
that truly runs your scripts. Technically, it’s just the last step of what is called the “Python
interpreter.”
classes and the linkage of modules. Such events occur before execution in more static
languages, but happen as programs execute in Python. As we’ll see, this makes for a much
more dynamic programming experience than that to which some readers may be
accustomed.
Now that we’ve studied the internal execution flow described in the prior section, we should note
that it reflects the standard implementation of Python today but is not really a requirement of the
Python language itself. Because of that, the execution model is prone to changing with time. In
fact, there are already a few systems that modify the picture. Before moving on, let’s briefly explore
the most prominent of these variations.
In brief, CPython is the standard implementation, and the system that most readers will wish to use
(if you’re not sure, this probably includes you). This is also the version used in this book, though the
core Python language presented here is almost entirely the same in the alternatives. All the other
Python implementations have specific purposes and roles, though they can often serve in most of
CPython’s capacities too. All implement the same Python language but execute programs in
different ways.
For example, PyPy is a drop-in replacement for CPython, which can run most programs much
quicker. Similarly, Jython and IronPython are completely independent implementations of Python
that compile Python source for different runtime architectures, to provide direct access to Java
and .NET components. It is also possible to access Java and .NET software from standard CPython
programs—JPype and Python for .NET systems, for instance, allow standard CPython code to call
out to Java and .NET components. Jython and IronPython offer more complete solutions, by
providing full implementations of the Python language.
Programming Language (Python) 17
Here’s a quick rundown on the most prominent Python implementations available today.
gain accessibility both to and from other .NET languages, and leverage .NET technologies
such as the Silverlight framework from their Python code.
- Chapter 3 -
3.1 Installation
Installing or updating Python on your computer is the first step to becoming a Python programmer.
There are a multitude of installation methods: you can download official Python distributions from
Python.org, install from a package manager, and even install specialized distributions for scientific
computing, Internet of Things, and embedded systems.
This tutorial focuses on official distributions, as they’re generally the best option for getting started
with learning to program in Python.
Programming Language (Python) 20
In this section, you’ll learn how to check which version of Python, if any, is installed on your Windows
computer. You’ll also learn which of the three installation methods you should use. Use of a WiFi
connection may not provide the best audio experience as WiFi may be less stable. We recommend
a hardwire connection or that you use the telephone for the best results on a WiFi connection.
To check if you already have Python on your Windows machine, first open a command-line
application, such as PowerShell.
With the command line open, type in the following command and press Enter:
Using the --version switch will show you the version that’s installed. Alternatively, you can use the -V
switch:
Programming Language (Python) 21
In either case, if you see a version less than 3.8.4, which was the most recent version at the time of
writing, then you’ll want to upgrade your installation. If you’re interested in where the installation is
located, then you can use the where.exe command in cmd.exe or PowerShell:
Note that the where.exe command will work only if Python has been installed for your user account.
As mentioned earlier, there are three ways to install the official Python distribution on Windows:
• Full Installer
This approach involves downloading Python directly from the Python.org website. This is
recommended for intermediate and advanced developers who need more control during
the setup process.
In this section, we’ll focus on only the first two options, which are the most popular installation
methods in a Windows environment. The two official Python installers for Windows aren’t identical.
The Microsoft Store package has some important limitations.
Programming Language (Python) 22
If you’re new to Python and looking to get started quickly, then the Microsoft Store package is the
best way to get up and running without any fuss. You can install from the Microsoft Store in two
steps.
Select Python 3.8, or the highest version number you see available in the app, to open the
installation page.
Alternatively, you can open PowerShell and type the following command:
If you don’t already have a version of Python on your system, then when you press Enter, the
Microsoft Store will automatically launch and take you to the latest version of Python in the store.
Programming Language (Python) 23
Congratulations! You now have access to Python, including pip and IDLE!
For professional developers who need a full-featured Python development environment, installing
from the full installer is the right choice. It offers more customization and control over the installation
than installing from the Microsoft Store.
The full installer gives you total control over the installation process. Customize the installation to
meet your needs using the options available on the dialog box. Then click Install Now. That’s all
there is to it! Congratulations—you now have the latest version of Python 3 on your Windows
machine!
Programming Language (Python) 25
In this section, you’ll learn how to check which version of Python, if any, is on your Linux computer.
You’ll also learn which of the two installation methods you should use.
Many Linux distributions come packaged with Python, but it probably won’t be the latest version
and may even be Python 2 instead of Python 3. You should check the version to make sure.
To find out which version of Python you have, open a terminal window and try the following
commands:
Programming Language (Python) 26
If you have Python on your machine, then one or more of these commands should respond with a
version number. For example, if you already had Python 3.6.10 on your computer, then the python3
--version command would display that version number:
You’ll want to get the latest version of Python if your current version is in the Python 2.X series or is
not the latest version of Python 3 available, which was 3.8.4 as of this writing.
In this section, you’ll learn how to install Python using Ubuntu’s apt package manager. If you’d like
to build Python from source code, skip ahead to the How to Build Python from Source Code section.
Depending on the version of the Ubuntu distribution you run, the process for setting up Python on
your system will vary. You can determine your local Ubuntu version by running the following
command:
Follow the instructions below that match the version number you see under Release in the console
output:
• Ubuntu 18.04, Ubuntu 20.04 and above: Python 3.8 doesn’t come by default on Ubuntu
18.04 and above, but it is available in the Universe repository. To install version 3.8, open a
terminal application and type the following commands:
Once the installation is complete, you can run Python 3.8 with the python3.8 command and
pip with the pip3 command.
Programming Language (Python) 27
• Linux Mint and Ubuntu 17 and below: Python 3.8 isn’t in the Universe repository, so you need
to get it from a Personal Package Archive (PPA). For example, to install from the
“deadsnakes” PPA, use the following commands:
• Once the installation is complete, you can run Python 3.8 with the python3.8 command and
run pip with the pip3 command.
- Chapter 4 -
Python Quickstart
Objectives:
4.1 Introduction
Python is an interpreted programming language, this means that as a developer you write Python
(.py) files in a text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:
Let's write our first Python file, called helloworld.py, which can be done in any text editor.
Simple as that. Save your file. Open your command line, navigate to the directory where you
saved your file, and run:
Congratulations, you have written and executed your first Python program.
Programming Language (Python) 29
To test a short amount of code in python sometimes it is quickest and easiest not to write the code
in a file. This is made possible because Python can be run as a command line itself.
Or, if the "python" command did not work, you can try "py":
From there you can write any python, including our hello world example from earlier in the tutorial:
Whenever you are done in the python command line, you can simply type the following to quit the
python command line interface:
Programming Language (Python) 30
- Chapter 5 -
5.1 Introduction
The Python language has many similarities to Perl, C, and Java. However, there are some definite
differences between the languages.
Type the following text at the Python prompt and press the Enter –
If you are running new version of Python, then you would need to use print statement with
parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the
following result –
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is no longer
active.
Let us write a simple Python program in a script. Python files have extension .py. Type the
following source code in a test.py file –
We assume that you have Python interpreter set in PATH variable. Now, try to run this
program as follows –
Let us try another way to execute a Python script. Here is the modified test.py file –
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run
this program as follows –
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero
or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python
is a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.
The following list shows the Python keywords. These are reserved words and you cannot use them
as constant or variable or any other identifier names. All the Python keywords contain lowercase
letters only.
Programming Language (Python) 34
Python provides no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be
indented the same amount. For example −
Thus, in Python all the continuous lines indented with same number of spaces would form a block.
The following example has various statement blocks −
Programming Language (Python) 35
Note − Just make sure you understood various blocks even if they are without braces.
Programming Language (Python) 36
Statements in Python typically end with a new line. Python does, however, allow the use of the
line continuation character (\) to denote that the line should continue. For example –
Statements contained within the [], {}, or () brackets do not need to use the line continuation
character. For example –
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as
the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are
legal –
Programming Language (Python) 37
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the end of the physical line are part of the comment and the Python interpreter ignores
them.
You can type a comment on the same line after a statement or expression –
Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comment:
Programming Language (Python) 38
- Chapter 6 -
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
There are following logical operators supported by Python language. Assume variable a
holds 10 and variable b holds 20 then
Programming Language (Python) 43
- Chapter 7 -
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You
need to determine which action to take and which statements to execute if outcome is TRUE or
FALSE otherwise.
Following is the general form of a typical decision-making structure found in most of the
programming languages –
Python programming language assumes any non-zero and non-null values as TRUE, and if
it is either zero or null, then it is assumed as FALSE value. Python programming language
provides following types of decision-making statements.
Programming Language (Python) 44
Programming Language (Python) 45
If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.
7.3 Loops
Programming languages provide various control structures that allow for more
complicated execution paths.
- Chapter 8 -
Tuple Matching in Python is a method of grouping the tuples by matching the second
element in the tuples. It is achieved by using a dictionary by checking the second element
in each tuple in python programming. However, we can make new tuples by taking
portions of existing tuples.
Tuple Syntax
To write an empty tuple, you need to write as two parentheses containing nothing-
For writing tuple for a single value, you need to include a comma, even though there is a
single value. Also at the end you need to write semicolon as shown below.
Tuple indices begin at 0, and they can be concatenated, sliced and so on.
Programming Language (Python) 49
Python has tuple assignment feature which enables you to assign more than one variable
at a time. In here, we have assigned tuple 1 with the persons information like name,
surname, birth year, etc. and another tuple 2 with the values in it like number (1,2,3,….,7).
For Example,
(name, surname, birth year, favorite movie and year, profession, birthplace) = Robert
In packing, we place value into a new tuple while in unpacking we extract those values
back into variables.
The comparison starts with a first element of each tuple. If they do not compare to =,< or
> then it proceed to the second element and so on.
It starts with comparing the first element from each of the tuples
Case1: Comparison starts with a first element of each tuple. In this case 5>1, so the output
a is bigger
Case 2: Comparison starts with a first element of each tuple. In this case 5>5 which is
inconclusive. So it proceeds to the next element. 6>4, so the output a is bigger
Case 3: Comparison starts with a first element of each tuple. In this case 5>6 which is false.
So it goes into the else block and prints "b is bigger."
Programming Language (Python) 52
Since tuples are hashable, and list is not, we must use tuple as the key if we need to create
a composite key to use in a dictionary.
Inside the brackets, the expression is a tuple. We could use tuple assignment in a for loop
to navigate this dictionary.
This loop navigates the keys in the directory, which are tuples. It assigns the elements of
each tuple to last and first and then prints the name and corresponding telephone
number.
- Chapter 9 -
Python Tutorials
This is going to be a simple guessing game where the computer will generate a random
number between 1 to 10, and the user has to guess it in 5 attempts.
Based on the user’s guess computer will give various hints if the number is high or low. When
the user guess matches the number computer will print the answer along with the number
of attempts.
In this tutorial, we will guide you through each step of making this interactive guessing
game in Python.
2. First, we will create a file a new file named game.py from our text editor.
3. To generate a random number we will use a Python module named random to use
this module in our program, we first need to import it.
4. Next, we will use the random module to generate a number between 1 to 10 and
store it in a variable named number.
5. Now we will prompt the user to enter his name and store it to a variable
named player_name.
6. In the next step, we will create a variable named “number_of_guesses” and assign
0 to it. Later we will increase this value on each iteration of the while loop.
Programming Language (Python) 55
7. Finally, before constructing the while loop, we will print a string which includes the
player name.
9. In the first line, we are defining the controlling expression of the while loop. Our
game will give user 5 attempts to guess the number, hence less than 5 because we
have already assigned the “number_of_guesses” variable to 0.
10. Within the loop, we are taking the input from the user and storing it in the guess
variable. However, the user input we are getting from the user is a string object and
to perform mathematical operations on it we first need to convert it to an integer
which can be done by the Python’s inbuilt int() method.
Programming Language (Python) 56
11. In the next line, we are incrementing the value of “number_of_guesses” variable by
Below it, we have 3 conditional statements.
• In the first, if statement we are comparing if the guess is less than the generated
number if this statement evaluates to true, we print the corresponding Guess.
• Similarly, we are checking if the guess is greater than the generated number.
• The final if statement has the break keyword, which will terminate the loop
entirely, So when the guess is equal to the generated number loop gets
terminated.
12. Below the while loop, we need to add another pair of condition statement:
13. Here we are first verifying if the user has guessed the number or not. if they did, then
we will print a message for them along with the number of tries.
Programming Language (Python) 57
14. If the player couldn’t guess the number at the end we will print the number along
with a message.
Final output:
15. To run the game, type this in your terminal python game.py and hit Enter.