PL Spring 2017: Python
PL Spring 2017: Python
PL Spring 2017: Python
Spring 2017
Python
A. PL Research: Python
1. History 4
2. Paradigm/Classification .. 5
3. Compilers 7
4. Applications.. 11
5. Program Structure..13
6. Data Types/Objects17
7. Sequence Control...20
8. Input/Output..22
9. Sup-program Control24
10. Encapsulation/Inheritance..26
11. Example of a Simple Program...27
1.URL.28
2.List of Question and Answers29
3.Program Structure (CGIapplet) Diagram30
4.List and Diagram of Programs32
5. Examples (print windows step by step)..33
2
3
A. PL Research: Python
1. History
Python was conceived in the late 1980s by Guido van Rossum who was conducting research
on programming languages at Centrum Wiskunde & Informatica in the Netherlands, a research
institution which concentrates on Mathematics and Computer science. Guido wanted to create a
new programming language during his free time in the weekends and he started his work on
python. He took inspiration from an existing programming language called ABC which was a
general purpose programming language which was used at CWI. Although it was not very
popular and CWI stopped further development of ABC. Python borrows features from ABC and
the syntax and semantics are influenced by MODULA 2+ and MODULA 3.
Following these principles python would rise to popularity, although not popular until the
mid 2000s since only a handful of people were using it. Python saw a major mainstream success
in the late 2000s since google started using it as an implementation language. Now python can be
seen everywhere since it is portable across all major hardware and software platforms and it also
has a lot of libraries and frameworks which makes it really easy to program with.
Versions:
How ever the default or the traditional implementation is CPython written in C. The first public
version of python was released on February 20, 1991 labeled as version 0.9.0
Version 1:
In 1994 python reached version 1.0 including a new set of features which included some
functional programming tools like reduce(), map(), filter() and patches.
4
From version 1.4 version 1.6 python got several updates inspired from MODULA-3s keyword
arguments and built-in support for complex numbers and fixed a lot of bugs from the previous
versions.
Version 2:
Version 2.0 introduced new features like list comprehension, which was inspired from
other programming languages like SETL and Haskell. The python syntax was also inspired from
Haskell and this version also introduced a garbage collection system.
During version 2.1- 2.2 python unified its types which are written in C and the classes which are
written and python into one hierarchy which made pythons object model into object oriented.
Version 2.7 was the last version 2 release and it had features very similar to version 3.0 and 3.1
Version 3:
Version 3.0 was released on December 2008 which was designed in a way to patch the
design flaws of the previous versions and improving backwards compatibility. Version 3 is still
getting updates to this date with the current release labeled Python 3.6.1, released on 21 March
2017.
2. Paradigm/Classification:
Python supports multiple paradigms. It can be Object-oriented, imperative, functional,
procedural and reflective.
Although python is classified into all these paradigms its much stronger in some paradigms than
the others. It is called a interpreted or a scripting language, in boarder sense it is an imperative
programming language rather than a declarative (functional) language. It is dynamically and
strongly typed.
Although its more object oriented the syntax allows procedural flow style. It is very flexible with
paradigms.
3. Compilers:
Python source code is automatically compiled into Python byte code by the CPython
interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the
source is updated, or when otherwise necessary.Lot of compilers are available for different kinds
of uses.
5
Example:
Nuitka
You feed it your Python app, it does a lot of clever things, and spits out an executable or
extension module.
License:
Free license (Apache).
Download from:
http://nuitka.net/pages/download.html
Pyjs
pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With
pyjs you can write your JavaScript-powered web applications entirely in Python.
License:
Free license (Apache).
Download from:
http://pyjs.org/Download.html
Most of the python compilers are free and is covered by the Python Software Foundation
License.
Even though python is used commercially there are no compilers that requires a paid license
Python is absolutely free, even for commercial use (including resale). You can sell a
product written in Python or a product that embeds the Python interpreter. No licensing
fees need to be paid for such usage.
The Open Source Initiative has certified the Python license as Open Source, and includes
it on their list of open source licenses.
However, the Python license is compatible with the GPL, according to the Free Software
Foundation.
6
You cannot remove the PSF's copyright notice from either the source code or the
resulting binary.
4. Applications:
Web and Internet Development:
Software Development:
Python is often used as a support language for software developers, for build control and
management, testing, and in many other ways.
SCons for build control.
Buildbot and Apache Gump for automated continuous compilation and testing.
Roundup or Trac for bug tracking and project management.
7
GUI Development:
Build a GUI application (desktop app) using Python modules Tkinter, PyQt to support it.
Rapid Prototyping:
Python has libraries for just about everything. Use it to quickly built a (lower-
performance, often less powerful) prototype. Python is also great for validating ideas or products
for established companies and start-ups alike.
Writing Scripts:
If you're doing something manually and want to automate repetitive stuff, such as emails,
it's not difficult to automate once you know the basics of this language.
Data Analysis:
Python is the leading language of choice for many data scientists. Python has grown in
popularity, within this field, due to its excellent libraries including; NumPy and Pandas and its
superb libraries for data visualisation like Matplotlib and Seaborn.
8
5. Program Structure:
9
Credits: This guide was created by David Faulkner, Dan Upton, and David Evans for CS150
Fall 2005. It was revised for CS 150 in Spring 2009 by Westley Weimer.
10
The program is structured with blocks and indentations are used to specify a block of code.
Variables are initialized first before they are used. Functions also use indentations to specify the
start and the end of a function block.
As long as they are indented properly the program can have as many parts the programmers
intend it to.
A familiar example:
We can see how login.cgi that we use later in the project is structured with importing modules
first, then variable initializations followed by blocks of codes and functions. Here we also
encounter multiple single line code used to print html.
6. Data types:
11
Numbers
String
List
Tuple
Dictionary
Boolean
Numbers:
Type Format Description
int a = 10 Signed Integer
long a = 345L (L) Long integers, they can also be represented in octal and hexadecimal
Any number you enter in Python will be interpreted as a number; you are not required to
declare what kind of data type you are entering. Python will consider any number written without
decimals as an integer (as in 138) and any number written with decimals as a float (as in 138.0).
Booleans:
The Boolean data type can be one of two values, either True or False
y=True
z=False
None: Often written null in other languages, it is usually used to represent 'nothing'.
It can be declared as
12
x = None
String:
Create string variables by enclosing characters in quotes. Python uses single quotes '
double quotes "and triple quotes """ to denote literal strings. Only the triple quoted strings """
also will automatically continue across the end of line statement.
How to declare:
firstName = 'john'
lastName = "smith"
message = """This is a string that will span across multiple lines. Using newline characters
and no spaces for the next lines. The end of lines within this string also count as a newline when
printed"""
List:
Lists are a very useful variable type in Python. A list can contain a series of values. List
variables are declared by using brackets [ ] following the variable name.
# w is an empty list
w=[]
# y is a list of numbers
y=[1,2,3,4,5]
# z is a list of strings
# and other lists
z=['first',[],'second',[1,2,3,4],'third']
Tuple:
Tuples are a group of values like a list and are manipulated in similar ways. But, tuples
are fixed in size once they are assigned. In Python the fixed size is considered immutable as
compared to a list that is dynamic and mutable. Tuples are defined by parenthesis ().
Example:
13
myGroup = ('Rhino', 'Grasshopper', 'Flamingo', 'Bongo')
Dictionaries:
A Python dictionary is a group of key-value pairs. The elements in a dictionary are indexed by
keys. Keys in a dictionary are required to be unique.
Example:
Objects are an encapsulation of variables and functions into a single entity. Objects get their
variables and functions from classes. Classes are essentially a template to create your objects.
source : https://www.learnpython.org/en/Classes_and_Objects
The variable "myobjectx" holds an object of the class "MyClass" that contains the variable and
the function defined within the class called "MyClass".
14
To access a function inside of an object you use notation similar to accessing a variable:
7. Sequence control:
Expressions:
An expression is an instruction that combines values and operators and always evaluates down
to a single value.
2+2
Assignments:
A Python statement is pretty much everything else that isn't an expression. Here's
an assignment statement:
15
spam = 2 + 2
Conditional statements:
if Statements:
Perhaps the most well-known statement type is the if statement. For example:
Output:
It is cold!
ifelse statement:
temp = 20
output:
It feels good!
for Statements:
The for statement in Python differs a bit from what you may be used to in C or Pascal.
16
Pythons for statement iterates over the items of any sequence (a list or a string), in the order that
they appear in the sequence. For example
for i in [0,1,2,3,4]:
print i
Output:
0
1
2
3
4
While loops:
A while loop repeats a sequence of statements until some condition becomes false. For example:
x=5
while x > 0:
print (x)
x=x1
Output:
5
4
3
2
1
Python includes statements to exit a loop (either a for loop or a while loop) prematurely. To exit a
loop, use the break statement:
x=5
while x > 0:
print x
break
x -= 1
print x
17
Output:
Continue statement:
The continue statement is used in a while or for loop to take the control to the top of the loop
without executing the rest statements inside the loop. Here is a simple example.
for x in range(6):
if (x == 3 or x==6):
continue
print(x)
Output:
0
1
2
4
5
8. Input/Output:
There will be situations where your program has to interact with the user. For example,
you would want to take input from the user and then print some results back. We can achieve
this using the input()function and print function respectively.
Example:
18
print(something)
Output:
In order to read and write a file, Python built-in function open() is used to open the file.
The open()function creates a file object.
Syntax:
Code:
file_input = open("simple_file.txt",'r')
all_read = file_input.read()
19
print all_read
file_input.close()
Output:
Hello
Hi
In this section we will discuss write a file with Python. This time we will use write mode "w"
in open()function.
We will use write() function.
text_file = open("writeit.txt",'w')
text_file.write("Hello")
text_file.write("\Hi")
text_file.close()
Output:
Hello
Hi
9.Sup-program Control:
Built-in Functions:
Functions like print(), input(), eval() etc. that we have been using, are some examples of the
built-in function. There are 68 built-in functions defined in Python 3.5.2. They are listed below
alphabetically along with a brief description.
Built-in Functions
20
Built-in Functions
Defining Functions
Example:
def functionname(arg1,arg2):
return arg1+arg2
t = functionname(24,24) # Result: 48
21
Output:
48
If a function takes no arguments, it must still include the parentheses, but without anything in
them:
def functionname():
statement1
statement2
...
Default Parameters
Having parameters is great, but it can be repetitive to continue to use them over and over, again.
We can define a default value for a parameter by setting its value when you define the parameter.
Take the script below for example.
def woof(x=0):
print(x)
woof(1)
woof()
woof(23)
1
0
23
Python allows you to declare two special arguments which allow you to create arbitrary-length
argument lists. This means that each time you call the function, you can specify any number of
arguments above a certain number.
def function(first,second,*remaining):
22
statement1
statement2
...
When calling the above function, you must provide value for each of the first two arguments.
However, since the third parameter is marked with an asterisk, any actual parameters after the
first two will be packed into a tuple and bound to "remaining."
def print_tail(first,*tail):
print tail
print_tail(1, 5, 2, "omega")
output:
5
2
omega
Python has the ability to return multiple values from a function call, something missing from
many other languages. In this case the return values should be a comma-separated list of values
and Python then constructs a tuple and returns this to the caller.
Example:
def square(x,y):
return x*x, y*y
t = square(2,3)
print t
Output:
4
9
23
10. Encapsulation/Inheritance:
Encapsulation
In an object oriented python program, you can restrict access to methods and variables.
This can prevent the data from being modified by accident and is known as encapsulation. Lets
start with an example.
If an identifier doesn't start with an underscore character "_" it can be accessed from
outside, i.e. the value can be read and changed. Data can be protected by making members
private or protected. Instance variable names starting with two underscore characters cannot be
accessed from outside of the class.
Public variables:
Example:
Output:
1
Private variables:
24
output :
error
The private variable __bar cannot be accessed by objects outside the class. So when you run the
program you will get an error:
Private Methods:
Methods can be made private in the same way, by naming them with two leading underscores
and no trailing underscores.
Output:
Error
We cannot access private methods that are declared private inside the object. So we get an error
when we try to execute the code.
Inheritance in Python:
Inheritance is used to inherit another class' members, including fields and methods. A sub class
extends a super class' members.
Syntax:
25
class SubClass(BaseClass):
def some_method(self, passed_params):
#calling base class version of method
BaseClass.some_method(self, passed_params)
Example:
class Cat(object):
def __init__(self, name):
self.name = "Garfield"
def sound(self):
return "Meow"
class Tiger(Cat):
def __init__(self, name): #will overwrite Cat constructor
self.name = "Mike Tyson Jr."
def cat_sound():
Cat.sound() #will call cat's sound
Code:
num1 = 1.5
num2 = 6.3
26
# Add two numbers
sum = num1 + num2
Output:
1.URL
http://cs.newpaltz.edu/~anbarasd1/simple3/
27
2.List of Question and Answers
Dialog -1 :
Possible Answers 1:
o NO! not at all
o YES! very much
o I guess..
Dialog 2:
(if answer-1 is NO! not at all)
Possible Answers 2:
Its hard!
I like javascript more!
I like more lines of code!
Possible answer 2:
Its so easy!
I like snakes!
so portable!
Possible answer 2:
not so interesting
Can't say why
28
Stop asking me so many questions!
29
3.Program Structure (CGIapplet) Diagram
30
4.List and Diagram of Programs
List of programs:
31
Diagram of programs:
Database MYSQL
<table UserPass>
UserName Password
abc 1234
aa bbb
32
33
34
35
36
37
Conclusion:
References:
https://www.programiz.com/
http://stackoverflow.com/
https://docs.python.org/
38