Introduction To Python Slides
Introduction To Python Slides
by …
Dr. Pradyumna Kumar Tripathy
Associate Professor & Head, Dept. of CSE,
Silicon Institute of Technology, Bhubaneswar
Disclaimer:
Few of the slides are prepared by collecting information from
various sources, particularly from Internet. Those information are
collected, compiled and presented here.
• Developed by Guido Van Rossum in Feb 1989 while working at Centrum Wiskunde
& Informatics (CWI). [released as Open Source in February 1991 ]
Why Python ? ? ?
The chart above shows how many of the top 39 departments teach either CS0 or CS1 using the seven most
common languages. The bar heights add up to more than 39 since many schools offer both CS0 and CS1.
• Interpreted Language
• Completeness (Batteries included)
– Emails, web-pages, databases, GUI, development, network
and many more…
• Cross-Platform Language (Portable)
• Free and Open Source
• Variety of Usage/ Applications
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
TechnoZeal
6/28/2020 6
Technology, Bhubaneswar
Limitations
• Not the fastest Language
• Lesser Libraries than C, Java, Perl
• Not Strong on Type-binding
( Declare int and later store a string-No worry)
• Not Easily Convertible
(Not Structured. So, Translating into another
programming language-difficult)
• Download from
– www.python.org/download ( select the python distribution )
>>>3 * 5
>>>print (3 * 5)
>>>print (“ hello”)
>>>3 ** 3
>>>6 + 2 * 4
>>>(6 + 2) * 4
>>>5 – 3 – 3
>>>k = 5 – (3 – 3)
>>>9 // 5
>>>a //= 3
>>>5 / 0
>>>a *= 2
>>> 9 % 5
>>>divmod(9,5) Dr. Pradyumna Kumar Tripathy, Silicon Institute of
TechnoZeal
6/28/2020 11
Technology, Bhubaneswar
Hands-on Contd…
>>>int(True)
>>>int(False)
>>>int(98.6)
>>>int(1.0e4)
>>>int(‘99’)
>>>int(‘-45’) GUESS THE OUTPUT
???
>>>int(‘+12’)
>>>True + 3
>>>False + 5.0
>>> googol=10 ** 100 (called googol)
>>>googol * googol
• Digits : 0-9
• Keywords
• Identifiers
• Literals
• Operators
• Punctuators
• Numeric
• Boolean
• Special ( None)
• Literal collection
>>>str3 = ‘ ‘ ‘ a 5
b
c‘‘‘
>>>str4 = ‘a\ 3
b\
c’ Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 20
TechnoZeal
Technology, Bhubaneswar
Hands-on Contd…
>>> ‘ ‘
>>>” “
>>>’ ‘ ‘ ‘ ‘ ‘
>>>” ” “ “ “ “
GUESS THE OUTPUT
>>> bottle = 99 ???
>>>base = ‘ ‘
>>>base += ‘current inventory:’
>>>base += str(bottles)
>>>base
>>>letters = ‘abcdefghijklmnopqrstuvwxyz’
>>>letters[0]
>>>letters[1]
>>>letters[-1]
>>>letters[-2]
>>>letters[100]
>>>name = ‘Henny’
>>>name[0] = ‘P’ ERROR
>>>name.replace(‘H’, ‘P’)
>>>’P’ + name[1:]
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 22
Technology, Bhubaneswar
TechnoZeal
Hands-on Contd…
[start: end: step]
>>>letters = ‘abcdefghijklmnopqrstuvwxyz’
>>>letters[:]
>>>letters[20:]
>>>letters[12:15]
>>>letters[-3:] GUESS THE OUTPUT
???
>>>letters[18:-3]
>>>letters[-6:-2]
>>>letters[::7]
>>>letters[4:20:3]
>>>letters[19::4]
>>>letters[:21:5]
>>>letters[-1::-1]
>>>letters[-51:-50]
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 23
Technology, Bhubaneswar
TechnoZeal
Hands-on Contd…
>>>t = ‘get gloves, get mask, give cat vitamins, call ambulance’
>>>t.split(‘,’)
>>>t.split( )
Special Literal
• None
>>> x = None
>>> y = None
>>> x == y True
• Arithmetic Operators + - * / % ** //
Punctuators
( Symbols used to organize sentence structure and indicate the rhythm and emphasis of expressions,
statements, and program structure)
‘“#\()[]{}@,:.`=;
TechnoZeal
#This program shows a program’s components
#Definition of seeyou( ) follows
def seeyou(): # Function Definition
print (‘Time to say good bye !!’)
#main program code follows now
a = 15
b = a – 10
GUESS THE OUTPUT
print (a+3) ???
if b > 5:
print (‘value of ‘a’ is more than 5’)
else:
print (‘value of ‘a’ is less than 5’)
seeyou( ) #Call of Function
Or
Age = int(Age)
num = -1
if num > 0:
GUESS THE OUTPUT
print(num, "is a positive number.")
???
print("This is also always printed.")
num = 3
if num >= 0:
print("Positive or Zero")
GUESS THE OUTPUT
else:
???
print("Negative number")
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 TechnoZeal 43
Technology, Bhubaneswar
if...elif...else Statement
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero") GUESS THE OUTPUT
else: ???
print("Negative number")
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 print(‘Thank you’) Technology,TechnoZeal
Bhubaneswar
44
Nested if else
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
GUESS THE OUTPUT
else: ???
print("Negative number")
Decisions n
o print('More than one’)
x = 42
if x > 1 : yes
print('More than one') x < 100
if x < 100 : n
print('Less than 100') o print('Less than 100')
print('All done')
print('All Done')
Visualize Blocks x=4
no yes
x = 4 x>2
if x > 2 :
print('Bigger') print('Not bigger') print('Bigger')
else :
print('Smaller')
print('All done')
print('All Done')
x = 20
Multi-way
yes
x<2 print('small')
x = 20
no
if x < 2 :
yes
print('small')
elif x < 10 :
x < 10 print('Medium')
print('Medium') no
else :
print('LARGE') print('LARGE')
print('All done')
print('All Done')
Multi-way if x < 2 :
print('Small')
elif x < 10 :
# No Else print('Medium')
x = 5 elif x < 20 :
if x < 2 : print('Big')
print('Small') elif x < 40 :
elif x < 10 : print('Large')
print('Medium') elif x < 100:
print('Huge')
print('All done') else :
print('Ginormous')
Sample Program
Problem: WAP to find largest among 3 numbers.
Solution:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
Ex-2
words = [ ’got ’ , ’me’ , ’ looking ’ , ’so ’ , ’crazy ’ , ’ right ’ , ’now’ ]
for w in words:
print (w)
Ex-4
# Program to find the sum of all numbers stored in a list
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum + val
GUESS THE OUTPUT
print("The sum is", sum) ??? ???
Ex. 1 :
count = 0
while count < 5:
GUESS THE OUTPUT
print(count) ???
count+=1
Ex. 2 :
n = 10
i=1
sum = 0
while i <= n: GUESS THE OUTPUT
sum = sum + i ???
i=i+1 # update counter
print("The sum is", sum)
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 61
Technology, Bhubaneswar
break and continue
• break is used to exit a for loop or a while loop
• continue is used to skip current block, and return to "for" or "while"
statement.
Ex-1
count = 0
while True:
print(count)
count += 1
if count >= 5: GUESS THE OUTPUT
break ???
Ex-2
for x in range(10): # Check if x is even
if x % 2 == 0:
continue
print(x)
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 62
Technology, Bhubaneswar
Ex :
for val in "string":
if val == "i":
continue
print(val)
print("The end")
GUESS THE OUTPUT
???
Ex :
for val in "string":
if val == "i":
break
print(val)
print("The end")
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True: > hello there
line = input('> ') hello there
if line == 'done' : > finished
break finished
print(line) > done
print('Done!') Done!
for loop with else
The else part is executed if the items in the sequence used in for
loop exhausts. break statement can be used to stop a for loop. In
such case, the else part is ignored. Hence, a for loop's else part
runs if no break occurs.
Ex :
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 70
Technology, Bhubaneswar
Sample Program
• Problem: Find a number is Prime or not?
Solution:
num = int(input("Enter a number: "))
count=0;
if num > 1:
for i in range(2,num):
if (num % i) == 0:
count = count+1;
if count == 0:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 71
Technology, Bhubaneswar
Sample Program
Problem: Reverse a word
Solution:
word = input("Input a word to reverse: ")
for char in range(len(word) - 1, -1, -1):
print(word[char], end="")
print(‘\n’)
Problem: Write a Python program that prints each item and its corresponding type from the
following list.
Sample List : datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A’}]
Solution:
datalist = [1452, 11.23, 1+2j, True, ‘Silicon', (0, -1), [5, 12], {"class":'V', "section":'A'}]
for item in datalist:
print ("Type of ",item, " is ", type(item))
Solution:
s = input("Input a string")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)
Dr. Pradyumna Kumar Tripathy, Silicon Institute of
6/28/2020 73
Technology, Bhubaneswar
Sample Program
Problem: To find numbers between 100 and 400 (both included) where each digit of a number is an
even number. The numbers obtained should be printed in a comma-separated sequence
Solution:
items = []
for i in range(100, 401):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0):
items.append(s)
print( ",".join(items))