Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

Programing

Prof. K. Adisesha
BE, MSc, M.Tech, NET, (Ph.D.)
Python!
• Python is an interpreted, object-oriented, high-level
programming language.
• As it is general-purpose, it has a wide range of applications
 Web development,
 Building desktop GUI
 Scientific and Mathematical computing.
• Created in 1991 by Guido van Rossum
 Named for Monty Python
• Used by:
 Google, Yahoo!, Youtube
 Many Linux distributions
 Games and apps (e.g. Eve Online)
2
Languages
• Some influential ones:
 FORTRAN
• science / engineering

 COBOL
• business data

 LISP
• logic and AI

 BASIC
• a simple language

3
Python
• Interpreted
 You run the program straight from the source code.
 Python program Bytecode a platforms native language
 You can just copy over your code to another system and it will auto-
magically work! with python platform
• Object-Oriented
 Simple and additionally supports procedural programming
• Extensible – easily import other code
• Embeddable –easily place your code in non-python programs
• Extensive libraries
 (i.e. reg. expressions, doc generation, CGI, ftp, web browsers, ZIP,
WAV, cryptography, etc...) (wxPython, Twisted, Python Imaging library)

4
Python Timeline/History
• Python was conceived in the late 1980s.
 Guido van Rossum, born in Netherlands, was a
 big fan of Monty python’s Flying Circus named after.

• In 1991 python 0.9.0 was first published.


• In January of 1994 python 1.0 was released
 Functional programming tools like lambda, map, filter, and
reduce
 comp.lang.python formed, greatly increasing python’s
userbase
• In 1995, python 1.2 was released.

5
python Timeline/History
• By version 1.4 python had several new features
 Keyword arguments (similar to those of common lisp)
 Built-in support for complex numbers
 Basic form of data-hiding through name mangling
(easily bypassed however)
• Computer Programming for Everybody (CP4E) initiative
 Make programming accessible to more people, with basic
“literacy” similar to those required for English and math skills for
some jobs.
 Project was funded by DARPA
 CP4E was inactive as of 2007, not so much a concern to get
employees programming “literate”

6
python Timeline/History
• In 2000, Python 2.0 was released.
 Introduced list comprehensions similar to Haskells
 Introduced garbage collection
• In 2001, Python 2.2 was released.
 Included unification of types and classes into one
hierarchy, making pythons object model purely
Object-oriented
 Generators were added(function-like iterator
behavior)
• Standards
 http://www.python.org/dev/peps/pep-0008/

7
Installing Python
Windows: Mac OS X:
• Download Python from • Python is already installed.
http://www.python.org • Open a terminal and run python
• Install Python. or run Idle from Finder.
• Run Idle from the Start Menu.
Linux:
• Chances are you already have
Python installed. To check, run
python from the terminal.
• If not, install from your
distribution's package system.
Note: For step by step installation
instructions, see the course web site.

8
Programming basics
• code or source code: The sequence of instructions in a
program.

• syntax: The set of legal structures and commands that can


be used in a particular programming language.

• output: The messages printed to the user by a program.

• console: The text box onto which output is printed.


 Some source code editors pop up the console as an external
window, and others contain their own console window.

9
Interpreted Languages
• interpreted
 Not compiled like Java
 Code is written and then directly executed by an interpreter
 Type commands into interpreter and see immediate results

Java: Runtime
Code Compiler Computer
Environment

Python: Code Interpreter Computer

10
Compiling and interpreting
• Many languages require you to compile (translate) your
program into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class

• Python is instead directly interpreted into machine


instructions. interpret
source code output
Hello.py

11
The Python Interpreter
• Allows you to type commands one-at-a-time and see results
• A great way to explore Python's syntax
 Repeat previous command: Alt+P

12
Token

Smallest individual unit in a program is known as token.

• 1.Keywords

• 2.Identifiers

• 3.Literals

• 4.Operators

• 5.Punctuators / Delimiters

13
Keywords
• Reserve word of the compiler/interpreter which
can’t be used as identifier.

