0% found this document useful (0 votes)
32 views

EBook - Programming Language Using PHP - Python

Uploaded by

Elle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

EBook - Programming Language Using PHP - Python

Uploaded by

Elle
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

Published by Advanced Business Systems Consultants Sdn Bhd

Lot 43-44, 1st Floor, Likas Square Commercial Centre,


Jalan Istiadat Likas, 88400 Kota Kinabalu, Sabah, Malaysia.

Tel: +(6) 088-235218


Fax: +(6) 088-245955
Email: [email protected]
Website: www.amc.edu.my

eISBN 978-967-2285-06-9

Copyright © Advanced Business Systems Consultants Sdn Bhd

All right reserved. No part of this publication may be reproduced,


stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording or otherwise,
without permission of the copyright holder.

© All right reserved, Intellectual Property Corporation of Malaysia (MyIPO) 2019


PHP Programming Language Level 1

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 2 PHP SYNTAX


2.1 Introduction 7
2.2 Semicolons 8
2.3 Comments in PHP 8
2.4 Arithmetic 8
2.5 Strings 9

CHAPTER 3 PHP VARIABLES


3.1 Introduction 10
3.2 PHP is a Loosely Typed Language 11
3.3 PHP String Variables 11
3.4 The Concatenation Operator 12
3.5 Introducing Function 13
3.6 The strlen() function 13
3.7 The substr() function 13
3.8 The strtoupper() and strtolower() function 14
3.9 The strpos() function 14
3.10 PHP String Reference 15

CHAPTER 4 OPERATOR
4.1 Introduction 19
4.2 Assignment Operators 20
4.3 Comparison Operators 22
4.4 PHP Logical Operators 29

CHAPTER 5 PHP IF STATEMENT


5.1 Introduction 32
5.2 Conditional Logic 32
5.3 IF Statement 33
5.4 IF … else Statement 37
5.5 IF… else if Statements 39

CHAPTER 6 PHP SWITCH STATEMENTS


6.1 Introduction 42
6.2 Switch ($variable_name) { 43
6.3 Case 'What_you_want_to_check_for': 43
6.4 //code here 43
6.5 break; 43
6.6 Default: 43

i
PHP Programming Language Level 1

CHAPTER 1 INTRODUCTION OF PHP


1.1 Introduction
PHP is a powerful tool for making dynamic and interactive Web pages.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP.
You should have a basic understanding of the following:

 HTML/XHTML
 JavaScript

What is PHP?

• PHP stands for PHP: Hypertext Preprocessor


• PHP is a server-side scripting language, like ASP
• PHP scripts are executed on the server
• PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, etc.)
• PHP is an open source software
• PHP is free to download and use

What is a PHP File?

• PHP files can contain text, HTML tags and scripts


• PHP files are returned to the browser as plain HTML
• PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?

• MySQL is a database server


• MySQL is ideal for both small and large applications
• MySQL supports standard SQL
• MySQL compiles on a number of platforms
• MySQL is free to download and use

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?

• PHP runs on different platforms (Windows, Linux, Unix, etc.)


• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP is FREE to download from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side

Where to Start?

To get access to a web server with PHP support, you can:

• Install Apache (or IIS) on your own server, install PHP, and MySQL
• Or find a web hosting plan with PHP and MySQL support

1.2 PHP Installation


What do you need?

Most people would prefer to install an all-in-one solution:

WampServer 2.0i [07/11/09] for Windows platform


Includes:
 Apache 2.2.11
 MySQL 5.1.36
 PHP 5.3.0

http://www.wampserver.com/en/

http://lamphowto.com/ for Linux platform

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

1.3 Installing and Testing Wampserver

If the installation went well, you should have a new icon in the bottom right, where the clock is:

Click the icon to see the menu above.

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

1.4 Saving Your PHP Files

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

Already have a web server?


If your server supports PHP you don’t need to do anything.
Just create some .php files in your web directory, and the server will parse them for you.
Because it is free, most web hosts offer PHP support. However, if your server does not support PHP,
you must install PHP. Here is a link to a good tutorial from PHP.net on how to install PHP5:
http://www.php.net/manual/en/install.php

Download PHP
Download PHP for free here: http://www.php.net/downloads.php

Download MySQL Database


Download MySQL for free here: http://www.mysql.com/downloads/index.html

Download Apache for free hete: http://httpd.apache.org/download.ogi

6
PHP Programming Language Level 1

CHAPTER 2 PHP SYNTAX


2.1 Introduction
PHP code is executed on the server, and the plain HTML result is sent to the browser.

Basic PHP Syntax

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

echo “HI EVERYONE”;

?>

</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

“Use your semicolons!”;

?>

2.3 Comments In PHP


In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.

<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!”

You can type a string all at once, like this:

<?php echo “HI EVERYONE!”;

Or use the concatenation operator, which glues several strings together:

<?php echo “HI,”. “ “ . “world” . “!”;

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

CHAPTER 3 PHP VARIABLES


3.1 Introduction
A variable is used to store information. A variable is just a name PHP uses to keep track of a value.

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.

All variables in PHP start with a $ sign symbol, called a sigil.

The correct way of declaring a variables in PHP:

$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:

<?php echo $total; ?>

PHP will respond with the sum 108.

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

$txt= “HI EVERYONE”;


$myAge=16;

echo $txt;
echo $myAge;

?>

10
PHP Programming Language Level 1

3.2 PHP Is A Loosely Typed Language


In PHP, a variable does not need to be declared before adding a value to it. In the example above,
you see that you do not have to tell PHP which data type the variable is.

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.

Naming Rules for Variables

 A variable name must start with a letter or an underscore “_”

 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)

3.3 PHP String Variables


A string variable is used to store and manipulate text.

String Variables in PHP


String variables are used for values that contain characters.

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

$txt= “HI EVERYONE”;


echo $txt;

?>

The output of the code above will be:

HI EVERYONE

11
PHP Programming Language Level 1

3.4 The Concatenation Operator


There is only one string in PHP.

The concatenation operator ( . ) is used to put two string values together.

To concatenate two string variables together, use the concatenation operator:

<?php

$txt1 = “HI EVERYONE”;


$txt2 = “What a nice day!”;

echo $txt1 . “ “ . $txt2;

?>

The output of the code above will be:

HI EVERYONE What a nice day!

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

3.5 Introducing Function


Functions are reusable pieces of code that you can use throughout an application, saving a lot of
time to copying and pasting.

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.

3.6 The strlen() Function


strlen() is one of the most common String functions in PHP. You pass it a string, or variable
containing a string, and it returns the number of characters in that string.

The strlen() function is used to return the length of a string.

Let’s find the length of a string:

<?php

echo strlen(“HI EVERYONE”);

?>

The output of the code above will be: 11

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).

3.7 The substr() Function


Another very common string function is substr(). This function allows you to return a substring
(piece of) of your 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”;

// you can manipulate string easily


// with built-in function too

$partial = substr ($myname, 0, 3);

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

3.8 The strtoupper() and strtolower() Function


Two other very useful string functions are strtoupper() and strtolower(), which make your entire
string UPPERCASE or lowercase. Example:

$uppercase = strtoupper($myname);

echo $uppercase;

// prints “DAVID”

$lowercase = strtolower($uppercase)

echo $lowercase;

// prints “david”

You can also call these functions on a string directly, like:

echo strtolower (“David”);

// prints “david”

3.9 The strpos() Function


The strops() function is used to search for character within a string.

Is a match is found, this function will return the position of the first match. If no match is found, it
will return FALSE.

Let’s see if we can find the string “EVERYONE” in our string:

<?php

echo strops (“HI EVERYONE” , “EVERYONE”);

?>

The output of the code above will be: 3

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

3.10 PHP String Reference


The reference contains a brief description, and examples of use, for each function. The PHP string
functions are part of the PHP core. No installation is required to use these functions. For a
reference of all string function:

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

parse_str() Parses a query string into variables


print() Outputs one or more strings
printf() Outputs a formatted string
quoted_printable_decode() Converts a quoted-printable string to an 8-bit string
quoted_printable_encode() Converts an 8-bit string to a quoted printable string
quotemeta() Quotes meta characters
Removes whitespace or other characters from the right side of a
rtrim()
string
setlocale() Sets locale information
sha1() Calculates the SHA-1 hash of a string
sha1_file() Calculates the SHA-1 hash of a file
similar_text() Calculates the similarity between two strings
soundex() Calculates the soundex key of a string
sprintf() Writes a formatted string to a variable
sscanf() Parses input from a string according to a format
str_getcsv() Parses a CSV string into an array
str_ireplace() Replaces some characters in a string (case-insensitive)
str_pad() Pads a string to a new length
str_repeat() Repeats a string a specified number of times
str_replace() Replaces some characters in a string (case-sensitive)
str_rot13() Performs the ROT13 encoding on a string
str_shuffle() Randomly shuffles all characters in a string
str_split() Splits a string into an array
str_word_count() Count the number of words in a string
strcasecmp() Compares two strings (case-insensitive)
Finds the first occurrence of a string inside another string (alias of
strchr()
strstr())
strcmp() Compares two strings (case-sensitive)
strcoll() Compares two strings (locale based string comparison)
Returns the number of characters found in a string before any part of
strcspn()
some specified characters are found
strip_tags() Strips HTML and PHP tags from a string
stripcslashes() Unquotes a string quoted with addcslashes()
stripslashes() Unquotes a string quoted with addslashes()
Returns the position of the first occurrence of a string inside another
stripos()
string (case-insensitive)
Finds the first occurrence of a string inside another string (case-
stristr()
insensitive)
strlen() Returns the length of a string
Compares two strings using a "natural order" algorithm (case-
strnatcasecmp()
insensitive)

16
PHP Programming Language Level 1

Compares two strings using a "natural order" algorithm (case-


strnatcmp()
sensitive)
strncasecmp() String comparison of the first n characters (case-insensitive)
strncmp() String comparison of the first n characters (case-sensitive)
strpbrk() Searches a string for any of a set of characters
Returns the position of the first occurrence of a string inside another
strpos()
string (case-sensitive)
strrchr() Finds the last occurrence of a string inside another string
strrev() Reverses a string
Finds the position of the last occurrence of a string inside another
strripos()
string (case-insensitive)
Finds the position of the last occurrence of a string inside another
strrpos()
string (case-sensitive)
Returns the number of characters found in a string that contains only
strspn()
characters from a specified charlist
Finds the first occurrence of a string inside another string (case-
strstr()
sensitive)
strtok() Splits a string into smaller strings
strtolower() Converts a string to lowercase letters
strtoupper() Converts a string to uppercase letters
strtr() Translates certain characters in a string
substr() Returns a part of a string
Compares two strings from a specified start position (binary safe and
substr_compare()
optionally case-sensitive)
substr_count() Counts the number of times a substring occurs in a string
substr_replace() Replaces a part of a string with another string
trim() Removes whitespace or other characters from both sides of a string
ucfirst() Converts the first character of a string to uppercase
ucwords() Converts the first character of each word in a string to uppercase
vfprintf() Writes a formatted string to a specified output stream
vprintf() Outputs a formatted string
vsprintf() Writes a formatted string to a variable
wordwrap() Wraps a string to a given number of characters

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

5 //Get a partial string from within your own name


6 // and print it to the screen!

7 .

8 ?>
9 </p>

10 <p>
11 <?php

12 // make your name upper case and print it to the screen:

13 .

14 ?>
15 </p>

16 <p>
17 <?php

18 // Make your name lower case and print it to the screen:

19 .

20 ?>
21 </p>

22 </body>
23 </html>

18
PHP Programming Language Level 1

CHAPTER 4 OPERATOR
4.1 Introduction

There are five basic arithmetic operators.


 + (addition)
 - (subtraction)
 * (multiplication)
 / (division)
 % (modulus)

The operators are summarized in the following table.

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y.

- Subtraction $x - $y Difference of $x and $y.

* Multiplication $x * $y Product of $x and $y.

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y.

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

4.2 Assignment Operators

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

$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4.

?>

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.

Example #1 Assigning by reference

<?php
$a = 3;
$b = &$a; // $b is a reference to $a

print "$a\n"; // prints 3


print "$b\n"; // prints 3

$a = 4; // change $a

print "$a\n"; // prints 4


print "$b\n"; // prints 4 as well, since $b is a reference to $a, which has
// been changed
?>

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.

For example, this code will result in a warning:

<?php
class C {}

/* The following line generates the following error message:


* Deprecated: Assigning the return value of new by reference is deprecated in...
*/
$o = &new C;
?>

21
PHP Programming Language Level 1

These are following assignment operators supported by PHP language:

Operator Description Example

= Simple assignment operator, Assigns C = A + B will assign value of A + B into C


values from right side operands to left
side operand

+= Add AND assignment operator, It adds C += A is equivalent to C = C + A


right operand to the left operand and
assign the result to left operand

-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A


subtracts right operand from the left
operand and assign the result to left
operand

*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A


multiplies right operand with the left
operand and assign the result to left
operand

/= Divide AND assignment operator, It C /= A is equivalent to C = C / A


divides left operand with the right
operand and assign the result to left
operand

%= Modulus AND assignment operator, It C %= A is equivalent to C = C % A


takes modulus using two operands
and assign the result to left operand

4.3 Comparison Operators

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.

Operator Name Example Result

== Equal $x == $y TRUE if $x is exactly equal to $y

=== Identical $x === TRUE if $x is exactly equal to $y, and they are of the same type.
$y

!= Not equal $x != $y TRUE if $x is exactly not equal to $y.

22
PHP Programming Language Level 1

<> Not equal $x <> $y TRUE if $x is exactly not equal to $y.

!== 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

>= Greater $x >= $y TRUE if $x is greater than or equal to $y.


than or
equal to

Pictorial Presentation Of Equal (==) Operator

23
PHP Programming Language Level 1

Test Equal (==) operator______________________________________________________________

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)

Pictorial Presentation Of Strict Equal (===) Operator

Test Strict Equal (===) Operator

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";

var_dump($x === $y);

?>

Output : bool(false)

24
PHP Programming Language Level 1

Pictorial Presentation Of Not Equal(!=)/(<>) Operator

Test Not Equal (!=) / (<>) Operator

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);

?>

Output: bool (false)

Test Not Identical (!==) Operator_______________________________________________________

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";

var_dump($x !== $y);

?>

Output: bool(true)

25
PHP Programming Language Level 1

Pictorial Presentation Of Greater Than (>) Operator

Test Greater Than(>) Operator

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)

