Tuesday 31 December 2019

BCA TY Unit – I Getting started with python


Unit – I Getting started with python
Introduction to python, features, program output, program input and raw_input(),comments in
python, operators, Code blocks and indentation.

Unit – I Getting started with python

Introduction to python:
Python is an elegant and robust programming language that delivers both the power and general applicability of traditional compiled languages with the ease of use (and then some) of simpler scripting and interpreted languages. It allows you to get the job done, and then read what you wrote later.
Work on Python began in late 1989 by Guido van Rossum, then at CWI (Centrum voor Wiskunde en Informatica, the National Research Institute for Mathematics and Computer Science) in the Netherlands.It was eventually released for public distribution in early 1991.
Python is a high-level scripting language which can be used for a wide variety of text processing, system administration and internet-related tasks. Unlike many similar languages, its core language is very small and easy to master, while allowing the addition of modules to perform a virtually limitless variety of tasks. Python is a true object-oriented language, and is available on a wide variety of platforms. There’s even a python interpreter written entirely in Java, further enhancing python’s position as an excellent solution for internet-based problems.
Features:
Python is a dynamic, high level, free open source and interpreted programming language. It supports object-oriented programming as well as procedural oriented programming. In Python, we don’t need to declare the type of variable because it is a dynamic typed language.
There are a few features of python which are different than other programming languages.
High Level: Python is a high-level language.When we write programs in python, we do not need to remember the system architecture, nor do we need to manage the memory.
Object Oriented: Object-oriented programming (OOP) adds another dimension to structured and procedural languages where data and logic are discrete elements of programming. OOP allows for associating specific behaviors, characteristics, and/or capabilities with the data that they execute on or are representative of. Python is an object-oriented (OO) language, all the way down to its core. However, Python is not just an OO language like Java or Ruby. It is actually a pleasant mix of multiple programming paradigms. For instance, it even borrows a few things from functional languages like Lisp and Haskell.
Scalable: The term "scalable" is most often applied to measuring hardware throughput and usually refers to additional performance when new hardware is added to a system. Python provides basic building blocks on which you can build an application, and as those needs expand and grow, Python's pluggable and modular architecture allows your project to flourish as well as maintain manageability.
Extensible: Extensibility in a language provides engineers with the flexibility to add-on or customize their tools to be more productive, and to develop in a shorter period of time. Although this feature is selfevident in mainstream third-generation languages (3GLs) such as C, C++, and even Java, the ease of writing extensions to Python in C is a real strength of Python. Furthermore, tools like PyRex, which understands a mix of C and Python, make writing extensions even easier as they compile everything to C for you.
Python extensions can be written in C and C++ for the standard implementation of Python in C (also known as CPython). The Java language implementation of Python is called Jython, so extensions would be written using Java. Finally, there is IronPython, the C# implementation for the .NET or Mono platforms. You can extend IronPython in C# or Visual Basic.NET.
Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
Easy to Learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time. What may perhaps be new to beginners is the OO nature of Python. Those who are not fully versed in the ways of OOP may be apprehensive about jumping straight into Python, but OOP is neither necessary nor mandatory. Getting started is easy, and you can pick up OOP and use when you are ready to.
Easy to Read: Python code is more clearly defined and visible to the eyes.
Easy to Maintain: Python's source code is fairly easy-to-maintain. Much of Python's success is that source code is fairly easy to maintain, dependent, of course, on size and complexity.
Robust: When your Python crashes due to errors, the interpreter dumps out a "stack trace" full of useful information such as why your program crashed and where in the code (file name, line number, function call, etc.) the error took place. These errors are known as exceptions. Python even gives you the ability to monitor for errors and take an evasive course of action if such an error does occur during runtime.
These exception handlers can take steps such as defusing the problem, redirecting program flow, perform cleanup or maintenance measures, shutting down the application gracefully, or just ignoring it.
Python's robustness is beneficial for both the software designer and the user.
Large Standard Library: Python has a large standard library which provides rich set of module and functions so you do not have to write your own code for every single thing. There are many libraries present in python for such as regular expressions, unit-testing, web browsers etc.
Dynamically Typed Language: Python is dynamically-typed language. That means the type (for example- int, double, long etc) for a variable is decided at run time not in advance because of this feature we don’t need to specify the type of variable.
Interpreted and (Byte-) Compiled: Python is an Interpreted Language. because python code is executed line by line at a time. like other language c, c++, java etc there is no need to compile python code this makes it easier to debug our code.The source code of python is converted into an immediate form called bytecode.
Program output, program input and raw_input():
A Program needs to interact with the user to accomplish the desired task; this is done using Input-Output facility. Input means the data entered by the user of the program. In python, we have input() and raw_input ( ) function available for Input.
1) input()
Syntax:
input (expression)
If prompt is present, it is displayed on monitor, after which the user can provide data from keyboard. Input takes whatever is typed from the keyboard and evaluates it. As the input provided is evaluated, it expects valid python expression. If the input provided is not correct then either syntax error or exception is raised by python.
Example:
>>>x= input ("Enter data:")
Enter data:  34.78
>>>print(x)
34.78
2) raw_input()
Syntax:
raw_input (expression)
This input method fairly works in older versions (like 2.x).
If prompt is present, it is displayed on the monitor after which user can provide the data from keyboard. The function takes exactly what is typed from keyboard, convert it to string and then return it to the variable on LHS of '='.
Example: In interactive mode
>>>x=raw_input ('Enter your name: ')
Enter your name: ABC
x is a variable which will get the string (ABC), typed by user during the execution of program. Typing of data for the raw_input function is terminated by enter key.
We can use raw_input() to enter numeric data also. In that case we typecast, i.e., change the data type using function, the string data accepted from user to appropriate Numeric type.
Example:
>>>y=int(raw_input("Enter your roll no."))
Enter your roll no. 5
It will convert the accepted string i.e., 5 to integer before assigning it to 'y'.
Print statement
Syntax:
print (expression/constant/variable)
Print evaluates the expression before printing it on the monitor. Print statement outputs an entire (complete) line and then goes to next line for subsequent output (s). To print more than one item on a single line, comma (,) may be used.
Example:
>>> print ("Hello")
Hello
>>> print (5.5)
5.5
>>> print (4+6)
10
comments in python:
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will ignore them:

#This is a comment
print("Hello, World!")

Multi Line Comments: Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Operators:
The standard mathematical operators that you are familiar with work the same way in Python as in most other languages.
+ - * / // % **
Addition, subtraction, multiplication, division, and modulus (remainder) are all part of the standard set of operators. Python has two division operators, a single slash character for classic division and a doubleslash for "floor" division (rounds down to nearest whole number). Classic division means that if the operands are both integers, it will perform floor division, while for floating point numbers, it represents true division. If true division is enabled, then the division operator will always perform that operation, regardless of operand types.
There is also an exponentiation operator, the double star/asterisk ( ** ). Although we are emphasizing the mathematical nature of these operators, please note that some of these operators are overloaded for use with other data types as well, for example, strings and lists.
Example:
>>> print -2 * 4 + 3 ** 2
1
As you can see, the operator precedence is what you expect: + and - are at the bottom, followed by *, /, //, and %; then comes the unary + and -, and finally, we have ** at the top. ((3 ** 2) is calculated first, followed by (-2 * 4), then both results are summed together.)

Python also provides the standard comparison operators, which return a Boolean value indicating the truthfulness of the expression:

< <= > >= == != <>
Trying out some of the comparison operators we get:
>>> 2 < 4
True
>>> 2 == 4
False
>>> 2 > 4
False
>>> 6.2 <= 6
False
>>> 6.2 <= 6.2
True
>>> 6.2 <= 6.20001
True
Python currently supports two "not equal" comparison operators, != and <>.

