Python Sonal
Python Sonal
with Python
1
Which of these languages do you know?
• C or C++
• Java
• Perl
• Scala
• PHP
• Python
• Matlab
• Ruby
Python
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where
as other languages use punctuation, and it has fewer syntactical constructions than
other languages.
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
4
Brief History of Python
Invented in the Netherlands, early 90s by Guido van
Rossum
Named after Monty Python
Open sourced from the beginning
Considered a scripting language, but is much more
high-level, interpreted, interactive and object-oriented
scripting language.
Used by Google from the beginning
Increasingly popular
The Python tutorial is good!
The Basics
Python Overview
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.
Examples:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
13
print
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.
28
Expressions
expression: A data value or set of operations to
compute a value.
Examples: 10 + 4 * 3
22
1 + 3 * 4 is ??
29
Expressions
expression: A data value or set of operations to
compute a value.
Examples: 10 + 4 * 3
22
30
Expressions
expression: A data value or set of operations to compute a
value.
Examples: 10 + 4 * 3
22
31
Logic
Many logical expressions use relational operators:
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= OR <> 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
32
Standard Data Types
• Python has five standard data types −
• Numbers – int, long, float, complex
• String
• List
• Tuple
• Dictionary
• x[2]=‘a’
Error Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
a[1]='q'
TypeError: 'str' object does not support item
assignment
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
40
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = "P. Diddy"
>>> s = '012345'
index 0 1 2 3 4 5 6 7 >>> s[3]
character P . D i d d y '3'
>>> s[1:4]
Accessing an individual character of a string: '123'
variableName [ index ] >>> s[2:]
Example:
'2345'
print name, "starts with", name[0] >>> s[:4]
'0123'
Output:
P. Diddy starts with P
>>> s[-2]
'4'
41
• str = 'Hello World!'
• print str
• print str[0]
• print str[2:5]
• print str[2:]
• print str * 2
• print str + "TEST”
• Hello World!
• H
• llo
• llo World!
• Hello World!Hello World!
• Hello World!TEST
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length,
"characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
44
String Literals: Many Kinds
Can use single or double quotes, and three double
quotes for a multi-line string
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> s = """And me too!
though I am much longer
than the others :)"""
'And me too!\nthough I am much longer\nthan the others :)‘
>>> print s
And me too!
though I am much longer
than the others :)‘
Basic Datatypes
Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
Floats
x = 3.456
Strings
Can use “” or ‘’ to specify with “abc” == ‘abc’
Unmatched can occur within the string: “matt’s”
Use triple double-quotes for multi-line strings or
strings that contain both ‘ and “ inside of them:
“““a‘b“c”””
>>word = 'word'
>>word
Output=?
O/P
{'cherry': 'red', 'apple': 'green', 'banana':
'yellow'}
{'cherry': 'red', 'apple': 'red', 'banana': 'yellow'}
thisdict =
{"apple":"green","banana":"yellow","cherry
":"red"}
print(thisdict.keys())
print(thisdict.values())
O/P:
['cherry', 'apple', 'banana']
['red', 'green', 'yellow']
Data Type Summary
print "Hi %s! You are %d years old!" % (name, 2015 - birthyear)
~: python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 35 years old!
WAP to take two numbers as input
from user and perform all binary
operations.
• Addition
• Subtraction
• Multiplication
• Division
• Floor division
• exponentiation
No Braces
• Python uses indentation instead of braces to determine
the scope of expressions
• All lines must be indented the same amount to be part
of the scope (or indented more if part of an inner
scope)
• This forces the programmer to use proper indentation
since the indenting is part of the program!
Control Flow
Things that are False
• The boolean value False
• The numbers 0 (integer), 0.0 (float) and 0j (complex).
• The empty string "".
Things that are True
• The boolean value True
• All non-zero numbers.
• Any string containing at least one character.
• A non-empty data structure.
Control Flow: if
if statement: Executes a group of statements only if a
certain condition is true. Otherwise, the statements are
skipped.
Syntax:
if condition:
statements
69
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
12
HelloWorld
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 4.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
A Code Sample (in IDLE)
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 4.45 and y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
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
74
• Draw a flowchart to take student total marks
as input and print whether student is
pass(>50) or fail.
Marks = int(input(" enter your marks: "))
print Marks
if Marks > 50:
print "PASS"
else:
print "FAIL"
WAP in python to find max
between two numbers
number1 = int(input ("Enter number 1: "))
number2 = int(input ("Enter number 2: "))
if number1 > number2:
largest = number1
else:
largest = number2
print("Largest of entered two numbers is",
largest,"\n")
if/else
Multiple conditions can be chained with elif ("else if"):
if condition:
statements
elif condition:
statements
else:
statements
79
WAP in python to find max between three numbers.
num1 = int(input ("Enter number 1: "))
num2 = int(input ("Enter number 2: "))
num3 = int(input ("Enter number 2: "))
if (num1 >= num2):
if(num1>=num3):
largest=num1
else:
largest=num3
else:
if(num2>=num3):
largest=num2
else:
largest=num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
80
Range Test
Syntax:
while condition:
statements
86
While Loops
>>> execfile(‘whileloop.py’)
1
2
3
4
5
6
7
8
9
>>>
In interpreter
While Loops
>>> execfile(‘whileloop.py’)
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
whileloop.py
6
7
8
9
>>>
In interpreter
WAP to print this series
1 2 4 8 16 32 64
89
while
number = 1
while number < 65:
print number,
number = number * 2
Output:
1 2 4 8 16 32 64
90
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)
x=1
1 2 hello
while x < 3 :
print x,
x=x+1
else:
print 'hello'
The Loop Else Clause
• The optional else clause runs only if the loop exits
normally (not by break)
x=1
1
while x < 3 : 2
print x hello
x=x+1
else:
print 'hello'
The Loop Else Clause
x=1
while x < 5 :
print x
x=x+1
break
else :
print 'i got here'
whileelse2.py
The Loop Else Clause
x=1
while x < 5 :
print x
x=x+1
break 1
else :
print 'i got here'
whileelse2.py
WAP in python to check string is palindrome or not
string = "naman"
str=string[len(string)-1]
i=len(string)-2
while i>=0:
str=str+string[i]
i=i-1
print str
print string
if str==string:
print "success"
95
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
Example:
for x in (1,2,3,4,5):
print x, "squared is", x * x
96
The for loop
for loop: Repeats a set of statements over a group of values.
Syntax:
Example:
for x in (1,2,3,4,5):
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
97
Program to add n natural numbers
n = int(input("Enter n: "))
sum= 0
i=1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
Example to illustrate the use of else statement
with the while loop
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")
Example: Using For loop
Example:
for x in range(5, 0, -1):
print x
print "Blastoff!"
101
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!
102
WAP in python to find sum of squares of first 10
numbers.
103
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
while i<=n :
fact=fact*i
i=i+1
else:
print("Factorial of ", n, " is ", fact)
Practice Question
Write a python program that searches for prime numbers
from 10 through 20.
lower = 10
upper = 20
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Sum of digits of numbers
n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits
is:",tot)
109
Reverse a number
x = int(input("Please Enter a
number to reverse: "))
reverse = 0
while(x):
reverse = reverse * 10
reverse = reverse + x % 10
x = int(x/10)
print(reverse)
110
Reverse a string
str = input("Enter string ")
str1=""
for i in str:
str1 = i + str1
print (str1)
111
Palindrome
112
Sum of digits of a number
n=156
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
113
Fibonacci series
a=1
b=1
n=10
print(a)
print(b)
while(n-2):
c=a+b
a=b
b=c
print(c)
n=n-1
114
Armstrong number
num=int(input("enter number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp /= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
115
Loop Control
Break
Continue
pass
The break Statement:
for i in range(1,10):
if i == 3:
break
print i
The continue statement
The continue statement in Python returns the control
to the beginning of the while loop.
122
Modules
• When a Python program starts it only has
access to a basic functions and classes.
(“int”, “dict”, “len”, “sum”, “range”, ...)
• “Modules” contain additional functionality.
• Use “import” to tell Python to load a module.
>>> import math
>>> import nltk
• Use ”from module import *” to import
everything.
Pattern Printing
n=5 *
for i in range(1,n+1): **
for j in range(1,i+1): ***
print ('* ', end="") ****
print('') *****
Pattern Printing
n=5 1
for i in range(1,n+1): 12
for j in range(1,i+1): 123
print (j, end="") 1234
print('') 12345
print ('')
Pattern Printing
n=5 *****
for i in range(1,n+1): ****
for j in range(n,i-1,-1): ***
print ('* ', end="") **
print('') *
Pattern Printing
n=5 54321
for i in range(1,n+1): 5432
for j in range(n,i-1,-1): 543
print (j, end="") 54
print('') 5
Pattern Printing
n=5 1 2 3 4 5
num=1 6 7 8 9
for i in range(1,n+1): 10 11 12
for j in range(n,i-1,-1): 13 14
#print ('%3d' %(num),end="") 15
print ('{:3d}'.format(num),
end="")
num+=1
print('')
Pattern Printing
n=5 5
for i in range(1,n+1): 45
for j in range(1,n-i+1): 345
print (end=" ") 2345
for k in range(n-i+1,n+1): 12345
print (k, end="")
print('')
Pattern Printing
n=5 1
for i in range(1,n+1): 12
for j in range(1,n-i+1): 123
print (end=" ") 1234
for k in range(1,i+1): 12345
print (k, end="")
print('')
Pattern Printing
k=0 *
rows = 10 ***
for i in range(1, rows+1): *****
for space in range(1, (rows-i)+1): *******
print(end=" ") *********
while k != (2*i-1): ***********
print("* ", end="") *************
k=k+1 ***************
k=0 *****************
print() *******************