You are on page 1of 122

Programming Languages

Category
• System Languages

• Architectural Languages

• Application Languages
Category
• System Languages
used to build operating systems, hardware drivers
etc. Fast and gives you low level (close to the
core) access to the computer. These languages
are used when speed is critical.
• These languages include:
• C
• C++
• Assembler
Category

• Architectural Languages
used to build frameworks that support (make
easy) application building. Not as fast (at run-
time) as system level languages, but they provide
a higher level of abstraction that makes writing
software quicker and more productive.
• These languages include:
Java
C#
.Net
Category

• Application Languages
• used to build the actual business applications like
web shopping carts/stores, connecting to
databases and creating the screens for users to
interact with the database.
• These languages include:
PHP
Ruby
Perl
Python
Introduction
Python is a general-purpose, high-level,
remarkably powerful dynamic programming
language that is used in a wide variety of
application domains. Python supports
multiple programming paradigms, including
object-oriented, imperative and functional
programming styles.
History
• History of the Python programming
language dates back to the late 1980s.
• Python was conceived in the late 1980s[1] and its
implementation was started in December
1989[2] by Guido van Rossum at CWI in the
Netherlands as a successor to the ABC
programming language
• Van Rossum is Python's principal author, and his
continuing central role in deciding the direction
of Python is reflected in the title given to him by
the Python community, Benevolent Dictator for
Life (BDFL).
Feature
• Easy to read and learn
• Free and Open Source
• Useful for scientific computing
• Powerful interactive interpreter
• Extensive scientific libraries
• Well documented
open source software

• Open source software is software with source code


that anyone can inspect, modify, and enhance.
• "Source code" is the part of software that most
computer users don't ever see; it's the code computer
programmers can manipulate to change how a piece of
software—a "program" or "application"—works.
• Programmers who have access to a computer
program's source code can improve that program by
adding features to it or fixing parts that don't always
work correctly.
Applications
• Numeric and Symbolic computation
• 2D/3D Plotting
• Useful for scientific computing
• User interfaces
• Parallel computing
• Machine learning & Image Processing
• Game development
• Web Development
• And Much More
Advantages

• Extensive Libraries
• Rapid Application Development
• Interface to C/C++ and Fortran languages
• Cross Platform
Versions of Python
• Python 2.1 - April 17, 2001.
• Python 2.2 - December 21, 2001.
• Python 2.3 - July 29, 2003.
• Python 2.4 - November 30, 2004.
• Python 2.5 - September 19, 2006.
• Python 2.6 - October 1, 2008.
• Python 2.7 - July 3, 2010.
• Latest 2.7.13 and 3.6.0
How to download
• www.Python.org

• It’s a python software foundation of USA


IDLE : Integrated Development
Environment
Using Python Shell
• Save your program with .py files

• And run as python filename.py on command


prompt
Variables
• Variables are nothing but reserved memory
locations to store values. This means that when
you create a variable you reserve some space in
memory.
• Based on the data type of a variable, the
interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore,
by assigning different data types to variables, you
can store integers, decimals or characters in these
variables.
Assigning Values to Variables

• Python variables do not need explicit


declaration to reserve memory space. The
declaration happens automatically when you
assign a value to a variable. The equal sign (=)
is used to assign values to variables.
• The operand to the left of the = operator is
the name of the variable and the operand to
the right of the = operator is the value stored
in the variable.
Variables
• No need to declare
• Need to assign (initialize)
• use of uninitialized variable raises exception
• Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
• Everything is a "variable":
• Even functions, classes, modules
Standard Data Types

Python has five standard data types −


• Numbers
• String
• List
• Tuple
• Dictionary
Numerical types
Python supports four different numerical types :

• int (signed integers)