14
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 special characters
• Identifier must not be a keyword of Python.
• Python is a case sensitive programming language.
• Thus, Rollnumber and rollnumber are two different identifiers in
Python.
• Some valid identifiers :Mybook, file123, z2td, date_2, _no
• Some invalid identifier : 2rno,break,my.book,data-cs

15
Literals
• Literals in Python can be defined as number, text, or
other data that represent values to be stored in
variables.
• Example of String Literals in Python
• name = ‘Johni’ , fname=“johny”
• Example of Integer Literals in Python(numeric literal)
• age = 22
• Example of Float Literals in Python(numeric literal)
• height = 6.2
• Example of Special Literals in Python
• name = None

16
Operators
• Operators can be defined as symbols that are used to
perform operations on operands.

• Types of Operators
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

17
Arithmetic Operators
• Arithmetic Operators are used to perform arithmetic
operations like addition, multiplication, division etc.

18
Relational Operators
• Relational Operators are used to compare the values.

19
Assignment Operators
• Used to assign values to the variables.

20
Logical Operators
• Logical Operators are used to perform logical
operations on the given two variables or values.

Example:
a=30
b=20
if(a==30andb==20):
print('hello')
Output :-
hello
21
Membership Operators
• The membership operators in Python are used to
validate whether a value is found within a sequence
such as such as strings, lists, or tuples.

• Example:
a = 22
list = [22,99,27,31]
Ans1= a in list Ans2= a not in list
print(Ans1) print(Ans2)
• Output :-
True False

22
Identity Operators
• Identity operators in Python compare the memory
locations of two objects.

• Example:
a = 34
b=34
if (a is b):
print('both a and b has same identity')
else:
print('a and b has different identity')
• Output :-
both a and b has same identity 23
Punctuators / Delimiters
• Used to implement the grammatical and structure of a
Syntax.
• Following are the python punctuators.

24
Our First Python Program
• Python does not have a main method like Java
 The program's main code is just written directly in the file
• Python statements do not end with semicolons

hello.py
1 print("Hello, world!")

25
Python program
• A python program contain the following components

1. Comments
2. Function
3. Expression
4. Statement
5. Block & indentation

26
Python Comment
• Comments: which is readable for programmer but ignored
by python interpreter
a) Single line comment: Which begins with # sign.
• Syntax:
# comment text (one line)
 Example
# This is a comment
b) Multi line comment (docstring): either write multiple line
beginning with # sign or use triple quoted multiple line. E.g.
 Example
‘’’this is my
first
python multiline comment ‘’’
27
Math commands
• Python has useful commands for performing calculations.
To use many of these commands, you must write the following at the top
of your Python program: from math import *

28
Expressions
• expression: A data value or set of operations to compute a
value.
Examples: 1 + 4 * 3
42
• Arithmetic operators we will use:
 + - * / addition, subtraction/negation, multiplication, division
 % modulus, a.k.a. remainder
 ** exponentiation
• precedence: Order in which operations are computed.
 * / % ** have a higher precedence than + -
1 + 3 * 4 is 13

 Parentheses can be used to force a certain order of evaluation.


(1 + 3) * 4 is 16
29
Integer division
• When we divide integers with / , the quotient is also an
integer.
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
 More examples:
• 35 / 5 is 7
• 84 / 10 is 8
• 156 / 100 is 1
• The % operator computes the remainder from a division of
integers.
3 43
4 ) 14 5 ) 218
12 20
2 18
15 30
3
Real numbers
• Python can also manipulate real numbers.
 Examples: 6.022 -15.9997 42.0 2.143e17

• The operators + - * / % ** ( ) all work for real numbers.


 The / produces an exact answer: 15.0 / 2.0 is 7.5
 The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -
• When integers and reals are mixed, the result is a real
number.
 Example: 1 / 2.0 is 0.5
 The conversion occurs on a per-operator basis.
 7 / 3 * 1.2 + 3 / 2
 2 * 1.2 + 3 / 2
 2.4 + 3 / 2
 2.4 + 1
 3.4 31
