You are on page 1of 59

Python

Data Types and Variables


• Numbers (No need to define data type)
>>> x=2
>>> y=3.2
>>> z=‘Hi’
>>> z="Hello"
>>> print (type(x) )
<type `int`>
Data Types and Variables
• Numbers (No need to define data type)
>>> x=2 (Integer)
>>> y=3.2 (real no)
>>> z=‘Hi’ (String)
>>> z="Hello"
(String)
>>> print (type(x) )
<type `int`>
Data Types and Variables
• Numbers (No need to define data type)
>>> x=2 (Integer) >>> y= 2+5j
>>> y=3.2 (real no) >>> print y 
>>> z=‘Hi’ (String) y= 2+5j
>>> z="Hello" >>> print y.real
(String) 2.0
>>> print (type(x) ) >>> print y.imag
<type `int`> 5.0
>>> x, y, z = 2, 10.2,
"Hi" >>> print
•  Arithmetic

+ - * / addition, subtraction/negation, multiplication,


division
% modulus, a.k.a. remainder
** exponentiation
>>> a=b+c
>>> a=b**4  means
• precedence:
* / % ** have a higher precedence than + -
• Strings
>>> print "Hello"
>>> x="Hi"
>>> y= "bye"
>>> msg = x+" "+y
>>> print msg
Hi bye
>>> s=100
>>> print "The string %s has %d integer" %
(s,len(s))
>>> x=10
>>> y=2.3
>>> z= "bye"
>>> print x+y
12.3
>>> print x+z  Error
>>> print (str(x)+z)  10bye
Slicing
Python starts indexing at 0. A string s will have indexes running
from 0 to len(s)-1 (where len(s) is the length of s) in integer
quantities.
0 1 2 3 4 5
s[i]  fetches the ith element in s
>>> s = 'string‘
s t r i n g
-6 -5 -4 -3 -2 -1
>>> print s[1]
>>> ‘t’
s[i:j]  fetches elements i (inclusive) through j (not inclusive)
>>> s[1:4]
'tri'
s[ :j]  fetches all elements up to, but not including j
>>> s[ :3]
'str'
s[i: ]  fetches all elements from i onward (inclusive)
>>> s[2:]
'ring‘
Slicing
s[i:j:k]  extracts every kth element starting with index i
(inlcusive) and ending with index j (not inclusive)
>>> s[0:5:2]
0 1 2 3 4 5
'srn'
s t r i n g
-6 -5 -4 -3 -2 -1

Python also supports negative indexes. For example, s[-1]


means extract the first element of s from the end (same as
s[len(s)-1])

>>> print s[-1]


'g'

>>> print s[-2]


'n
String Functions
• len(string) - number of characters in a string
• str.lower(string) - lowercase version of a string
• str.upper(string) - uppercase version of a string
• str.isalpha(string) - True if the string has only
alpha chars
• Many others: split, replace, find, format, etc.
Other Built-in Types
• tuples, lists, sets, and dictionaries
• They all allow you to group more than
one item of data together under one
name
• You can also search them