• long (long integers, they can also be
represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
Examples
int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBD 32.3+e18 .876j


AECBFBAEl
-0490 535633629843L -90. -.6545+0J

-0x260 - -32.54e100 3e+26J


052318172735L

0x69 - 70.2-E12 4.53e-7j


4721885298529
L
Boolean (bool)

• The simplest build-in type in Python is the bool


type, it represents the truth values False and
True. See the following statements in Python
shell.
Numerical Data
• Python allows you to use a lowercase l with
long, but it is recommended that you use only
an uppercase L to avoid confusion with the
number 1. Python displays long integers with
an uppercase L.
• A complex number consists of an ordered pair
of real floating-point numbers denoted by x +
yj, where x and y are the real numbers and j is
the imaginary unit.
String
• Strings in Python are identified as a contiguous set of
characters represented in the quotation marks. Python
allows for either pairs of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
• The plus (+) sign is the string concatenation operator and
the asterisk (*) is the repetition operator. For example −

• str = 'Hello World!'

• print str # Prints complete string


Special characters in strings
String indices and accessing string
elements

To cut a substring from a string is called string slicing. Here two indices are used
separated by a colon (:). A slice 3:7 means indices characters of 3rd, 4th, 5th
and 6th positions. The second integer index i.e. 7 is not included.
Strings are immutable
in' operator in Strings
• The 'in' operator is used to check whether a
character or a substring is present in a string or
not. The expression returns a Boolean value.
Lists

• Lists are the most versatile of Python's compound data


types. A list contains items separated by commas and
enclosed within square brackets ([]). To some extent, lists
are similar to arrays in C. One difference between them is
that all the items belonging to a list can be of different data
type.
• The values stored in a list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator. For example −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


Tuples
• A tuple is another sequence data type that is similar to
the list. A tuple consists of a number of values
separated by commas. Unlike lists, however, tuples are
enclosed within parentheses.
• The main differences between lists and tuples are: Lists
are enclosed in brackets ( [ ] ) and their elements and
size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated. Tuples can
be thought of as read-only lists. For example −

• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


• tinytuple = (123, 'john')
Dictionary

• Python's dictionaries are kind of hash table type. They


work like associative arrays or hashes found in Perl and
consist of key-value pairs. A dictionary key can be
almost any Python type, but are usually numbers or
strings. Values, on the other hand, can be any arbitrary
Python object.
• Dictionaries are enclosed by curly braces ({ }) and
values can be assigned and accessed using square
braces ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
Data Type Conversion
Function Description
• int(x [,base])
Converts x to an integer. base specifies the base if x is a string.
• long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
• float(x)
Converts x to a floating-point number.
• complex(real [,imag])
Creates a complex number.
• str(x)
Converts object x to a string representation.
• repr(x)
Converts object x to an expression string.
Data Type Conversion
• tuple(s) Converts s to a tuple.

• list(s) Converts s to a list.

• chr(x) Converts an integer to a character.

• ord(x) Converts a single character to its integer value.

• hex(x) Converts an integer to a hexadecimal string.

• oct(x) Converts an integer to an octal string.


Use of inbuilt function
Import math

math.sqrt(2)
math.factorial(2)
math.exp(3)  ex
math.pow(2,3)
math.sin(90) returns of 90 radians
Input
• A=input(“Enter the value of a: “)

• It will read string


• a=int(A)
will convert into integer
Python Output Using print() function
• The print() function is used to output data to the standard output
device (screen).

• print (a)

• print (‘my name is : ‘ , s)

• print(a,b,c)
Comments
• # is used for commenting

• Like as >>> # Addition of two numbers

… a=2;b=3;c=a+b; print (c )
Arithmetic operators
• + (addition)
• - (subtraction)
• * (Multiplication)
• / (Division)
• % (Remainder)
• ** (power)
• // (Division without fraction)
Relational/Comparison Operators
==

!=

>

<

>=

<=
Logical Operators
• and
x > 0 and x < 10
is true only if x is greater than 0 and less than 10.
• or
n%2 == 0 or n%3 == 0 is true if either of the conditions is
true, that is, if the number is divisible by 2 or 3.

• Not
not (x > y) is true if x > y is false, that is, if x is less than
or equal to y.
Python Bitwise Operators
• Bitwise operator works on bits and performs bit
by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
• -----------------
• a&b = 0000 1100
• a|b = 0011 1101
• a^b = 0011 0001
• ~a = 1100 0011
Difference between == and is
operator in Python
• The == operator compares the values of both the operands and
checks for value equality. Whereas is operator checks whether
both the operands refer to the same object or not.
Control and Conditional Statements
Control Structures
if else elif

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.
Syntax and example

if condition: if a>b:
statements print(“a is greater”)
elif condition: elif a>c:
statements] ... print(“a is greater “)
else: else:
statements printf(“b or c is greater “)
Nested if
• Logical operators often provide a way to simplify
nested conditional statements. For example, we
can rewrite the following code using a single
conditional:
• if 0 < x:
if x < 10:
print 'x is a positive single-digit number.'
The print statement is executed only if we make it past both
conditionals, so we can get the same effect with
the and operator:
if 0 < x and x < 10:
print 'x is a positive single-digit number.'
Multiple If statements
if score >= 90:
letter = 'A'
elif score >= 80:
letter = 'B'
elif score >= 70:
letter = 'C'
elif score >= 60:
letter = 'D'
else: letter = 'F‘
print(letter)
Compound statements
credits = float(input('How many units of credit
do you have? '))
GPA = float(input('What is your GPA? '))
if credits >= 192 and GPA >=4.5:
print('You are eligible to graduate!')
else:
print('You are not eligible to graduate.')
With logical or
a=22
b=30
c=17
If a>b or a>c:
print(a)
else:
print(b)
Control Structures

• for var in sequence:


statements

• while condition:
statements

• break
• continue
For statement
• The for statement in Python differs a bit from
what you may be used to in C or Pascal.
Rather than always iterating over an
arithmetic progression of numbers (like in
Pascal), or giving the user the ability to define
both the iteration step and halting condition
(as C), Python’s 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 (no pun intended):
Python for loop and range() function
Control Statement

for i in range(0,19):
if i%3 == 0:
print (i)
if i%5 == 0:
print ("Bingo!“)
print ("---“)
Control Statement

for i in range(0,19,2):

print (i)
Control Statement

for i in range(10,0,-1):

print (i)
Some Strange Examples
• print (range(10)

• range(0,15)
String related for

names = [‘san', ‘man', ‘hello']


for w in names:
print(w, len(w))

Will print ... san 3 man 3 hello 5


While Loop
• A while loop statement in
Python programming
language repeatedly
executes a target
statement as long as a
given condition is true.
Examples
sum = 0
while (sum < 10):
print ('The sum is:', sum )
sum = sum + 1
print (“finish“)
Infinite loop

sum = 0
while (sum < 10):
print ('The sum is:', sum)

Print(“finish“)
While else
while condition:
statement_1 ...
statement_n
else:
statement_1 ...
statement_n
While else
s=0
while (s < 10):
print ('The number is:', s)
s=s+1
else: print(‘s is more than 10’)
print (“finish“)
Break and continue
• The break statement in Python terminates the
current loop and resumes execution at the
next statement, just like the traditional break
found in C.

Syntax :

break
Break and continue
• The continue statement in Python returns the control to
the beginning of the while loop. The continue statement
rejects all the remaining statements in the current iteration
of the loop and moves the control back to the top of the
loop.
• The continue statement can be used in
both while and for loops.

Syntax :

continue
Random Numbers
• To generate a pseudo-random number between 0 and 1:
import random
print(random.random())
Output : 0.40977913687523215
• To generate random integer number in Python, randint() function is used.
This function is defined in random module.
import random
print(random.randint(0,9))
Output : 5
This will generate a random integer number between 0 and 9.
• To generate a random floating point number between 1 and 10 you can use
the uniform() function.
import random
print(random.uniform(1, 10))
Output : 2.2033121325247382
Immutable Objects or Variables in
Python
• In Python, immutable objects are those whose
value cannot be changed in place after
assignment or initialization. They allocate new
memory whenever their value is changed.
Examples of immutable data types or objects or
variables in Python are numbers
(integers, floats), strings and tuples.
Lists
• Set of Homogenous data elements

• Can be one dimensional or Multidimensional

• a=[2,3,4]

• Print a[2]
Array with Indexing
• a=[2,3,4]

• Print a[0:2]
Means print 2 values which start from 0 index

it will print 2 3

You might also like