Type conversion

• The process of converting the value of one data type


(integer, string, float, etc.) to another data type is called
type conversion.
• Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion

32
Type conversion
• Implicit Type Conversion:
• InImplicittypeconversion,Pythonautomaticallyconvertsonedatatypetoanot
herdatatype.Thisprocessdoesn'tneedanyuserinvolvement.
• Example:
num_int=12
num_flo=10.23
num_new=num_int+num_flo
print("datatypeofnum_int:",type(num_int))
print("datatypeofnum_flo:",type(num_flo))
print("Valueofnum_new:",num_new)
print("datatypeofnum_new:",type(num_new))
• OUTPUT
('datatypeof num_int:', <type 'int'>)
('datatypeof num_flo:', <type 'float'>)
('Value of num_new:', 22.23)
('datatypeof num_new:', <type 'float'>)
33
Type conversion
• Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an
object to required data type. We use the predefined functions
like int(),float(),str() etc.
Example: print("Data type of the
num_int= 12 sum:",type(num_sum))
num_str= "45" OUTPUT
print("Data type of ('Data type of num_int:', <type
num_int:",type(num_int)) 'int'>)
print("Data type of num_strbefore ('Data type of num_strbefore Type
Type Casting:",type(num_str)) Casting:', <type 'str'>)
num_str= int(num_str) ('Data type of num_strafter Type
print("Data type of num_strafter Casting:', <type 'int'>)
Type Casting:",type(num_str)) ('Sum of num_intand num_str:', 57)
num_sum= num_int+ num_str ('Data type of the sum:', <type
print("Sum of num_intand 'int'>)
num_str:",num_sum) 34
Variables
• variable: A named piece of memory that can store a value.
 Usage:
• Compute an expression's result,
• store that result into a variable,
• and use that variable later in the program.

• assignment statement: Stores a value into a variable.


 Syntax:
name = value
 Examples: x = 5 gpa = 3.14

 A variable that has been given a value can be used in


expressions.
x + 4 is 9

35
Statement
• A statement in Python: is a logical instruction
which Python interpreter can read and execute.
• In Python, it could be an:
 Assignment statement
 Multi-line statement

36
Assignment Statement
• Assignment statement
 The assignment statement is fundamental to Python.
 It defines the way an expression creates objects and preserve
them.
 a simple assignment, we create new variables, assign and
change values.
 Syntax:
• variable = expression
 Example
• Var=10

37
Multi-line statement
• Multi-line statement
• Python statement ends with a newline character.
However, we can extend it over to multiple lines
using the line continuation character (\).
• Python gives us two ways to enable multi-line
statements in a program.
• Explicit line continuation
• Implicit line continuation

38
Multi-line statement
• Explicit line continuation
 When you right away use the line continuation character (\)
to split a statement into multiple lines.
 Example:
a=1+2+3+\
4+5+6+\
7+8+9

39
Multi-line statement
• Implicit line continuation
 Implicit line continuation is when you split a statement
using either of parentheses ( ), brackets [ ] and braces { }.
• Example:
colors = ['red',
'blue',
'green']

40
Input Statement
• input : Reads a number from user input.
 You can assign (store) the result of input into a variable.
 Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years until
retirement"

Output:
How old are you? 53
Your age is 53
You have 12 years until retirement

41
print Statement
• print : Produces text output on the console.
• Syntax:
print ("Message“)
print (Expression)
 Prints the given text message or expression value on the console, and moves the
cursor down to the next line.
print (Item1, Item2, ..., ItemN)
 Prints several messages and/or expressions on the same line.

• Examples:
print ("Hello, world!“)
age = 45
print ("You have", 65 - age, "years until retirement“)
Output:
Hello, world!
You have 20 years until retirement
42
The print Statement
print("text")
print() (a blank line)
 Escape sequences such as \" are the same as in Java
 Strings can also start/end with '

swallows.py
1 print("Hello, world!")
2 print()
3 print("Suppose two swallows \"carry\" it together.")
4 print('African or "European" swallows?')

43
Python Indentation
• Python uses indentation to indicate blocks, instead of {}
 Makes the code simpler and more readable
 In Java, indenting is optional. In Python, you must indent.
 A code block which represents the body of a function or a loop
begins with the indentation.
 Typically, we indent each line by four spaces (or by the same
amount) in a block of code.
hello3.py
1 # Prints a helpful message.
2 def hello():
3 print("Hello, world!")
4 print("How are you?")
5
6 # main (calls hello twice)
7 hello()
8 hello()
44
Data Types
Prof. K. Adisesha
Data Types
• Data Type specifies which type of value a variable can
store. type() function is used to determine a variable 's type
in Python.
• Various data types supported by Python programs are:

46
Data Types
Data Types In Python
• Booleans
• Numbers
• Strings
• Bytes
• Lists
• Tuples
• Sets
• Dictionaries

47
Data Types
Python Data objects are broadly categorized into
• Immutable Type: Those that can never change values
in place
 Number
 String
 Boolean
 Tuple
• Mutable Types: Those whose values can be changed in
place.
 List
 Set
 Dictionary

48
Booleans
A Boolean is such a data type that almost every
programming language.
Boolean In Python
• Boolean in Python can have two values –
 True or False.
• Example
str="compsc"
b=str.isupper() #test if string contain uppercase
print(b)
• Output
False

49
Numbers
• The numbers in Python are classified using the following
keywords.
 Int,
 Float
 Complex.
• Python has a built-in function type() to determine the data
type of a variable or the value.
• Another built-in function isinstance() is there for testing
the type of an object.
• In Python, we can add a “j” or “J” after a number to make
it imaginary or complex.

50
Numbers
Number In Python
• It is used to store numeric values
• Python has three numeric types:
1. Integers
 Example: a = 10
 The number ( a ) is of type <class 'int'>
2. Floating point numbers
 Example: b = -101.4
 The number ( b ) is of type <class 'float'>
3. Complex numbers
 Example: c=complex(101,23)
 Output :- (101+23j)
 The number (c) is of type <class 'complex'> 51
Strings
String In Python
• A sequence of one or more characters enclosed within either
single quotes (‘ ')or double quotes (“ ”) is considered as
String.
• Example:
>>>str1='computer science'
>>>str #print string
• Python also supports multi-line strings which require a triple
quotation mark at the start and one at the end.
• Example
>>> str2 = """A multiline string
starts and ends with
a triple quotation mark."""
>>> str2 52
Bytes
Byte in Python
• The byte is an immutable type in Python.
• It can store a sequence of bytes (each 8-bits) ranging
from 0 to 255.
• Similar to an array, we can fetch the value of a single byte
by using the index. But we can not modify the value.

Differences between a byte and the string.


• Byte objects contain a sequence of bytes whereas the
strings store sequence of characters.
• The bytes are machine-readable objects whereas the
strings are just in human-readable form.

53
Lists
List in Python
• It is a heterogeneous collection of items of varied data
types.
• Lists in Python can be declared by placing elements inside
square brackets separated by commas.
• It is very flexible and does not have a fixed size. Index in a
list begins with zero in Python.
• List objects are mutable.
• Example:
 List1 = ['Learn', 'Python', '2']

54
Tuples
Tuples in Python
• A tuple is a heterogeneous collection of Python objects
separated by commas.
• Define a tuple using enclosing parentheses () having its
elements separated by commas inside.
• Tuples objects are immutable.
• Example:
 Tup1 = ('Learn', 'Python', '2‘)

55
Tuple & List
Difference between Tuple & List
• The tuple and a list are some what similar as they share
the following traits.
 Both objects are an ordered sequence.
 They enable indexing and repetition.
 Nesting is allowed.
 They can store values of different types.
Example of List: Example of tuple
list=[6,9] tup=(66,99)
list[0]=55 Tup[0]=3 # error message will be displayed
print(list[0]) print(tup[0])
print(list[1]) print(tup[1])
OUTPUT OUTPUT
55, 9 66, 9

56
Need for Tuple
Why need a Tuple as one of the Python data types?
• Here are a couple of thoughts in support of tuples.
• Python uses tuples to return multiple values from a
function.
• Tuples are more lightweight than lists.
• It works as a single container to stuff multiple things.
• We can use them as a key in a dictionary.

57
Sets
Set In Python
• Amongst all the Python data types, the set is one which supports
mathematical operations like union, intersection, symmetric
difference etc.
• A set is an unordered collection of unique and immutable objects.
• Its definition starts with enclosing braces { } having its items
separated by commas inside.
• To create a set, call the built-in set() function with a sequence or
any inerrable object.
• Example:
set1={11,22,33,22}
print(set1)
• Output
{33, 11, 22}
58
Dictionaries
Dictionary In Python
• A dictionary in Python is an unordered collection of key-
value pairs.
• It’s a built-in mapping type in Python where keys map to
values.
• Python syntax for creating dictionaries use braces {} where
each item appears as a pair of keys and values.
• Example:
dict= {'Subject': 'comp sc', 'class': '11'}
print(dict)
Output
{'Subject': 'comp sc', 'class': '11'}

59
Repetition (loops)
and Selection (if/else)
Prof. K. Adisesha
if Statement
• if statement: Executes a group of statements only if a
certain condition is true. Otherwise, the statements are
skipped.
 Syntax:
if condition:
statements

• Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is accepted."

61
if/else
• if/else statement: Executes one block of statements if a certain condition is
True, and a second block of statements if it is False.
 Syntax:
if condition:
statements
else:
statements

• Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to University!"
else:
print "Your application is denied."

• Multiple conditions can be chained with elif ("else if"):


if condition:
statements
elif condition:
statements
else:
statements 62
Short Hand If ... Else
If you have only one statement to execute, one for if, and
one for else, you can put it all on the same line:
• Example: One line if else statement:
a=2
b = 330
print("A") if a > b else print("B")
Output: B
We have multiple else statements on the same line:
• Example: One line if else statement, with 3 conditions:
a = 330
b = 330
Print("A") if a > b else print(“equ") if a == b else print("B")
Output: equ
63
while
• while loop: Executes a group of statements as long as a condition is True.
 good for indefinite loops (repeat an unknown number of
times)

• Syntax:
while condition:
statements
• Example:
number = 1
while number < 200:
print number,
number = number * 2
 Output:
1 2 4 8 16 32 64 128 64
The for loop
• for loop: A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
• Repeats a set of statements over a group of values.
 Syntax:
for variableName in groupOfValues:
statements
• We indent the statements to be repeated with tabs or spaces.
• variableName gives a name to each value, so you can refer to it in the statements.
• groupOfValues can be a range of integers, specified with the range function.

 Example:
for x in range(1, 6):
print x, "squared is", x * x
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
65
range
• The range function specifies a range of integers:
• range(start, stop) - the integers between start (inclusive)
and stop (exclusive)

 It can also accept a third value specifying the change between


values.
• range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step

 Example:
for x in range(5, 0, -1):
print(x)
print "Blastoff!"
Output:
5
4
3
2
1
Blastoff! 66
Cumulative loops
• Some loops incrementally compute a value that is initialized
outside the loop. This is sometimes called a cumulative
sum.
sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print "sum of first 10 squares is", sum

Output:
sum of first 10 squares is 385

67
The break Statement
• With the break statement we can stop the loop before it has
looped through all the items
Example: Exit loop when x is “banana” Example: Do not print banana

fruits = ["apple", "banana", "cherry"] fruits = ["apple", "banana", "cherry"]


for x in fruits: for x in fruits:
print(x) if x == "banana":
if x == "banana": break
break print(x)

Output:
Output: apple
apple
banana

68
continue Statement
• With the continue statement we can stop the current
iteration of the loop, and continue with the next
Example: Do not print banana

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

Output:
apple
cherry

69
Operators
• Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True

• Logical expressions can be combined with logical operators:


Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False

70
Thank you

Prof. K. Adisesha

You might also like