Python also provides the expression conjunction operators:
and or not

We can use these operations to chain together arbitrary expressions and logically combine the Boolean results:
>>> 2 < 4 and 2 == 4
False
>>> 2 > 4 or 2 < 4
True
>>> not 6.2 <= 6
True
>>> 3 < 4 < 5
True
The last example is an expression that may be invalid in other languages, but in Python it is really a short way of saying:
>>> 3 < 4 and 4 < 5

Code blocks and indentation:
Code blocks are identified by indentation rather than using symbols like curly braces. Without extra symbols, programs are easier to read. Also, indentation clearly identifies which block of code a statement belongs to. Of course, code blocks can consist of single statements, too.
Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a statement. The statements with the same indentation belong to the same group called a suite or code block.
Consider the example of a correctly indented Python code statement mentioned below.
Example:
if a==1:
    print(a)
    if b==2:
        print(b)
print('end')
In the above code, the first and last line of the statement is related to the same suite because there is no indentation in front of them. So after executing first "if statement", the Python interpreter will go into the next statement, and if the condition is not true it will execute the last line of the statement.


Monday 23 December 2019

Unit I :Chapter 2 -Handling Html Form with Php


Syllabus
Chapter 2 Handling Html Form with Php
2.1 Capturing Form Data
2.2 Dealing with Multi-value filed
2.3 Generating File uploaded form
2.4 Redirecting a form after submission

HTML Form:
The HTML <form> element defines a form that is used to collect user input:
<form>
.
form elements.
.
</form>
An HTML form contains form elements.
Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and more.
The <input> Element:
The <input> element is the most important form element.
The <input> element can be displayed in several ways, depending on the type attribute.
Here are some examples:
Type
Description
<input type="text">
Defines a one-line text input field
<input type="radio">
Defines a radio button (for selecting one of many choices)
<input type="submit">
Defines a submit button (for submitting the form)
Example:
<html>
<body>
<form>
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname"><br>
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other <br>
  <input type="submit" value="Submit">
</form>
</body>
</html>

2.1 Capturing Form Data
First of all, the form's action attribute needs to contain the URL of the PHP script that will handle the form.

For example:

<form action="form_handler.php"method="post">
When users send their forms, their data is sent to the server and the form_handler.php script is run.

The script then needs to read the form data and act on it.
Superglobal Array
Description
$_GET
Contains a list of all the field names and values sent by a form using the get method
$_POST
Contains a list of all the field names and values sent by a form using the post method
$_REQUEST
Contains the values of both the $_GET and $_POST arrays combined, along with the values of the $_COOKIE superglobal array
Each of these three superglobal arrays contains the field names from the sent form as array keys, with the field values themselves as array values.

For example, suppose you created a form using the get method, and that form contained the following control:

<input type="text" name="emailAddress"value=""/ >
You could then access the value that the user entered into that form field using either the $_GET or the $_REQUEST superglobal:

$email = $_GET["emailAddress"];
$email = $_REQUEST["emailAddress"];
Example
In this example, you create a simple user registration form, then write a form handler script that reads the field values sent from the form and displays them in the page.

First, create the registration form.

Save the following HTML code as capformdata.html in your document root folder:
<html>
<body>
<form action="capformdata.php" method="get">
    <label for="firstName">First name</label>
    <input type="text" name="firstName" id="firstName" value="" />
    <label for="lastName">Last name</label>
    <input type="text" name="lastName" id="lastName" value="" />
    <label for="genderMale">male ?</label>
    <input type="radio" name="gender" id="genderMale" value="M" />
    <label for="genderFemale">female?</label>
    <input type="radio" name="gender" id="genderFemale" value="F" />
    <input type="submit" value="Submit" id="moveRight">