Beginning Python 11
Lists
• List is a compound data type used to group
together other values. List items need not all have
the same datatype.
• Lists are created by using square brackets.
Ex:
>>> L1 = [0,1,2,3],
>>> L2 = ['zero', 'one']
>>> L1 = [0,1,2,3]
>>> breakfast = [ "coffee", "tea", "toast", "egg" ]
• You can add or delete items from a list:
breakfast.append(“waffles”)
breakfast.remove(“coffee”)
Beginning Python 12
Types and Operators: Operations on Lists (1)
Some basic operations on lists:
Indexing: L1[i], L2[i][j]
Slicing: L3[i:j]
Concatenation:
>>> L1 = [0,1,2]; L2 = [3,4,5]
>>> L1+L2
[0,1,2,3,4,5]
Repetition:
>>> L1*3
[0,1,2,0,1,2,0,1,2]
Appending: 
>>> L1.append(3)
[0,1,2,3]
Sorting: 
>>> L3 = [2,1,4,3]
>>> L3.sort()
[1,2,3,4]
Types and Operators: Operations on Lists (2)
More list operations:
Reversal:
>>> L4 = [4,3,2,1]
>>> L4.reverse()
>>> L4
[1,2,3,4]
Index and slice assignment:
>>> L1 = [0,1,2]
>>> L2 = [3,4,5]
>>> L1[1]  1
>>> L2[0:2]  [3,4]
Tuples
• A Tuple is a sequence of data type similar to List. A tuple consist of a
number of values separated by commas and enclosed witin parenthesis.
• Unlike list, the elements of a tuple can’t be changed, so it is a read only
list.
Ex:
>>> L1 = (0,1,2,3])
>>> L2 = ('zero', 'one‘)
>>> L1 = [0,1,2,3]
>>> print L1
0,1,2,3
>>> print (L1[1])
1
>>> tuple1 = ("This", "is", "a", "tuple")
Print(tuple1[1])
is

Beginning Python 15
Types and Operators: Tuples
Basic properties:
Concatenation: 
>>> t1 = (0,1,2,3); t2 = (4,5,6)
>>> t1+t2
(0,1,2,3,4,5,6)
Repetition:
>>> t1*2
(0,1,2,3,0,1,2,3)
Length: len(t1) (this also works for lists and strings)
Dictionaries
• It is a mapping data type or a kind of hash table
that maps keys to values.
• Keys in a Dictionary can be of any data type.
• Keys in a Dictionary can be of any data type.
• Dictionaries are created using braces
Ex.
>>>sales = {‘apple’:100, ’orange’:[120,90]}
>>>print (sales.items())  It print all the items in the dictionary
>>>print (sales.keys())  It print all the keys in the dictionary
>>>print (sales.values())  It print all the values in the dictionary
>>>print (sales[‘apple’])  It print the price of apple

17
Dynamic Input
• Input() : Reads a number from user input.
• You can assign the return value by 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
Conditional Statements
If (Cond): If (Cond):
statement1 statement1
statement2
statement2
else:
statement1
statement2
Conditional Statements
If (Cond): while (Cond):
statement1 statement1
statement2 statement2
elif (cond):
statement1
statement2
else: for var_name in
group_of_values:
statement1 <statements>
statement2
if Condition
If (Cond): Example:
statement1 x = 5

statement2 if x > 4:
print("x is greater than
4")
print("Bye")

• The colon is required for if. print("This is not in if


scope")
• Note that all statement
indented one level in from Output:
x is greater than 4
the if are within it scope:
Bye
This is not in if scope

Beginning Python 21
if Condition
If (Cond): Example:
statement1 x = 3

statement2 if x > 4:
print("x is greater than
4")
print("Bye")

• The colon is required for if. print("This is not in if


scope")
• Note that all statement
indented one level in from Output:
the if are within it scope:
This is not in if scope

Beginning Python 22
if/else Condition
If (Cond):
statement1
statement2
else:
statement1
statement2

• Note the colon following the else


• This works exactly the way you would expect

Beginning Python 23
if/else Condition
• Example: WAP to check whether a number is
even or odd.
x = 3
if (x%2==0):
print("Number is even")
else:
print ("Number is odd")

Output:
Number is odd

Beginning Python 24
if/else Condition
• Example: WAP to check whether a number is
even or odd.
x = input("Enter a number:")
if (x%2==0):
print("Number is even")
else:
print ("Number is odd")

Output:
Enter a number: 12
Number is even

Beginning Python 25
for Loop
for var_name in group_of_values:
<statements>

• Var_name gives a name to each value, so you


can refer to it in the statements.

• Group_of_values can be a range of integers,


specified with the range function.

Beginning Python 27
Range Function
• The range function specifies a range of
integers:

range(start, stop)
Integers range is in between start (inclusive) and
stop (exclusive)

range(start, stop, step)


Integers range is in between start (inclusive) and
stop (exclusive) by step

Beginning Python 28
Use of Range Function in for loop
Example: Example:
for(i = 1 ; i <5; i+ for i in range
+) (1,5):
{ print i
printf("%d\n",i);
}

Output: Output:
1
1
2
2
3
3
4
4

Beginning Python 29
Use of Range Function in for loop
Example: Example:
for(i = 1 ; i <10; for i in range
i=i+2) (1,10,2):
{ print i
printf("%d\n",i);
}

Output: Output:
1 1
3 3
5 5
7 7
9 9
Beginning Python 30
for Loop
Example: Example:
for x in range (1,6): for x in range (1,6,2):
print x, "squared is", x * print x, "squared is", x*x
x

Output:
Output:
1 squared is 1
1 squared is 1 3 squared is 9
2 squared is 4 5 squared is 25
3 squared is 9
4 squared is 16
5 squared is 25

Beginning Python 31
for Loop
Example:
x= [1,2,3,4]
for i in x:
print i
Output:
1
2
3
4

Beginning Python 32
while Loop
Syntax:
Example:
while (Cond):
number = 1
statement1 while number < 5:
statement2 print number
number = number * 2

Output:
1
2
4

Beginning Python 33
While Loop
Example: Write a program o print first N
natural number

num = input("Enter a natural number: ")


i=1
while i<=num:
print i
i=i+1

Beginning Python 34
While Loop
Example: Write a program o print first N
natural number

num = input("Enter a natural number: ")


i=1
while i<=num: Output:
print i Enter a natural number: 5
i=i+1 1
2
3
4
5
Beginning Python 35
while for Loop
• len(x): Give the length of the
x = [1,20,'hi']
data structure
i=0
Ex: len(x), len(str)
while i < len(x):
print x[i]
i=i+1

Output:
1
20
hi

Beginning Python 36
Functions in Python
A function in python begins with keyword def followed by function
name and parenthesis.

 Defining a function

Without return type


def fun_name(arg1,arg2,…):  Defining the function
statement1
statement2

With return type


def fun_name(arg1,arg2,…):  Defining the function
statement1
statement2
return x  Returning the value
Functions in Python (Contd..)

Without return With return type


type
def add (a,b):
def add (x,y): c=a+b
z=x+y return c
print z
x=add(3,4)
add(3,4) print x

Output: 7
Output: 7
Functions in Python (Contd..)

Without return With return type


type
def add (a,b):
Function
def add (x,y): c=a+b body
Function
z=x+y body return c
print z
x=add(3,4)  Func
add(3,4)  Func Calling Calling
print x

Output: 7 Output: 7
Functions in Python (Contd..)

def example (mystring):


print (mystring + "Hi")

example("Hello") #Calling the function

Output: HelloHi
Functions in Python (Contd..)

def add(a,b):
return a+b

print(add(4,6)) #Calling the function


c=add(4,6) #Calling the function
Print c

Output:
10
10
Functions in Python (Contd..)
 Showing function return multiple vales
def greater(x,y):
if x>y:
return x,y
else:
return y,x

Val= greater(10,100)
Print val

Output: (100,10)
Modules in Python
• Modules refers to a file containing python
statements and definitions.
• If a python file (say demo.py) is called a
module then its module name would be
demo.
• We can define our most used function in
a module and import it instead of copying
their definitions into different programs.
Modules in Python
Syntax:
Creating Module: import module_name

import demo
def add (a,b):
return (a+b)

def display():
program.py
print "Bye"
demo.py
Modules in Python
Syntax:
Creating Module: import module_name

import demo
def add (a,b):
x=2
return (a+b) print x

def display():
program.py
print "Bye"
demo.py
Modules in Python
Syntax:
Creating Module: import module_name

import demo
def add (a,b):
x=2
return (a+b) print x
demo.display()
demo.add(3,4))
def display():
program.py
print "Bye"
demo.py
Modules in Python
Syntax:
Creating Module: import module_name as
newname
import demo as
prog
def add (a,b):
return (a+b)

def display():
program.py
print "Bye"
demo.py
Modules in Python
Syntax:
Creating Module: import module_name as
newname
import demo as
prog
def add (a,b):
return (a+b) x=2
print x
prog.display()
def display():
print(prog.add(3,
program.py
print "Bye" 4))
demo.py
Modules in Python
Syntax:
Creating Module: from module_name import
func_name
from demo import
display
def add (a,b):
return (a+b)

def display():
program.py
print "Bye"
demo.py
Modules in Python
Syntax:
Creating Module: from module_name import
func_name
from demo import
display
def add (a,b):
return (a+b) demo.display()

def display():
program.py
print "Bye"
demo.py
Modules in Python
Syntax:
Creating Module: from module_name import
func_name
from demo import
display
def add (a,b):
return (a+b) demo.display()
demo.add(3,4) ×
def display():
program.py
print "Bye"
demo.py
Package in Python
• Package consist of modules and sub
packages.

• Packages are organized in a directory which


contains a special file named __init__.py
which tells the python to treat directories as
packages.

• __init__.py can either be an empty file or


contain some initialization code for the
package.
Package in Python
module1.py import Package.module1
x() Packa
y() ge
module1.py

module2.p
y
module2.py
a() __init__.p
y
b()
__init__.py can either be an empty file or
contain some initialization code for the
package.
Program to check a number is
prime or not
def isprime(n)
if n==1: Output:
return False; Enter a number: 5
for I in range(2,n/2): Number is Prime
if (n%2)==0:
return False Enter a number: 4
return True Number is not Prime

num = input("Enter a number: ")


y=isprime(num)
if y==True:
print "Number is Prime"

else:
print "Number is not Prime"

Beginning Python 57

You might also like