Pictorial Presentation Of Greater Than Or Equal (>=)

26
PHP Programming Language Level 1

Test Greater Than Or Equal (>=) Operator

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)

Pictorial Presentation Of Less Than (<) Operator

Test Less Than (<) Operator

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

Pictorial Presentation Of Less Than Or Equal (<=) Operator

Test Less Than Or Equal (<=) Operator

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

4.4 PHP Logical Operators

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.

 The && Operator


The && symbols mean AND. Use this if you need both values to be true, as in our username
and password test. After all, you don't want to let people in if they just get the username
right but not the password! Here's an example:

$username ='user';
$password ='password';

if ($username =='user' && $password =='password') {

print("Welcome back!");

}
else {

print("Invalid Login Detected");

The if statement is set up the same, but notice that now two conditions are being tested:

$username =='user' && $password =='password’

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';

if ($total_spent ==100 | | $special_key =='SK12345') {

print("Discount Granted!");

}
else {

print("No discount for you!");

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:

$username =='user' && $password =='password

With this

$username =='user' AND $password =='password

And this:

$total_spent ==100 | | $special_key =='SK12345'

With this:

$total_spent ==100 OR $special_key =='SK12345'

It's up to you which you use. AND is a lot easier to read than &&. OR is a lot easier to read
than ||.

The difference, incidentally, is to do with Operator Precedence. We touched on this when


we discussed variables, earlier. Logical Operators have a pecking order, as well.

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;

if ($contestant_one XOR $contestant_two) {

print("Only one winner!");

}
else {

print("Both can't win!");

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

CHAPTER 5 PHP IF STATEMENT


5.1 Introduction
If you have stored a username in a variable, for example, you'll then need to check if this is a valid
username. To help you do the checking, something called Conditional Logic comes in very handy
indeed. In this section, we'll take a look at just what Conditional Logic is. In the next section, we'll do
some practical work.

5.2 Conditional Logic


Conditional Logic is all about asking "What happens IF ... ". When you press a button labelled "Don't
Press this Button - Under any circumstance!" you are using Conditional Logic. You are asking, "Well,
what happens IF I do press the button?"

You use Conditional Logic in your daily life all the time:

"If I turn the volume up on my stereo, will the neighbours be pleased?"


"If spend all my money on a new pair of shoes, will it make me happy?"
"If I study this course, will it improve my web site?"

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."

In PHP, you use the "IF" word like this:

if ($User_Name == "authentic") {

//Code to let user access the site here;

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") }

//Code to Let user access the site here;

And so will this:

if ($User_Name == "authentic") {

//Code to Let user access the site here;

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) {

//your code here;

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:

<IMG SRC =cat.jpg>

Just plain HTML. But you can put that code inside of the print statement:

print ("<IMG SRC =images/cat.jpg>");

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.

(Create your own folder and also the image name.)

Copy the images folder to your www (root) directory. Then try the following script:

<?PHP

print ("<IMG SRC =images/cat.jpg>");

?>

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.

To clarify things, let's have some more practical example of If Statements.

Some Practise with PHP If Statements

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) {

print ("<IMG SRC =images/kitten.jpg>");

?>

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.

The first two lines just set up some variables:

$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”.

What we want to say is:

"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) {

print ("<IMG SRC =images/kitten.jpg>");

You need the semi-colon at the end of the print statement.

But if your if statement only runs to one line, you can just do this:

if ($kitten_image == 1) { print ("<IMG SRC = images/kitten.jpg>"); }

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) {

print ("<IMG SRC =images/kitten.jpg>");

if ($cat_image == 1) {

print ("<IMG SRC =images/cat.jpg>");

?>

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:

print ("<IMG SRC =images/cat.jpg>");

In the next section, we'll take a look at if ... else statements.

if … else Statements in PHP

36
PHP Programming Language Level 1

5.4 IF … else Statement


Instead of using two if statements, as in the previous lesson, we can use the if ... else statement. Like
this:

<?PHP

$kitten_image = 0;
$cat_image = 1;

if ($kitten_image == 1) {

print ("<IMG SRC =images/kitten.jpg>");

}
else {

print ("<IMG SRC =images/cat.jpg>");

?>

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.

Following is the syntax for the if else statement:

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 {

print ("<IMG SRC =images/cat.jpg>");

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

5.5 IF… else if Statements


You can also add “else if” parts to the If Statements you've been exploring in the previous sections.
The syntax is this:

else if (another_condition_to_test) {

Change your code to this, to see how else if works:

<?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) {

print ("<IMG SRC =images/cat.jpg>");

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

Sample script of ‘selectPicture.php’ file

<html>
<head>
<title>PHP Test</title>
</head>
<body>

<form Name = "f1" action="selectPicture.php" method="post">


<select name="picture">
<option value="none">Select a Picture</option>
<option value="church">Cat</option>
<option value="kitten">Kitten</option>
<option value="planet">Planet</option>
<option value="cartoon">Cartoon</option>
<option value="space">Space Image</option>
<option value="abstract">Photoshop Abstract</option>
</select>

<input type="submit" name = "Submit" Value = "Choose an Image">


</form>

<?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

CHAPTER 6 PHP SWITCH STATEMENTS

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;

It looks a bit complex, so we'll break it down.

42
PHP Programming Language Level 1

6.2 Switch ($variable_name) {


You Start with the word 'Switch' then a pair of round brackets. Inside of the round brackets, you type
the name of the variable you want to check. After the round brackets, you need a left curly bracket.

6.3 Case 'What_you_want_to_check_for':

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 ( : ).

6.4 //code here

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

CHAPTER 1: PHP ARRAYS


1.1 What are Arrays 3

1.2 Numeric Arrays 4

1.3 Associative Arrays 6

1.4 Multidimensional Arrays 7

1.5 Exercise 1 11

1.6 Exercise 2 11

CHAPTER 2: PHP LOOPING – WHILE LOOPS


2.1 The Loops 15

2.2 The while Loop 15

2.3 The do…while statement 19

2.4 Exercise 3 21

CHAPTER 3: PHP LOOPING – FOR LOOPS


3.1 The for Loop 22

3.2 The foreach Loop 24

3.3 Exercise 4 25

3.4 Exercise 5 28

CHAPTER 4: PHP FUNCTIONS


4.1 PHP Functions 30

4.2 Create a PHP Function 30

4.3 PHP Function – Adding parameters 31

4.4 PHP Functions – Return values 33

4.5 Exercise 6 34

1
PHP Programming Language Level 2

CHAPTER 5: PHP FORMS AND USER INPUT


5.1 PHP Form Handling 36

5.2 Form Validation 37

5.3 The $_GET Function 37

5.4 When to se method=”get”? 38

5.5 The $_POST Function 39

5.6 Exercise 7 41

2
PHP Programming Language Level 2

CHAPTER 1: PHP ARRAYS


An array stores multiple values in one single variable.

1.1 What is an Array?


A variable is a storage area holding a number or text. The problem is, a variable will hold only one value.

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?

The best solution here is to use an array!

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:( , ) .

In PHP, there are three kinds of arrays:

 Numeric array – An array with a numeric index

 Associative array – An array where each ID key is associated with a value

 Multidimensional array – An array containing one or more arrays.

1.2 Numeric Arrays


A numeric array stores each array element with a numeric index.

There are two methods to create a numeric array.

1. In the following example the index are automatically assigned (the index starts at 0):

$cars = array (“Saab”, “Volvo”, “Toyota”);

2. In following example we assign the index manually:

$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

Echo $cars[0] . “ and “ . $cars[1] . “ are Swedish cars.”;

?>

The code above will output:

Saab and Volvo are Swedish cars.

Get The Length of an Array – The count() Function


The count() function is used to return the length (the number of elements) of an array:

Example: Try to run this code and see the output.

<?php

$cars=array (“Volvo”, “BMW”, “Toyota”);

Echo count($cars);

?>

Loop Through an Indexed Array


To loop through and print all the values of an indexed array, you could use a for loop, like this:

<?php

$cars=array (“Volvo”, “BMW”, “Toyota”);


$arrlength=count($cars);

For ($x=0; $x<$arrlength; $x++)

{
echo $cars[$x];
echo “<br>”;
}

?>

5
PHP Programming Language Level 2

1.3 Associative Arrays


An associative array, each ID key is associated with a value.

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

In this example we use an array to assign ages to the different person:

$ages = array (“Peter” =>32, “Quagmire” =>30, “Joe”=>34);

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”;

The ID keys can use in a script:

<?php

$ages[‘Peter’] = “32”;

$ages[‘Quagmire’] = “30”;

$ages[‘Joe’] = “34”;

Echo “Peter is “ . $ages[‘Peter’] . “ years old.”;

?>

6
PHP Programming Language Level 2

The code above will output:

Peter is 32 years old.

1.4 Multidimensional Arrays


In a multidimensional array, each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:

$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
)

[Quagmire] => Array

(
[0] => Glenn
)

[Brown] => Array

(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)

Example 2

Let’s try displaying a single value from the array above:

echo “Is” . $families[‘Griffin’] [2] .

“ a part of the Griffin family?”;

The code above will output:

Is Megan a part of the Griffin family?

8
PHP Programming Language Level 2

Complete PHP Array Reference

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

key() Fetches a key from an array


krsort() Sorts an associative array in descending order, according to the key
ksort() Sorts an associative array in ascending order, according to the key
list() Assigns variables as if they were an array
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order

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 ‘ ).

Use [] notation to echo or print the third element of the array.

<html>
<head>

<title>My First Array</title>

</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>

<h2>Large Cities<br /></h2>

<?php

//Create array.

$cities=array(

"Tokyo",

"Mexico City",

"New York City",

"Mumbai",

"Seoul",

"Shanghai",

"Lagos",

"Buenos Aires",

"Cairo",

"London"

);

//Print values of array to browser, separated by commas.

foreach($cities as $c){

echo "$c, ";

//Sort array.

sort($cities);

13
PHP Programming Language Level 2

//Print array as bulleted list.

echo "\n<ul>\n" ;

foreach($cities as $c){

echo "<li>$c</li>\n";

echo "</ul>" ;

//Add four cities to array.

array_push($cities, "Los Angeles", "Calcutta", "Osaka", "Beijing") ;

//Sort again, and print bulleted list.

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

CHAPTER 2: PHP LOOPING – WHILE LOOPS


If you want to repeat the execution of a code block you can use loops in any programming languages. In
PHP there are more ways to do it. First we will discuss the while loop, which is maybe the simplest loop
type in PHP. The loops in general check their condition and depends on the result the code block will be
executed 1 or more times or will not be executed at all. So the definition of the while loop is a bit similar
to the definition of the statement.

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.

2.1 PHP Loops


Often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this. In
Php, we have the following looping statements:

 While – loops through a block of code while a specified condition is true


 Do…while – loops through a block of code once, and then repeats the loop as long as a specified
condition is true
 For – loops through a block of code a specified number of times
 Foreach – loops through a block of code for each element in an array

2.2 The while Loop


A while loop will execute as long as a certain condition is true. For example, the loop in the editor will
simulate coin flips as long as the number of consecutive heads is less than 5.

The while loop executes a block of code while a 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)

echo “The number is “ . $i . “<br/>”;

$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.

Break and continue in while 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;

while ($x < 10)

$x++;

if ($x<5) continue;

echo “$x<br/>;

Using Endwhile

PHP offers the following alternative syntax for while loops:

while (condition):

//looped statement go here

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

2.3 The do…while Statement


This loop variant is very similar to the while loop. However there is one important difference. With do
while loop the code block will be executed at least once. This is because in case of a do while loop PHP
checks the condition only after the first iteration. It is clearly visible from the syntax:

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++;

echo “The number is “ . $i . “<br/>”;

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

2.4 Exercise 3: Completing the Loop


Fill in the missing punctuation to make sure the do…while loop in the editor executes correctly. You will
need to fill in the following characters:

{ } ( ) ; ;

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

8 echo “<p>Now the loop is done running.</p>

9 ?>

10 </body>

11 </html>

21
PHP Programming Language Level 2

CHAPTER 3: PHP LOOPING – FOR LOOPS


Loops execute a block of code a specified number of times, or while a specified condition is true.

3.1 The for Loop


The for loop is used when you know in advance how many times the script should run.

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.

It break down like this:

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

For (init; condition; increment)


{
code to be execute;
}

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

Writing Your First ‘For’ Loop


Be very careful when constructing your loop – in particular, make sure your loop is written with
conditions that will allow it to end.

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.

3.2 The foreach Loop


The foreach loop is a bit special control structure. Foreach was designed to iterate over an array and
you can use it only for array variables.

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

Foreach ($array as $value)

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”);

foreach ($x as $value)

echo $value . “<br/>”;

?>

</body>

</html>

Output:

one

two

three

25
PHP Programming Language Level 2

Practicing with ForEach.

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

$number=array (1, 2, 3);

foreach ($numbers as $item)


{

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.

Foreach for associative arrays


Sometimes it would be usefull to display not only the array values but the keys as well. In this case you
don’t have to choose another looping statement. There is a much better way. The foreach statement
has an addition syntax as well designed to solve this problem.

The syntax is:

Foreach (array_expression as $key => $value) statement

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);

foreach ($test as $key => $value) {


echo "$key - $value <br/>" ;
}

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

8 $yardlines = array("The 50... ", "the 40... ",

9 "the 30... ", "the 20... ", "the 10... ");

10 // Write your foreach loop below this line

// Write your foreach loop above this line

11 echo "touchdown!";

12 ?>

13 </p>

14 </body>

15 </html>

27
PHP Programming Language Level 2

3.4 Exercise 5: Nested For Loops


HTML tables involve a lot of repetitive coding – a perfect place to use for loops. You can do even more if
you nest the for loops.

Use two for loops, one nested inside another. Create the following multiplication table:

Output:

Answer:

<html>

<body>

<h2>Nested Loop Multiplication Table</h2>

<?php

//Generate an HTML table

echo "<table border=\"1\">";

//Generate table data showing the numbers 1-7 multiplied by each other,

//starting with the rows.

28
PHP Programming Language Level 2

for ($row=1; $row<=7; $row++){

echo "<tr>\n";

//Generate each entry in the row to create the columns.

for ($col=1; $col<=7; $col++){

//First, do the math.

$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

CHAPTER 4: PHP FUNCTIONS


4.1 PHP Functions
The real power of PHP comes from its functions.

In PHP, there are more than 700 built-in functions.

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.

4.2 Create a PHP Function


A function will be executed by a call to the function.

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

A simple function that writes my name when it is called:

<html>
<body>

<?php
function writeName()
{
echo “Kevin James Michael”;
}

echo “My name is “;


writeName();
?>

30
PHP Programming Language Level 2

</body>
</html>
Output:

My name is Kevin James Michael

4.3 PHP Functions – Adding parameters


To add more functionality to a function, we can add parameters. A parameter is just like a variable.

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)

echo $fname . “ Michael.<br/>”;

echo “My name is “;

writeName (“Kevin James”);

echo “My sister’s name is “;

writeName (“Hege”);

echo “My brother’s name is “;

writeName (“Stale”);

?>

</body>

31
PHP Programming Language Level 2

</html>

Output:

My name is Kevin James Michael.

My sister’s name is Hege Michael.

My brother’s name is Stale Michael.

Example 2

The following function has two parameters:

<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:

My name is Kevin James Michael.


My sister's name is Hege Michael!
My brother's name is Ståle Michael?

32
PHP Programming Language Level 2

4.4 PHP Functions – Return values


Sometimes you want to return a value if you are using functions. This is where the return statement
comes in. To let a function return a value, use the return statement.

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

4.5 Exercise 6: Returning Values


Fill in the code to return a value from a function.

1 <?php

2 //return the addition of two numbers

3 //supplied by the parameters

4 .

5 .

6 .

7 .

8 //add 2 and 4 and put the value in $additionResult

9 .

10 //print the value of $additionResult

11 .

12 //skip a line

13 .

14 //print the value returned by passing

15 //the parameters 10 to the add() function

16 .

17 ?>

Output:

2+4=6

10+10=20

34
PHP Programming Language Level 2

Answer:

1 <?php

2 //return the addition of two numbers

3 //supplied by the parameters

4 function add($num1, $num2)

5 {

6 return $num1 + $num2;

7 }

8 //add 2 and 4 and put the value in $additionResult

9 $additionResult = add(2, 4);

10 //print the value of $additionResult

11 print “2 + 4 = “ . $additionResult;

12 //skip a line

13 print “<br/>”;

14 //print the value returned by passing

15 //the parameters 10 to the add() function

16 print “10 + 10 = “. add(10, 10);

17 ?>

35
PHP Programming Language Level 2

CHAPTER 5: PHP FORMS AND USER INPUT


The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.

5.1 PHP Form Handling


The most important thing to notice when dealing with HTML forms and PHP is that any form element in
an HTML page will automatically be available to your PHP scripts.

Example

The example below contains an HTML form with two input fields and a submit button:

<html>
<body>

<form action=”welcome.php” method=”post”>


Name: <input type=”text” name=”fname” />
Age: <input type=”text” name=”age” />
<input type=”submit” />
</form>

</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”:

“welcome.php” looks like this:

<html>

<body>

Welcome <?php echo $_POST [“fname”]; ?> ! <br />

You are <?php echo $_POST [“age”]; ?> years old.

</body>

</html>

36
PHP Programming Language Level 2

Output could be something like this:

Welcome John!

You are 28 years old.

The PHP $_GET and $_POST functions will be explained in the next chapters.

5.2 Form Validation


Use input should be validated on the browser whenever possible (by client script). Browser validation is
faster and reduces the server load.

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”.

5.3 The $_GET Function


The built-in $_GET function is used to collect values from a form sent 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

<form action=”welcome.php” method=”get”>

Name: <input type=”text” name=”fname” />

Age: <input type=”text” name=”age” />

<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):

Welcome <?php echo $_GET [“fname”]; ?>. <br />

You are <?php echo $_GET[“age”]; ?> years old!

5.4 When to use method=”get”?


When using method=”get” in HTML forms, all variable names and values are displayed in the URL.

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

5.5 The $_POST Function


The built-in $_POST function is used to collect values from a form sent with method=”post”.

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 action=”welcome.php” method=”post”>

Name: <input type=”text” name=”fname” />

Age: <input type=”text” name=”age” />

<input type=”submit” />

</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):

Welcome <?php echo $_POST [“fname”]; ?> ! <br />

You are <?php echo $_POST [“age”]; ?> years old.

39
PHP Programming Language Level 2

When to use method=”post”?


Information sent from a form with the POST method is invisible to others and has no limits on the
amount of information to send.

However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The PHP $_REQUEST Function


The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE.

The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.

Example:

Welcome <?php echo $_REQUEST [“fname”]; ?> ! <br />

You are <? Echo $_REQUEST [“age”]; ?> years old.

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>

<form method="post" action="yourfile.php">

Please enter your favorite city: <br />

<input type="text" name="city" />

<p />

<input type="submit" name="submit" value="Go" />

</form>

</body>

</html>

41
PHP Programming Language Level 2

Response file,

<html>

<body>

<h2>Favorite City</h2>

<?php

//Retrieve string from post submission

$city = $_POST['city'];

echo "Your favorite city is $city.";

?>

</body>

</html>

42
PHP Programming Language Level 2

2. Array from User Input.

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>

<h2>How's your weather? </h2>

<?php

//If form not submitted, display form.

if (!isset($_POST['submit'])){

?>

<form method="post" action="testing.php">

<p>Please enter your information:</p>

City: <input type="text" name="city" />

Month: <input type="text" name="month" />

Year: <input type="text" name="year" />

<p>Please choose the kinds of weather you experienced from the list below.

<br />Choose all that apply. </p>

<input type="checkbox" name="weather[]" value="sunshine" />Sunshine<br />

<input type="checkbox" name="weather[]" value="clouds" />Clouds<br />

<input type="checkbox" name="weather[]" value="rain" />Rain<br />

<input type="checkbox" name="weather[]" value="hail" />Hail<br />

<input type="checkbox" name="weather[]" value="sleet" />Sleet<br />

<input type="checkbox" name="weather[]" value="snow" />Snow<br />

<input type="checkbox" name="weather[]" value="wind" />Wind<br />

<input type="checkbox" name="weather[]" value="cold" />Cold<br />

<input type="checkbox" name="weather[]" value="heat" />Heat<br />

44
PHP Programming Language Level 2

<p />

<input type="submit" name="submit" value="Go" />

</form>

<?php

//If form submitted, process input.

}else{

//Retrieve the date and location information.

$inputLocal = array(

$_POST['city'],

$_POST['month'],

$_POST['year']

);

echo "In $inputLocal[0] in the month of $inputLocal[1] $inputLocal[2], you

observed the following weather:<br /> <ul>";

//Save weather array into a variable.

$weather = $_POST['weather'];

//Iterate through the array to show what the user chose.

foreach($weather as $w){

echo "<li>$w</li>\n";

}
echo "</ul>";
}
?>

</body>

</html>

45
PHP Programming Language Level 2

3. Interactive Form with If-Else Statement

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 form not submitted, display form.

if (!isset($_POST['submit'])){

?>

<form method="post" action="yourfile.php">

<!--Make sure you have entered the name you gave the file as the action.-->

Please enter your favorite city: <br />

<input type="text" name="city" />

<p />

<input type="submit" name="submit" value="Go" />

</form>

<?php

//If form submitted, process input.

}else{

46
PHP Programming Language Level 2

//Retrieve string from form submission.

$city = $_POST['city'];

echo "Your favorite city is $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.

For the second section, you’ll need the following poem:

Laugh on Monday, laugh for danger.

Laugh on Tuesday, kiss a stranger.

Laugh on Wednesday, laugh for letter.

Laugh on Thursday, something better.

Laugh on Friday, laugh for sorrow.

Laugh on Saturday, joy tomorrow.

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>

<h2>Days of the Week</h2>

<?php

//If form not submitted, display form.

if (!isset($_POST['submit'])){

?>

<form method="post" action="testing.php">

Please enter a day of the week: <br />

<input type="text" name="day" />

<p />

<input type="submit" name="submit" value="Go" />

</form>

<?php

//If form submitted, process input.

}else{

//Retrieve string from post submission

$day = $_POST["day"];

if ($day == 'Monday'){

echo "Laugh on Monday, laugh for danger.";

} elseif ($day == 'Tuesday'){

echo "Laugh on Tuesday, kiss a stranger.";

} elseif ($day == 'Wednesday'){

48
PHP Programming Language Level 2

echo "Laugh on Wednesday, laugh for a letter.";

} elseif ($day == 'Thursday'){

echo "Laugh on Thursday, something better.";

} elseif ($day == 'Friday'){

echo "Laugh on Friday, laugh for sorrow.";

} elseif ($day == 'Saturday'){

echo "Laugh on Saturday, joy tomorrow.";

} else {

echo "No information for that day.";

?>

</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.

Once again, here’s the poem:

Laugh on Monday, laugh for danger.

Laugh on Tuesday, kiss a stranger.

Laugh on Wednesday, laugh for letter.

Laugh on Thursday, something better.

49
PHP Programming Language Level 2

Laugh on Friday, laugh for sorrow.

Laugh on Saturday, joy tomorrow.

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>

<body bgcolor="#ffffff" text = "#000000">

<h2>Pick a Day</h2>

<?php

//If form not submitted, show form.

if (!isset($_POST['submit'])){

?>

<form method="post" action="testing.php">

Please choose a day:<p />

<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

<input type="submit" name="submit" value="Go"/>

</form>

<?php

//If form submitted, process input.

}else{

$day = $_POST['day'];

switch($day){

case 'Monday':

echo 'Laugh on Monday, laugh for danger.';

break;

/*Did you remember your break statements for each option?

If not, once started, the script will continue to execute

the instructions to the end of the switch statement.*/

case 'Tuesday':

echo 'Laugh on Tuesday, kiss a stranger.';

break;

case 'Wednesday':

echo 'Laugh on Wednesday, laugh for a letter.';

break;

case 'Thursday':

echo 'Laugh on Thursday, something better.';

break;

case 'Friday':

51
PHP Programming Language Level 2

echo 'Laugh on Friday, laugh for sorrow.';

break;

case 'Saturday':

echo 'Laugh on Saturday, joy tomorrow.';

break;

default:

echo 'No information for that day.';

break;

?>

<p />

<form action="testing.php">

<input type="submit" name="submit" value="Back" onclick="self.location='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 2 How Python Runs Programs 12


2.1 Introducing the Python Interpreter 12
2.2 Execution Model Variations 16

Chapter 3 Getting Started with Python 19


3.1 Installation 19
3.2 How to Install Python on Windows 20
3.3 How to Install Python on Linux 25

Chapter 4 Python Quickstart 28


4.1 Introduction 28
4.2 The Python Command Line 29

Chapter 5 Python – Basic Syntax 30


5.1 Introduction 30
5.2 First Python Progam 30
5.3 Python Identifiers 32
5.4 Reserved Words 33
5.5 Lines and Indentation 34
5.6 Multi-Line Statements 36

Chapter 6 Python – Basic Operators 38


6.1 Overview of Operators 38
6.2 Python Arithmetic Operators 39
6.3 Python Comparison Operators 40
6.4 Python Assignment Operators 41
6.5 Python Logical Operators 42
Programming Language (Python) ii

Chapter 7 Python – Decision Making & Loops 43


7.1 Overview of Python – Decision Making 43
7.2 Single Statement Suites 45
7.3 Loops 46

Chapter 8 Python TUPLE - Pack, Unpack, Compare, Slicing, Delete, Key 48


8.1 Overview of Python - Tuple 48
8.2 Tuple Assignment 49
8.3 Packing and Unpacking 50
8.4 Comparing Tuples 50
8.5 Using tuples as keys in dictionaries 52

Chapter 9 Python Tutorials 53


9.1 Tutorial: Creating A Guessing Game in Python 53
Programming Language (Python) 1

- Chapter 1 -

Introduction
Objectives:

• To understand Python functions


• To understand Python developed and supported
• To understand Python technical strengths

1.1 Introduction to Python

Why Do People Use Python?


Because there are many programming languages available today, this is the usual first
question of newcomers. Given that there are roughly 10 million Python users out there at
the moment, there really is no way to answer this question with complete accuracy; the
choice of development tools is sometimes based on unique constraints or personal
preference.

The primary factors cited by Python users seem to be these:

• 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.

• Developer productivity: Python boosts developer productivity many times beyond


compiled or statically typed languages such as C, C++, and Java. Python code is
typically one-third to one-fifth the size of equivalent C++ or Java code. That means
there is less to type, less to debug, and less to maintain after the fact. Python
programs also run immediately, without the lengthy compile and link steps required
by some other tools, further boosting programmer speed.

• 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.

Is Python a “Scripting Language”?

Python is a general-purpose programming language that is often applied in scripting roles.


It is commonly defined as an object-oriented scripting language—a definition that blends
support for OOP with an overall orientation toward scripting roles. If pressed for a one-liner,
I’d say that Python is probably better known as a general-purpose programming language
that blends procedural, functional, and object-oriented paradigms— a statement that
captures the richness and scope of today’s Python.
Programming Language (Python) 3

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:

• Shell tools: Sometimes when people hear Python described as a scripting


language, they think it means that Python is a tool for coding operating-system-
oriented scripts. Such programs are often launched from console command lines
and perform tasks such as processing text files and launching other programs.
Python programs can and do serve such roles, but this is just one of dozens of
common Python application domains. It is not just a better shell-script language.

• 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.

Who Uses Python Today?

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:

• Google makes extensive use of Python in its web search systems.


• The popular YouTube video sharing service is largely written in Python.
• The Dropbox storage service codes both its server and desktop client software
primarily in Python.
• The Raspberry Pi single-board computer promotes Python as its educational
language.
• EVE Online, a massively multiplayer online game (MMOG) by CCP Games, uses
Python broadly.
• The widespread BitTorrent peer-to-peer file sharing system began its life as a Python
program.
• Industrial Light & Magic, Pixar, and others use Python in the production of animated
movies.
Programming Language (Python) 5

• 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.

1.2 What Can I Do with Python?

In addition to being a well-designed programming language, Python is useful for


accomplishing real-world tasks—the sorts of things developers do day in and day out. It’s
commonly used in a variety of domains, as a tool for scripting other components and
implementing standalone programs. In fact, as a general-purpose language, Python’s
roles are virtually unlimited: you can use it for everything from website development and
gaming to robotics and spacecraft control.

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.

1.3 How Is Python Developed and Supported?

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

Open Source Tradeoffs

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

1.4 What Are Python’s Technical Strengths?

Naturally, this is a developer’s question. If you don’t already have a programming


background, the language in the next few sections may be a bit baffling—don’t worry,
we’ll explore all of these terms in more detail as we proceed through this book. For
developers, though, here is a quick introduction to some of Python’s top technical features.

It’s Object-Oriented and Functional

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.

In addition to its original procedural (statement-based) and object-oriented (classbased)


paradigms, Python in recent years has acquired built-in support for functional
programming — a set that by most measures includes generators, comprehensions,
closures, maps, decorators, anonymous function lambdas, and first-class function objects.
These can serve as both complement and alternative to its OOP tools.
Programming Language (Python) 10

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.

As mentioned earlier, Python development is performed by a community that largely


coordinates its efforts over the Internet. It consists of Python’s original creator—Guido van
Rossum, the officially anointed Benevolent Dictator for Life (BDFL) of Python—plus a
supporting cast of thousands. Language changes must follow a formal enhancement
procedure and be scrutinized by both other developers and the BDFL. This tends to make
Python more conservative with changes than some other languages and systems. While
the Python 3.X/2.X split broke with this tradition soundly and deliberately, it still holds
generally true within each Python line.

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.

• Automatic memory management: Python automatically allocates objects and


reclaims (“garbage collects”) them when they are no longer used, and most can
grow and shrink on demand. As you’ll learn, Python keeps track of low-level
memory details so you don’t have to.

• Programming-in-the-large support: For building larger systems, Python includes tools


such as modules, classes, and exceptions. These tools allow you to organize systems
into components, use OOP to reuse and customize code, and handle events and
errors gracefully. Python’s functional programming tools, described earlier, provide
additional ways to meet many of the same goals.

• 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.

• Third-party utilities: Because Python is open source, developers are encouraged to


contribute precoded tools that support tasks beyond those supported by its built-
ins; on the Web, you’ll find free support for COM, imaging, numeric programming,
XML, database access, and much more.
Programming Language (Python) 12

- Chapter 2 -

How Python Runs Programs


Objectives:

• To understand Python Interpreter


• To understand the Python variations

2.1 Introducing the Python Interpreter

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

Python installation details vary by platform. In short:

• 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.

• The Programmer’s View


In its simplest form, a Python program is just a text file containing Python statements. For
example, the following file, named script0.py, is one of the simplest Python scripts we could
dream up, but it passes for a fully functional Python program:

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.”

• Performance implications: Readers with a background in fully compiled languages such as


C and C++ might notice a few differences in the Python model. For one thing, there is usually
no build or “make” step in Python work: code runs immediately after it is written. For another,
Python byte code is not binary machine code (e.g., instructions for an Intel or ARM chip).
Byte code is a Python-specific representation.

• Development implications: Another ramification of Python’s execution model is that there is


really no distinction between the development and execution environments. That is, the
systems that compile and execute your source code are really one and the same. This
similarity may have a bit more significance to readers with a background in traditional
compiled languages, but in Python, the compiler is always present at runtime and is part of
the system that runs programs. This makes for a much more rapid development cycle. There
is no need to precompile and link before execution may begin; simply type and run the
code. This also adds a much more dynamic flavour to the language—it is possible, and
often very convenient, for Python programs to construct and execute other Python
programs at runtime. The level and exec built-ins, for instance, accept and run strings
containing Python program code. This structure is also why Python lends itself to product
customization—because Python code can be changed on the fly, users can modify the
Python parts of a system onsite without needing to have or compile the entire system’s
code. At a more fundamental level, keep in mind that all we really have in Python is
runtime— there is no initial compile-time phase at all, and everything happens as the
program is running. This even includes operations such as the creation of functions and
Programming Language (Python) 16

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.

2.2 Execution Model Variations

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.

Python Implementation Alternatives

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.

• CPython: The standard


The original, and standard, implementation of Python is usually called CPython when you
want to contrast it with the other options (and just plain “Python” otherwise). This name
comes from the fact that it is coded in portable ANSI C language code. This is the Python
that you fetch from http://www.python.org, get with the ActivePython and Enthought
distributions, and have automatically on most Linux and Mac OS X machines. If you’ve
found a preinstalled version of Python on your machine, it’s probably CPython, unless your
company or organization is using Python in more specialized ways. Unless you want to script
Java or .NET applications with Python or find the benefits of Stackless or PyPy compelling,
you probably want to use the standard CPython system. Because it is the reference
implementation of the language, it tends to run the fastest, be the most complete, and be
more up-to-date and robust than the alternative systems.

• Jython: Python for Java


The Jython system (originally known as JPython) is an alternative implementation of the
Python language, targeted for integration with the Java programming language. Jython
consists of Java classes that compile Python source code to Java byte code and then route
the resulting byte code to the Java Virtual Machine (JVM). Programmers still code Python
statements in .py text files as usual; the Jython system essentially just replaces the rightmost
two bubbles. Jython’s goal is to allow Python code to script Java applications, much as
CPython allows Python to script C and C++ components. Its integration with Java is
remarkably seamless. Because Python code is translated to Java byte code, it looks and
feels like a true Java program at runtime. Jython scripts can serve as web applets and
servlets, build Java-based GUIs, and so on. Moreover, Jython includes integration support
that allows Python code to import and use Java classes as though they were coded in
Python, and Java code to run Python code as an embedded language. Because Jython is
slower and less robust than CPython, though, it is usually seen as a tool of interest primarily
to Java developers looking for a scripting language to serve as a frontend to Java code.

• IronPython: Python for .NET


A third implementation of Python, and newer than both CPython and Jython, IronPython is
designed to allow Python programs to integrate with applications coded to work with
Microsoft’s .NET Framework for Windows, as well as the Mono open source equivalent for
Linux. .NET and its C# programming language runtime system are designed to be a
language-neutral object communication layer, in the spirit of Microsoft’s earlier COM
model. IronPython allows Python programs to act as both client and server components,
Programming Language (Python) 18

gain accessibility both to and from other .NET languages, and leverage .NET technologies
such as the Silverlight framework from their Python code.

• Stackless: Python for concurrency


Still other schemes for running Python programs have more focused goals. For example, the
Stackless Python system is an enhanced version and reimplementation of the standard
CPython language oriented toward concurrency. Because it does not save state on the C
language call stack, Stackless Python can make Python easier to port to small stack
architectures, provides efficient multiprocessing options, and fosters novel programming
structures such as coroutines.

• PyPy: Python for speed


The PyPy system is another standard CPython reimplementation, focused on performance.
It provides a fast Python implementation with a JIT (just-in-time) compiler, provides tools for
a “sandbox” model that can run untrusted code in a secure environment, and by default
includes support for the prior section’s Stackless Python systems and its microthreads to
support massive concurrency. PyPy is the successor to the original Psyco JIT, described
ahead, and subsumes it with a complete Python implementation built for speed. It does this
as your program is running, not in a prerun compile step, and is able to created type-specific
machine code for the dynamic Python language by keeping track of the data types of the
objects your program processes. By replacing portions of your byte code this way, your
program runs faster and faster as it is executing. In addition, some Python programs may
also take up less memory under PyPy.
Programming Language (Python) 19

- Chapter 3 -

Getting Started with Python


Objectives:

• To learn about Python Installation


• To learn about Installation between Windows and Linux

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

3.2 How to Install Python on Windows

There are three installation methods on Windows:


• The Microsoft Store
• The full installer
• Windows Subsystem for Linux

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.

How to Check Your Python Version on Windows

To check if you already have Python on your Windows machine, first open a command-line
application, such as PowerShell.

You can also use cmd.exe or Windows Terminal.

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.

What Your Options Are

As mentioned earlier, there are three ways to install the official Python distribution on Windows:

• Microsoft Store package


The most straightforward installation method on Windows involves installing from the
Microsoft Store app. This is recommended for beginner Python users looking for an easy-to-
set-up interactive experience.

• 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.

• Windows Subsystem for Linux (WSL)


The WSL allows you to run a Linux environment directly in Windows. You can learn how to
enable the WSL by reading the Windows Subsystem for Linux Installation Guide for Windows
10.

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

How to Install From the Microsoft Store

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.

Step 1: Open the Python App Page in the Microsoft Store


Open the Microsoft Store app and search for Python. You’ll likely see multiple versions that you can
choose to install:

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

Step 2: Install the Python App


After you’ve selected the version to be installed, follow these steps to complete the installation:
i. Click Get.
ii. Wait for the application to download. When it’s finished downloading, the Get button will
be replaced with a button that says Install on my devices.
iii. Click Install on my devices and select the devices on which you’d like to complete the
installation.
iv. Click Install Now and then OK to start the installation.
v. If the installation was successful, then you’ll see the message “This product is installed” at
the top of the Microsoft Store page.

Congratulations! You now have access to Python, including pip and IDLE!

How to Install From the Full Installer

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.

You can install from the full installer in two steps.

Step 1: Download the Full Installer


Follow these steps to download the full installer:
i. Open a browser window and navigate to the Python.org Downloads page for Windows.
ii. Under the “Python Releases for Windows” heading, click the link for the Latest Python 3
Release - Python 3.x.x. As of this writing, the latest version was Python 3.8.4.
iii. Scroll to the bottom and select either Windows x86-64 executable installer for 64-bit or
Windows x86 executable installer for 32-bit.

When the installer is finished downloading, move on to the next step.


Programming Language (Python) 24

Step 2: Run the Installer


Once you’ve chosen and downloaded an installer, run it by double-clicking on the downloaded
file. A dialog box like the one below will appear:

There are four things to notice about this dialog box:


• The default install path is in the AppData/ directory of the current Windows user.
• The Customize installation button can be used to customize the installation location and
which additional features get installed, including pip and IDLE.
• The Install launcher for all users (recommended) checkbox is checked default. This means
every user on the machine will have access to the py.exe launcher. You can uncheck this
box to restrict Python to the current Windows user.
• The Add Python 3.8 to PATH checkbox is unchecked by default. There are several reasons
that you might not want Python on PATH, so make sure you understand the implications
before you check this box.

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

3.3 How to Install Python on Linux

There are two installation methods on Linux:

• Using your operating system’s package manager


• Building Python from source code

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.

How to Check Your Python Version on Linux

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.

How to Install on Ubuntu and Linux Mint

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.

Congratulations! You now have Python 3 set up on your machine!


Programming Language (Python) 28

- Chapter 4 -

Python Quickstart
Objectives:

• To understand Python command line


• To understand the CLI in Python

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:

Where "helloworld.py" is the name of your python file.

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:

The output should read:

Congratulations, you have written and executed your first Python program.
Programming Language (Python) 29

4.2 The Python Command Line

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.

Type the following on the Windows, Mac or Linux command line:

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:

Which will write "Hello, World!" in the command line:

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 -

Python - Basic Syntax


Objective:

• To understand the concept of syntax


• To understand the key component of Python identifiers

5.1 Introduction

The Python language has many similarities to Perl, C, and Java. However, there are some definite
differences between the languages.

5.2 First Python Program

Let us execute programs in different modes of programming.

Interactive Mode Programming


Invoking the interpreter without passing a script file as a parameter brings up the following
prompt −
Programming Language (Python) 31

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 –

Script Mode Programming

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 –

This produces the following result –


Programming Language (Python) 32

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 –

This produces the following result −

5.3 Python Identifiers

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.

Here are naming conventions for Python identifiers –


• Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
• Starting an identifier with a single leading underscore indicates that the identifier is
private.
• Starting an identifier with two leading underscores indicates a strongly private
identifier.
• If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Programming Language (Python) 33

5.4 Reserved Words

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

5.4 Lines and Indentation

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 −

However, the following block generates an error –

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

5.6 Multi-Line Statements

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.

This produces the following result –

You can type a comment on the same line after a statement or expression –

You can comment multiple lines as follows –

Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline
comment:
Programming Language (Python) 38

- Chapter 6 -

Python - Basic Operators


Objectives:

• To understand the concept of Operators


• To understand the differences between Python Operators

6.1 Overview of Operators

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.

Types of Operator - Python language supports the following types of operators.


• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Programming Language (Python) 39

6.2 Python Arithmetic Operators

Assume variable a hold 10 and variable b holds 20, then –


Programming Language (Python) 40

6.3 Python Comparison Operators

These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then –


Programming Language (Python) 41

6.4 Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then –


Programming Language (Python) 42

6.5 Python Logical 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 -

Python - Decision Making & Loops


Objectives:

• To understand the concept of Decision Making


• To understand the key component of Loops

7.1 Overview of Python - Decision Making

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

7.2 Single Statement Suites

If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.

Here is an example of a one-line if clause –

When the above code is executed, it produces the following result –


Programming Language (Python) 46

7.3 Loops

In general, statements are executed sequentially: The first statement in a function is


executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more
complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.


The following diagram illustrates a loop statement –

Python programming language provides following types of loops to handle looping


requirements.
Programming Language (Python) 47

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.

Let us go through the loop control statements briefly –


Programming Language (Python) 48

- Chapter 8 -

Python TUPLE - Pack, Unpack, Compare, Slicing, Delete, Key


Objectives:

• To understand the concept of Tuple


• To understand the key component of Python Assignments

8.1 Overview of Python - Tuple

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

8.2 Tuple Assignment

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

Here is the code,

• Tuple 1 includes list of information of Robert


• Tuple 2 includes list of numbers in it
• We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4
• Run the code- It gives name Robert for first tuple while for second tuple it gives
number (2,3 and 4)
Programming Language (Python) 50

8.3 Packing and Unpacking

In packing, we place value into a new tuple while in unpacking we extract those values
back into variables.

8.4 Comparing Tuples

A comparison operator in Python can work with tuples.

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

Let's study this with an example-


Programming Language (Python) 51

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

8.5 Using Tuples as Keys in Dictionaries

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.

Example: We would come across a composite key if we need to create a telephone


directory that maps, first-name, last-name, pairs of telephone numbers, etc. Assuming that
we have declared the variables as last and first number, we could write a dictionary
assignment statement as shown below:

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.

Tuples and dictionary


Dictionary can return the list of tuples by calling items, where each tuple is a key value
pair.
Programming Language (Python) 53

- Chapter 9 -

Python Tutorials

9.1 Tutorial: Creating a Guessing Game in Python

Today we are going to make an interactive guessing game in Python.

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.

This is how the game looks in action,


Programming Language (Python) 54

In this tutorial, we will guide you through each step of making this interactive guessing
game in Python.

1. Now, open your favourite text editor and start coding.

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.

8. Now let’s design the while loop.

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:

Now let’s run our game!

15. To run the game, type this in your terminal python game.py and hit Enter.

You might also like