</form>
</body>
</html>
Next, save the following script as capformdata.php in your document root, the folder where you placed capformdata.html.
<html>
<body>
<?php
$first=$_GET["firstName"];
$last=$_GET["lastName"];
$sex=$_GET["gender"];
if($sex == "F")
   echo "$first $last is a female.<br />";
else
   echo "$first $last is a male.<br />";
?>
</body>
</html>
Fill in the fields in the form, then click the Submit button.

If all goes well, you should see a page displaying the data that you just entered.
the process of capturing and displaying the submitted form data is really quite simple.
Because the form is sent using the post method, the script extracts the form field values from the $_POST superglobal array, and displays each field value using echo.
2.2 Dealing with Multi-value filed
The following form fields are capable of sending multiple values to the server:
<html>
<body>
<form action="multiValue.php" method="post">
<h2> <label>Enter Your Name: </label></h2>
  <input type="text" name="Name" id="Name" /></br>
<h2>What whould like to eat?</h2>
<label>Apple</label>
<input type="checkbox" name="fruit[]" value="Apple" />
<label>Banana</label>
<input type="checkbox" name="fruit[]" value="Banana" />
<label>Jackfruit</label>
<input type="checkbox" name="fruit[]" value="Jackfruit" />
<label>Orange</label>
<input type="checkbox" name="fruit[]" value="orange" />
<label>Mango</label>
<input type="checkbox" name="fruit[]" value="Mango" />
<h2>What are your favorite soft drink?</h2>
<select name="favor[]" size = "4" multiple = "multiple">
  <option value="coke">Coke</option>
  <option value="sprite">Sprite</option>
  <option value="orange juice">Orange Juice</option>
  <option value="apple juice">Apple Juice</option>
  <option value="water">Water</option>
</select>
<p>Note that hold a <b>ctrl</b> key to choose more than one item.</p>
<input type="submit" name="submit" id="moveRight" value="Submit" />
<input type="reset" name="reset" value="Reset" style="margin-left: 20px;display:inline;" />
</form>
</body>
</html>
Php script to process multiple values:
<html>
<body>
<?php
$fruitlist=$_POST["fruit"]; //assign an array to a local array
$favorlist=$_POST["favor"];
$name=$_POST["Name"];
echo $name."  Your favorite drink from checkboxes are <br />";
foreach($fruitlist as $fruit)
     echo $fruit . "<br /> ";
echo "<br />";

echo $name."  Your favorite drink from pull-down menu are <br /> ";
foreach($favorlist as $favor)
     echo $favor. "<br />";
?>
</body>
</html>
2.3 Generating File uploaded form
move_uploaded_file()  : Moves an uploaded file to a new location.
syntax: 
move_uploaded_file ( string $filename , string $destination )

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.


formtoup.html

<form enctype="multipart/form-data" action="formtoup.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
</form>

formtoup.php

<?php
$target_path = "d:/uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
} else{
    echo "</br>There was an error uploading the file, please try again!";
}
?>

Uploading Files with PHP
In this tutorial we will learn how to upload files on remote server using a Simple HTML form and PHP. You can upload any kind of file like images, videos, ZIP files, Microsoft Office documents, PDFs, as well as executables files and a wide range of other file types.
Step 1: Creating an HTML form to upload the file
The following example will create a simple HTML form that can be used to upload files.
<html>
<head>
    <title>File Upload Form</title>
</head>
<body>
    <form action="upmanager.php" method="post" enctype="multipart/form-data">
        <h2>Upload File</h2>
        <label for="fileSelect">Filename:</label>
        <input type="file" name="photo" id="fileSelect">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
    </form>
</body>
</html>
Note: In addition to a file-select field the upload form must use the HTTP post method and must contain an enctype="multipart/form-data" attribute. This attribute ensures that the form data is encoded as mulitpart MIME data — which is required for uploading the large quantities of binary data such as image, audio, video, etc
Step 2: Processing the uploaded file
Here's the complete code of our "upload-manager.php" file. It will store the uploaded file in a "upload" folder on permanent basis as well as implement some basic security check like file type and file size to ensure that users upload the correct file type and within the allowed limit.
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
    
        // Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
    
        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["photo"]["tmp_name"], "d:/uploads/" . $filename);
                echo "Your file was uploaded successfully.";
            } 
        } else{
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else{
        echo "Error: " . $_FILES["photo"]["error"];
    }
}
?>
Note: The above script prevents uploading a file with the same name as an existing file in the same folder. However, if you want to allow this just prepend the file name with a random string or timestamp, like $filename = time() . '_' . $_FILES["photo"]["name"];
You might be wondering what this code was all about. Well, let's go through each part of this example code one by one for a better understanding of this process.
Explanation of Code
Once the form is submitted information about the uploaded file can be accessed via PHP superglobal array called $_FILES. For example, our upload form contains a file select field called photo (i.e. name="photo"), if any user uploaded a file using this field, we can obtains its details like the name, type, size, temporary name or any error occurred while attempting the upload via the $_FILES["photo"] associative array, like this:
$_FILES["photo"]["name"] — This array value specifies the original name of the file, including the file extension. It doesn't include the file path.
$_FILES["photo"]["type"] — This array value specifies the MIME type of the file.
$_FILES["photo"]["size"] — This array value specifies the file size, in bytes.
$_FILES["photo"]["tmp_name"] — This array value specifies the temporary name including full path that is assigned to the file once it has been uploaded to the server.
$_FILES["photo"]["error"] — This array value specifies error or status code associated with the file upload, e.g. it will be 0, if there is no error.
2.4 Redirecting a form after submission
URL redirection is often used within form handling code.
Normally when you run a PHP script — whether by typing its URL, following a link, or submitting a form — the script does its thing, displays some sort of response as a Web page, and exits.
However, by sending a special HTTP header back to the browser from the PHP script, you can cause the browser to jump to a new URL after the script has run.
This is commonly used within a form handler script to redirect the users to a thank - you page after they ’ ve submitted the form.
This means that you can keep your thank - you page separate from your PHP script, which makes the page easier to edit and update.
Another good thing about redirecting to a new URL after a form has been submitted is that it prevents users from accidentally resubmitting the form by clicking their browser ’ s Reload or Refresh button.

Redirection is as simple as outputting a Location: HTTP header, including the URL you want to
redirect to. You output HTTP headers in PHP using the built - in header() function. So here ’ s how to redirect to a page called thanks.html :
header( “Location: thanks.html” );
The only thing to watch out for is that you don’t output any content to the browser — whether via echo() or print() , or by including HTML markup outside the < ?php ... ?> tags — before calling
header() . This is because the moment you send content to the browser, the PHP engine automatically sends the default HTTP headers — which won’t include your Location: header — and you can send headers only once per request.
Here’s a quick example of a form handler script that redirects to a thank - you page:
<?php
if ( isset( $_POST["submitButton"] ) ) {
// (deal with the submitted fields here)
header( "Location: thanks.html" );
exit;
} else {
displayForm();
}
function displayForm() {
?>
<html>
<head>
<title>Membership Form</title>
</head>
<body>
<h1>Membership Form</h1>
<form action="redirect.php" method="post">
<div style="width: 30em;">
<label for="firstName">First name</label>
<input type="text" name="firstName" id="firstName" value="" /></br>
<label for="lastName">Last name</label>
<input type="text" name="lastName" id="lastName" value="" />
<div style="clear: both;">
<input type="submit" name="submitButton" id="submitButton" value=
"Send Details" />
</div>
</div>
</form>
</body>
</html>
<?php
}
?>

Notice that the script doesn’t output anything to the browser until either the header() function is called, or until the membership form is displayed. Also notice that the script terminates with the exit statement after calling header() to avoid sending any further output to the browser.