Unit_I_Python Programming Material
Unit_I_Python Programming Material
27-07-2024 3
Python Programming Department of CSE (AIML)
Python Features
➢Interpreted
➢Platform Independent, High Level
➢Object Oriented programming
Python comments:
Comments can be used to explain Python code.
Creating a comment: comments starts with a special character #
Example:
# range() function generates a sequence of numbers
Multi-line comments:
Enclose all lines in triple quote which you wanted to marked it as
comment line.
27-07-2024 4
Python Programming Department of CSE (AIML)
Python working modes
Python working modes are two:
1.Interactive mode:
▪ Working with python in interactive mode is nothing but working with
python shell.
▪ Python shell is a tool which comes with python software.
▪ Python shell is called command line interface
▪ Python shell also called REPL tool. REPL stands Read-Evaluate-Print-Loop
▪ Python shell is a command line interpreter. It reads command given at
prompt and interpret/evaluates and display result.
27-07-2024 5
Python Programming Department of CSE (AIML)
Python working modes
2. Programming mode :
• In python script is program which is saved with extension .py (source
program).
• How to write a program or create module:
1. Open IDLE (Integrated development environment)
2. File ➔New File ➔Type program ➔ Save program ➔File➔ Save
3. File name➔Click on Run ➔ Run Module
27-07-2024 6
Python Programming Department of CSE (AIML)
Builtin Key words in Python
• Python 3.12.2 version support 35 keywords
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
27-07-2024 7
Python Programming Department of CSE (AIML)
Identifiers
• Identifiers are user defined words. These words are used to identify
programming elements.
1. Package Name
2. Module Name
3. Function Name
4. Variable Name
27-07-2024 8
Python Programming Department of CSE (AIML)
Rules for creating identifiers
1. Identifier should not be keyword
2. Identifier can be defined in upper case or lowercase. Python is case
sensitive language and find difference between uppercase and
lowercase.
3. Identifier is only one word, there should not any space.
4. Identifier allows alphabets from (a-z,A-Z,0-9) and one special
character _
5. Identifier should start with alphabet or _
6. Maximum length of identifier is any length
Example: >>> amt$=100
SyntaxError: invalid syntax
27-07-2024 9
Python Programming Department of CSE (AIML)
Python Lines and Indentation
❑ Python programming provides no braces and semicolons to indicate block of code (code block).
❑ Block of code are denoted by line indentation (usually indentation is equal to four white spaces)
Example: Example python program using if-else conditional control statment
if True:
print("True") # if block
else:
print("False") # else block
#Example python program using if - elif- else conditional control statements
n = int(input())
if n%2 != 0:
print("Weird") # if block
elif n%2 == 0 and n >=2 and n <=5:
print("Not Weird") # elif block
elif n%2 == 0 and n >=6 and n <=20:
print("Weird") # elif block
else:
print("Not Weird") # else block
27-07-2024 10
Python Programming Department of CSE (AIML)
Python - Variables
▪ A variable is an identity given to value or memory location.
▪ Variable is named memory location.
▪ The value of variable can be changed.
▪ Python is dynamically typed language; there is no variable
declaration in python.
▪ How to create a variable in python?
▪ Variables are created in python by assigning a value.
• Example: name =‘Python’
• X=10
• X=20.5
• X=2+3j
27-07-2024 11
Python Programming Department of CSE (AIML)
Python – Control statements
➢Control statements are used to control flow of execution of program.
➢Default flow of execution of program is sequential.
Conditional control statements
• If
• If-else
• If-elif-else
• Nested-if
• match
Loop control statements
• for
• while
• Nested loops
Branching control statements
• Break
• Continue
• Pass
• Return
27-07-2024 12
Python Programming Department of CSE (AIML)
Branching control statements
Key note:
How to define empty blocks in python?
Empty blocks are defined in python by including one statement
“pass”
What is pass?
“pass” is a keyword, which is represent do-nothing or null operation
Example:
if 10>2:
pass
27-07-2024 13
Python Programming Department of CSE (AIML)
Python – while Loop Control statements
while loop required 3 statements
1. initialization statement
2. condition
3. update statement
Example:
c=1 # initialization statement
while c<=10: # condition/test
print(“SREE")
c=c+3 # update statement
Output:
SREE
SREE
SREE
SREE
27-07-2024 14
Python Programming Department of CSE (AIML)
Python – for Loop Control statements
for loop
• The for statement is used to iterate over the elements of a sequence (such as a string,
tuple or list) or other iterable object.
• For loop is used to read each time one value/element from collection/ sequence data
type
Syntax:
for variable in iterable/collection / sequence:
statement-1
statement-2
• for loop each time read value from collection and assign that value to variable. after
assigning it executes statement-1 and statement-2
• This repeating is done until read all values from collection.
Example:
str1="PYTHON"
for a in str1:
print(a)
27-07-2024 15
Python Programming Department of CSE (AIML)
Built-in data types in Python
▪ Data types are used to allocate / reserve memory for data.
▪ Python data types are classified into two categories
1. Standard data types
2.Collection data types / Data structures
▪ Standard data types are used to represent one value. ==> Scalar data types
▪ Collection data types are used to represent more than one value
Standard data types
1.Numeric data types (Numbers)
a. integers b. floating point real numbers c. complex numbers
2.Boolean data type
3.None type
27-07-2024 16
Python Programming Department of CSE (AIML)
Built-in data types in Python
❑Collection data types
a. set b. frozenset
a. dictionary
27-07-2024 17
Python Programming Department of CSE (AIML)
Python – classes & objects
• In python every data type is called a class.
• Python uses the object model abstraction for data storage. Any
construct that contains any type of value is an object.
• Python is an object oriented programming language.
What is class?
▪ In python class represents data type.
▪ This data type is used to allocate memory for data/object
>>> n2=20
>>> type(n2)
Output:
<class 'int’>
27-07-2024 18
Python Programming Department of CSE (AIML)
Python – classes & objects
▪ All python objects have the following three characteristics:
1.Identity: Unique identifier that differentiates an object from all others.
▪ Any object identifier can be obtained using a built-in function(BIF) called
id(). This function returns value is as close as you will get to a memory
address.
2.Type: An object’s type indicates what kind of values an object can hold.
▪ Type of an object can be obtained using a built-in function(BIF) called
type(). This function returns the class (data type) of object.
3.Value: Data item that is represented by an object.
▪ Example:
>>> x=10
>>> print(id(x))
140707907586776 # memory location of object ‘x’
>>> print(type(x))
<class 'int'>
27-07-2024 19
Python Programming Department of CSE (AIML)
Operators in Python
▪ Operator is a special symbol which is used to perform operations.
• Based on the operands on which it performs operations, operators are
classified into different categories
1. Unary Operators
2. Binary Operators
3. Ternary Operators
• Unary operator required one operand
• Binary operator required two operands
• Ternary operator required three operands
27-07-2024 20
Python Programming Department of CSE (AIML)
Operators in Python
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
• Conditional Operators
• Walrus operator (Python 3.8)
27-07-2024 21
Python Programming Department of CSE (AIML)
Arithmetic Operators in Python
Operator Description
+ Addition
Operator Description
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
!= Not equal
== Equal
27-07-2024 23
Python Programming Department of CSE (AIML)
Logical Operators in Python
• Logical operators are used to combine two boolean expressions.
• Logical operators in python are represented using three python
keywords
1. and
2. or
3. not
27-07-2024 24
Python Programming Department of CSE (AIML)
Conditional Operator in Python
▪ Conditional operator is ternary operator. This operator required three
operands.
▪ Conditional operator is used to create conditional expression.
▪ Conditional operator allows evaluating of expression based on
condition/Test.
Syntax:
• result=opr1 if opr2 else opr3
➢Opr1(operand 1) ==> expression/true-expression
➢opr2 ==> boolean expression/test/condition
➢opr3 ==> expression/false-expression
▪ if condition is True, PVM (Python virtual machine) evaluates opr1 and
assign to result
▪ if condition is False, PVM evaluates opr3 and assign to result
27-07-2024 25
Python Programming Department of CSE (AIML)
Ternary Operator in Python : Example
#write a program to find a person is eligible to vote or not
name=input("Enter Name")
age=int(input("Enter Age"))
print(result)
OUTPUT:
• Enter Age 45
• Sreenivasu
27-07-2024
Elgible
26
Python Programming Department of CSE (AIML)
Membership Operators
▪ Membership operator is used with collection data types.
▪ Membership operator is used to search a given value exists in group
values.
▪ If given value exists in group of values, it returns True
▪ If given value not exists in group values, it returns False
1. in
2. not in
• These two are binary operators.
➢opr1 in opr2
➢opr1 not in opr2
➢opr2 must be collection type.
27-07-2024 27
Python Programming Department of CSE (AIML)
Membership Operators : Example program
# Write a program to find input character is vowel
Output:
Vowel
27-07-2024 28
Python Programming Department of CSE (AIML)
Membership Operators : Example program
# Write a program to demonstrate membership operator ‘in’
students=['sreenivasu','aruna','snigdha','sreyanshi','sanvi']
for name in students:
print(name)
OUTPUT:
27-07-2024 30
Python Programming Department of CSE (AIML)
Identity Operators : Example program in interactive mode
>>> a=10
>>> b=20
>>> c=10
>>> d=20
>>> print(c is a)
True
>>> print(b is d)
True
>>> print(id(a)) #id() This function returns id or address of object.
140707260877528
>>> print(id(c))
140707260877528
>>>print(id(b))
140707260877848
>>>print(id(d))
140707260877848
27-07-2024 31
Python Programming Department of CSE (AIML)
Assignment Operators
• Python Assignment Operators
• Assignment operators are used to assign values to variables.
• Augmented assignment statements
27-07-2024 32
Python Programming Department of CSE (AIML)
Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
27-07-2024 33
Python Programming Department of CSE (AIML)
Assignment Operators
• >>> a=10
• >> a++
• SyntaxError: incomplete input
• >>> a=a+1
• >>> print(a)
• 11
• >>> a+=1
• >>> print(a)
• 12
• >>> b=10
• >>> b=b-2
• >>> print(b)
• 8
• >>> b-=2
• >>> print(b)
• 6
• >>> c=5
• >>> c=c*10
• >>> print(c)
• 50
• >>> c*=5
• >>> print(c)
• 250
27-07-2024 34
Python Programming Department of CSE (AIML)
Assignment Operators
▪ Walrus operator (OR) assignment expression operator:
▪ := is called walrus operator
▪ This operator is introduced in python 3.8 version.
▪ It is an assignment operator, but it is used as part of expression.
▪ >>> a=(b:=5+2)*(c:=5-2)
▪ >>> print(a)
▪ 21
▪ >>> print(b)
▪7
▪ >>> print(c)
▪3
27-07-2024 35
Python Programming Department of CSE (AIML)
Bitwise Operators
Bitwise Operators
• Bitwise operators are used to perform operations on binary data.
1. Shift operators
a. Left shift operator
b. Right shift operator
2. & bitwise and operator
3. | bitwise or operator
4. ^ bitwise XOR operator
5. ~ bitwise not operator
• Shift operators
• Shift operators are used to shift number of bits towards left side or right side.
1. Right shift operator >>
2. Left shift operator <<
• Right shift operator >>
• This operator is used to shift number of bits towards right side. By shifting number of bits
towards right side the value get decremented. It decrement value by deleting shifted
bits.
27-07-2024 36
Python Programming Department of CSE (AIML)
Number Systems
• In python integer values/literals are represented in four formats.
1. Decimal
2. Octal
3. Hexadecimal
4. Binary
Decimal, Octal, Hexadecimal and binary are called number system.
Number system defines set of rules and regulations for representing numbers
in computer science or programming language.
27-07-2024 37
Python Programming Department of CSE (AIML)
Number Systems
• Binary integer:
• Applications:
➢Images/Audio/Video
27-07-2024 38
Python Programming Department of CSE (AIML)
Bitwise Operators
• >>> a=0b10100
• >>> b=a>>2
• >>> print(bin(a))
• 0b10100
• >>> print(bin(b))
• 0b101
• >>> print(a,b)
• 20 5
27-07-2024 39
Python Programming Department of CSE (AIML)
Bitwise Operators
• Left shift operator <<
• This operator is used to shift number of bits towards left side. This operator
increment value by adding number of bits at right side.
• Syntax:
• Opr<<n
27-07-2024 40
Python Programming Department of CSE (AIML)
Bitwise Operators
▪ Logical Gates
▪ Logic gates are the basic building blocks of any digital system. It is an
electronic circuit having one or more than one input and only one output.
▪ The following operators are used to apply logic gates
1. & (AND gate)
2. | (OR gate)
3. ^ (XOR gate)
4. ~ (NOT gate)
27-07-2024 41
Python Programming Department of CSE (AIML)
Bitwise Operators
• & AND gate
27-07-2024 42
Python Programming Department of CSE (AIML)
Bitwise Operators
• Example:
• >>> a=0b1010
• >>> b=0b1000
• >> c=a&b
• >> print(a,b,c)
• 10 8 8
• >>> print(bin(a),bin(b),bin(c))
27-07-2024 43
Python Programming Department of CSE (AIML)
Bitwise Operators
• | or operation
27-07-2024 44
Python Programming Department of CSE (AIML)
Bitwise Operators
• ^ XOR operation
27-07-2024 45
Python Programming Department of CSE (AIML)
XOR Bitwise Operators
• >>> a=0b101
• >>> b=0b110
• >>> c=a^b
• >>> print(bin(a),bin(b),bin(c))
• >>> print(a,b,c)
•563
27-07-2024 46
Python Programming Department of CSE (AIML)
NOT Bitwise Operators
➢ ~ Not operator
Opr ~Opr
1 0
0 1
27-07-2024 47
Python Programming Department of CSE (AIML)
NOT Bitwise Operators
• >>> a=5
• >>> b=~a
• >>> print(a,b)
• 5 -6
• >>> c=~b
• >>> print(c)
•5
27-07-2024 48
Python Programming Department of CSE (AIML)
Week-1: Hackerrank: coding platform of international repute:
• Python Programming
• SUB-DOMAIN: Introduction:
• Hackerrank coding challenge -1: Say “Hello, World!” with python
• Here is a sample line of code that can be executed in Python:
Print(“Hello, World!”)
my_string = “Hello, World!”
print(my_sytring)
• Input Format:
You do not need to read any input in this challenge.
• Output Format:
Print Hello, World! to stdout
• Sample output:
Hello, World!
27-07-2024 49
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -2 : Python if-else
Given an integer, n, perform the following conditional actions:
▪ If n is odd, print Weird
▪ If n is even and in the inclusive range of 2 to 5 , print Not Weird
▪ If n is even and in the inclusive range of 6 to 20, print Weird
▪ If n is even and greater than 20 , print Not Weird
Input Format
▪ A single line containing a positive integer, n.
▪ Output Format
▪ Print Weird if the number is weird. Otherwise, print Not Weird.
Sample Input:
• 3
Sample Output:
• Weird
27-07-2024 50
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -2
• Program:
import math
import os
import random
import re
import sys
n=int(input())
if n%2==0 and 2<=n<=5:
print("Not Weird")
elif n%2==0 and 6<=n<=20:
print("Weird")
elif n%2==0 and n>20:
print("Not Weird")
else:
print("Weird")
27-07-2024 51
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -3: Arithmetic operators
➢The provided code stub reads two integers from STDIN, a and b. Add
code to print three lines where:
➢The first line contains the sum of the two numbers.
➢The second line contains the difference of the two numbers (first -
second).
➢The third line contains the product of the two numbers.
Example:
• a=3
• b=5
Print the following:
•8
• -2
• 15
27-07-2024 52
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -3
Input Format
• The first line contains the first integer, a .
The second line contains the second integer, b.
Output Format:
• Print the three lines as explained above.
Sample Input :
• 3
• 2
Sample Output:
• 5
• 1
• 6
Explanation:
• 3+2 ==> 5
• 3-2 ==> 1 3*2 ==> 6
27-07-2024 53
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -3
27-07-2024 54
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -4: Python : Division
▪ The provided code stub reads two integers, a and b, from STDIN.
▪ Add logic to print two lines. The first line should contain the result of integer
division, a // b . The second line should contain the result of float
division, a / b.
▪ No rounding or formatting is necessary.
Example
a=3
b=5
The result of the integer division 3 //5 =0
The result of the float division is 3/5 =0.6
print:
0
0.6
27-07-2024 55
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -4
Input Format
• The first line contains the first integer, a.
• The second line contains the second integer, b.
Output Format
Print the two lines as described above.
Sample Input:
4
3
• Sample Output:
1
1.33333333333
27-07-2024 56
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -4
Code:
a = int(input())
b = int(input())
print(a//b)
print(a/b)
27-07-2024 57
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -5: Loops
• The provided code stub reads and integer, n, from STDIN. For all non-negative
integers i < n, print i**2.
• Example
n=3
• The list of non-negative integers that are less than n = 3 is [0,1,2]. Print the square
of each number on a separate line.
• 0
• 1
• 4
Input Format
• The first and only line contains the integer, n.
Output Format
• Print n lines, one corresponding to each i.
Sample Input:
• 5
27-07-2024 58
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -5
Sample Output:
• 0
• 1
• 4
• 9
• 16
CODE:
n = int(input())
for i in range(0,n):
print(i**2)
27-07-2024 59
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -6 ==> Write a function (talk about leap year )
▪ An extra day is added to the calendar almost every four years as February
29, and the day is called a leap day. It corrects the calendar for the fact
that our planet takes approximately 365.25 days to orbit the sun. A leap
year contains a leap day.
▪ In the Gregorian calendar, three conditions are used to identify leap
years:
➢ The year can be evenly divided by 4, is a leap year, unless:
➢ The year can be evenly divided by 100, it is NOT a leap year, unless:
▪ This means that in the Gregorian calendar, the years 2000 and 2400 are
leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap
years.
27-07-2024 60
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -6 ==> talk about leap year
Task :Given a year, determine whether it is a leap year. If it is a leap year, return
the Boolean True, otherwise return False.
• Note that the code stub provided reads from STDIN and passes arguments to
the is_leap function. It is only necessary to complete the is_leap function.
Input Format:
• Read year, the year to test.
Output Format
• The function must return a Boolean value (True/False). Output is handled by the
provided code stub.
Sample Input:
• 1990
Sample Output:
• False
Explanation:
• 1990 is not a multiple of 4 hence it's not a leap year.
27-07-2024 61
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -6 ==> let us talk about leap year
Code:
# creating a function called ‘is_leap’ which takes one argument that is ‘year’as an
input parameter (parameterized function)
#to create a user defined function we use python built-in keyword ‘def’
def is_leap(year):
if year%100 ==0 and year%400==0:
return True
elif year%4==0 and year%100!=0:
return True
else:
return False
# calling a function
year = int(input()) # allow the user to enter input from keyboard
print(is_leap(year)) # calling a function called is_leap that takes year as an
argument.
27-07-2024 62
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -7 : print function
▪ The included code stub will read an integer, n, from STDIN.
▪ Without using any string methods, try to print the following:
▪ 123…n
▪ Note that "…" represents the consecutive values in between.
Example:
▪ N=5
▪ Print the string 12345 .
Input Format:
▪ The first line contains an integer n.
Output Format
▪ Print the list of integers from 1 through n as a string, without spaces.
Sample Input:
▪3
Sample Output:
▪ 123
27-07-2024 63
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -7
• CODE:
n=int(input())
for i in range(1,n+1):
print(i,end='')
27-07-2024 64
Python Programming Department of CSE (AIML)
Programming exercises
• sum=0
• while num>0:
• r=num%10
• sum=sum + r
• num=num//10
27-07-2024 65
Python Programming Department of CSE (AIML)
Programming exercises
▪ Write a program to display product of digits of number accepted from
user.
• num=int(input("Enter any number"))
• p=1
• while num>0:
• r=num%10
• p=p*r
• num=num//10
• print(f'Sum of digits {p}')
• Output:
• Enter any number345
• Sum of digits 60
27-07-2024 66
Python Programming Department of CSE (AIML)
Programming exercises
▪ Python program to print all prime numbers in a given interval ( use break).
lower=int(input("Enter any number"))
upper=int(input("Enter any number"))
for num in range(lower,upper+1):
if num>1:
for i in range(2,num):
if (num%i)==0:
break
else:
print(num)
▪ Note: A prime number is a positive number that has only two factors, 1 and
the number itself. Numbers such as 2, 3, 5, 7, 11, etc., are prime numbers as
they do not have any other factors other than 1 and themselves.
27-07-2024 67
Python Programming Department of CSE (AIML)
Programming exercises
▪ Print below Floyd’s triangle pattern using for loop.
5
44
333
2222
11111
Solution:
for i in range(5,0,-1): # range(5,0,-1) generates sequence of numbers : 5,4,3,2,1
for j in range(i,6):
print(i,end=" ")
print() # for printing new line
27-07-2024 68
Python Programming Department of CSE (AIML)
Programming exercises
#Python program to print the Fibonacci sequence using while loop.
num_terms=int(input("Enter number of terms that you want to print in fibonaaci"))
n1=0
n2=1
counter=0
while counter<num_terms:
print(n1)
next_term=n1+n2
n1=n2
n2=next_term
counter +=1 #counter = counter +1
27-07-2024 69
Python Programming Department of CSE (AIML)
Week-1 & 2 Assignment
27-07-2024 70
Python Programming Department of CSE (AIML)
Week-1 & 2 Assignment
27-07-2024 71
Python Programming Department of CSE (AIML)
Week-2: Hackerrank coding challenges: sub-domain: Basic Data Types
Input Format:
• The first line contains the integer n, the number of students' records. The
next n lines contain the names and marks obtained by a student, each
value separated by a space. The final line contains query_name, the
name of a student to query.
27-07-2024 72
Python Programming Department of CSE (AIML)
Problem: ‘Finding the percentages’
Output Format:
▪ Print one line: The average of the marks obtained by the particular student
correct to 2 decimal places
Sample Input:
▪2
▪ Harsh 25 26.5 28
▪ Anurag 26 28 30
▪ Harsh
Sample Output:
▪ 26.50
27-07-2024 73
Python Programming Department of CSE (AIML)
Problem: ‘Finding the percentages’
n=int(input("Number of students"))
list1=[] # Initializing empty list
list2=[]
dict1={} # Initializing empty dictionary
for i in range(n):
name=input("Enter name of the student")
list1.append(name)
score=list(map(float,input("Enter score of a student ==> enter space separated values").split()))
dict1.fromkeys(list1) # use BIF dict.fromkeys(sequence,value)
dict1[name]=score
list2=list(set(list1)) #remove duplicates in list1 ==> use set() BIFs
print(list1)
print(list2)
print(dict1)
query_name=input()
if query_name in list2:
scores=dict1[query_name]
average=sum(scores)/len(scores)
print(f'{average:.2f}')
27-07-2024 74
Python Programming Department of CSE (AIML)
Problem: ‘Finding the percentages’
n = int(input("Enter number of students"))
student_marks = {}
for x in range(n):
name, *marks = input("Enter name and scores separated by space: ").split()
scores = list(map(float, marks))
student_marks[name] = scores
query_name = input("Enter name of the student for whom you want to calculate
average of marks: ")
if query_name in student_marks:
scores = student_marks[query_name]
avg_score = sum(scores) / len(scores)
print(f'{avg_score:.2f}')
else:
pass
27-07-2024 75
Python Programming Department of CSE (AIML)
Problem: ‘Finding the percentages’
n = int(input("Enter number of students"))
student_marks = {}
for x in range(n):
name, *marks = input("Enter name and scores separated by space: ").split()
scores = list(map(float, marks))
student_marks[name] = scores
query_name = input("Enter name of the student for whom you want to calculate
average of marks: ")
if query_name in student_marks:
scores = student_marks[query_name]
avg_score = sum(scores) / len(scores)
print(f'{avg_score:.2f}')
else:
pass
27-07-2024 76
Python Programming Department of CSE (AIML)
Problem: ‘Finding the percentages’
▪ name, *marks = input().split() # this line takes user input and splits it into
list of strings separated by white space and assigns the first element to
the variable ‘name’ and rest of the elements in the list to list ‘marks’.
▪ The * operator in front of ‘marks’ unpacks all remaining elements into
‘marks’
▪ scores = list(map(float, marks)) # converts elements of list marks into
float values and converts result into list using list() Built-in function. This
float values represents the scores of the student.
▪ student_marks[name] = scores # This line of python code assigns the
‘list of scores’ to the dictionary ‘student_marks’, with the student's name
‘name’ as the key.
27-07-2024 77
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -2: Problem: List Comprehensions:
Task: Let's learn about list comprehensions! You are given three integers x,y and z
representing the dimensions of a cuboid along with an integer n. Print a list of all possible
coordinates given by (i,j,k) on a 3D grid where the sum of i+j+k is not equal to n . Here,
0≤i≤x, 0≤j≤y, 0≤k≤z. Please use list comprehensions rather than multiple loops, as a learning
exercise.
List Comprehension:
▪ List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Syntax:
▪ The return value is a new list, leaving the old list unchanged.
Condition:
▪ The condition is like a filter that only accepts the items that valuate to True.
27-07-2024 78
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -2: Problem: List Comprehensions:
x = int(input("Enter x: "))
y = int(input("Enter y: "))
z = int(input("Enter z: "))
n = int(input("Enter n: "))
print(possible_coordinates)
27-07-2024 79
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -2: Problem: List Comprehensions:
Sample Input:
Enter x: 2
Enter y: 2
Enter z: 3
Enter n: 4
Sample Output:
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], [0, 2, 1],
[0, 2, 3], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 3], [1, 2, 0], [1, 2, 2],
[1, 2, 3], [2, 0, 0], [2, 0, 1], [2, 0, 3], [2, 1, 0], [2, 1, 2], [2, 1, 3], [2, 2, 1], [2, 2, 2],
[2, 2, 3]]
27-07-2024 80
Python Programming Department of CSE (AIML)
List Comprehensions:
# OUTPUT:
# ['ai', 'acd']
27-07-2024 81
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -3: Problem: Find the runner-up score
▪ Task: Given the participants' score sheet for your University Sports Day, you
are required to find the runner-up score. You are given n scores. Store
them in a list and find the score of the runner-up.
Input Format:
▪ The first line contains n. The second line contains an array A[] of n integers
each separated by a space.
Output Format:
▪ Print the runner-up score.
Sample Input:
▪5
▪23665
Sample Output:
▪5
27-07-2024 82
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -3: Problem: Find the runner-up score
n=int(input())
array_A=list(map(int,input().split()))
array_A.sort()
n=array_A.count(max(array_A))
print(array_A[-(n+1)])
27-07-2024 83
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -4: Lists
Task: Consider a list (list = []).
You can perform the following commands:
1.insert i e: Insert integer at position .
2.print: Print the list.
3.remove e: Delete the first occurrence of integer .
4.append e: Insert integer at the end of the list.
5.sort: Sort the list.
6.pop: Pop the last element from the list.
7.reverse: Reverse the list.
▪ Initialize your list and read in the value of n followed by n lines of
commands where each command will be of the 7 types listed above.
Iterate through each command in order and perform the corresponding
operation on your list.
27-07-2024 84
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -4: Lists
Input Format:
Constraints:
Output Format:
For each command of type print, print the list on a new line.
27-07-2024 85
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -4: Lists
n = int(input())
list = []
for i in range(n):
cmd = input().split()
if cmd[0] == 'append':
list.append(int(cmd[1]))
elif cmd[0] == 'print':
print(list)
elif cmd[0] == 'insert':
list.insert(int(cmd[1]), int(cmd[2]))
elif cmd[0] == 'remove':
list.remove(int(cmd[1]))
elif cmd[0] == 'sort':
list.sort()
elif cmd[0] == 'pop':
list.pop()
elif cmd[0] == 'reverse':
list.reverse()
27-07-2024 86
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -4: Lists
Sample Input:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output:
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
27-07-2024 87
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -5:Nested Lists
Task: Given the names and grades for each student in a class of N students,
store them in a nested list and print the name(s) of any student(s) having
the second lowest grade.
Input Format:
▪ The first line contains an integer N, the number of students.
The 2N subsequent lines describe each student over lines.
- The first line contains a student's name.
- The second line contains their grade.
Output Format:
Print the name(s) of any student(s) having the second lowest grade in. If
there are multiple students, order their names alphabetically and print each
one on a new line.
27-07-2024 88
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -5:Nested Lists
n=int(input())
student = []
marks = []
names = []
for i in range(n):
name = input()
score = float(input())
student.append([name, score])
for item in student:
marks.append(item[1])
marks = list(set(marks))
marks.sort()
for item in student:
if marks[1] == item[1]:
names.append(item[0])
names.sort()
for name in names:
print(name)
27-07-2024 89
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -6
Task: (Problem)
Given an integer, n, and n space-separated integers as input, create a
tuple, t , of those n integers. Then compute and print the result of hash(t) .
• Note: hash() is one of the functions in the __builtins__ module, so it need
not be imported.
Input Format:
▪ The first line contains an integer, n, denoting the number of elements in
the tuple.
The second line contains n space-separated integers describing the
elements in tuple t .
Output Format:
• Print the result of hash(t).
27-07-2024 90
Python Programming Department of CSE (AIML)
Hackerrank coding challenge -6
CODE:
n = int(input())
t = tuple(map(int, input().split()))
print(hash(t))
Explanation:
hash(object)
Return the hash value of the object (if it has one). Hash values are integers. They
are used to quickly compare dictionary keys during a dictionary lookup. Numeric
values that compare equal have the same hash value (even if they are of different
types, as is the case for 1 and 1.0).
Note
For objects with custom __hash__() methods, note that hash() truncates the return
value based on the bit width of the host machine.
27-07-2024 91
Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use on lists
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
27-07-2024 92
Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use on lists
Method Description
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
27-07-2024 93
Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use on dictionaries.
# write a python program for demonstrating BIFs to work with Dictionary
dict1={"name":"ram", "rollno": 565, 'branch': "AIML"} # initializing a dictionary
print(dict1)
print(dict1.get("name"))
print(dict1.items())
print(dict1.keys())
print(dict1.pop("rollno"))
print(dict1)
print(dict1.clear())
keys=range(10)
dict2=dict.fromkeys(keys)
print(dict2)
keys2=['sr','rollno','branch']
dict3=dict.fromkeys(keys2,100)
print(dict3)
94
27-07-2024 Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
Syntax: dict.fromkeys(sequence,value)
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
index() Searches the tuple for a specified value and returns the position
of where it was found
96
27-07-2024 Python Programming Department of CSE (AIML)
Example python program for demonstrating BIFs to process tuple.
t1=(1,2,3,4,3,4)
print(type(t1))
print(t1.count(3))
print(t1.index(4))
print(len(t1))
print("converting other sequences into a tuple:", tuple([6,5,4]))
print("converting other sequences into a tuple:", tuple("SREYAS"))
print(min(t1))
print(max(t1))
print(sum(t1))
97
27-07-2024 Python Programming Department of CSE (AIML)
Example python program for demonstrating BIFs to process tuple.
OUTPUT:
<class 'tuple'>
2
3
6
converting other sequences into a tuple: (6, 5, 4)
converting other sequences into a tuple: ('S', 'R', 'E', 'Y', 'A', 'S')
1
4
17
98
27-07-2024 Python Programming Department of CSE (AIML)
Example program on tuples
>>> t1=(1,2,3,4)
>>> print(sum(t1))
10
>>> print(max(t1))
4
>>> print(min(t1))
1
>>> print(t1.index(3))
2
99
27-07-2024 Python Programming Department of CSE (AIML)
❖ Tuple operators and Built-in Functions
▪ creation, repetition and concatenation
>>> tuple1=(["ai",100],45,-103.45)
>>> print(tuple1)
(['ai', 100], 45, -103.45)
>>> print(tuple1*2)
(['ai', 100], 45, -103.45, ['ai', 100], 45, -103.45)
>>> print(tuple1+("python","java"))
(['ai', 100], 45, -103.45, 'python', 'java')
100
27-07-2024 Python Programming Department of CSE (AIML)
❖ Tuple operators and Built-in Functions
▪ Membership and slicing
>>> tuple2=(23,45,"acd","dbms","AI","Python")
>>> print( 23 in tuple2)
True
>>> print("acd" not in tuple2)
False
>>> print(tuple2[0])
23
>>> print(tuple2[::])
(23, 45, 'acd', 'dbms', 'AI', 'Python')
101
27-07-2024 Python Programming Department of CSE (AIML)
❖ Tuple operators and Built-in Functions
▪ Built-in Functions
>>> t1=(['xyz',123],23,-103.4,'free','easy','popular','opensource')
>>> str(t1)
"(['xyz', 123], 23, -103.4, 'free', 'easy', 'popular', 'opensource')"
>>> len(t1)
7
>>> list(t1)
[['xyz', 123], 23, -103.4, 'free', 'easy', 'popular', 'opensource']
102
27-07-2024 Python Programming Department of CSE (AIML)
❖ Tuple operators
>>> (4,2) < (3,5)
False
>>> (2,4) < (3,-1)
True
>>> (2,4) == (2,4)
True
>>> (2,4) == (3,-1)
False
103
27-07-2024 Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use it to handle strings
Method Name Description
String.capitalize() Capitalizes first letter of string
String.islanum() Returns True if string has at least 1 character and all characters are
alphanumeric and False otherwise
String.isalpha() Returns True if string has at least 1 character and all characters are
alphabetic and False otherwise
String.isdecimal() Returns True if string contains only decimal digits and False
otherwise
104
27-07-2024 Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use it to handle strings
Method Name Description
String.isdigit() Returns True if string contains only digits and False otherwise
String.islower() Returns True if string contains at least 1 cased character and all
cases characters are in lowercase and False otherwise
String.isupper() Returns True if string contains at least 1 cased character and all
cases characters are in uppercase and False otherwise
String.isnumeric() Returns True if string contains only numeric characters and False
otherwise
String.isspace() Returns True if string contains only whitespace characters and
False otherwise
String.istitle() Returns True if string is properly “titlecased” and False otherwise
105
27-07-2024 Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use it to handle strings
Method Name Description
String.join(seq) Merges(concatenates) the string representation of elements in
sequence seq into a string
String.ljust(width) Returns space padded string with the original string left-justified to
a total of width columns
String.lower() Converts all uppercase letters in string to lowercase
106
27-07-2024 Python Programming Department of CSE (AIML)
Python has a set of built-in methods that you can use it to handle strings
Method Name Description
String.swapcase() Inverts case for all letters in string
isascii() Returns True if all the characters in the string are ASCII characters
107
27-07-2024 Python Programming Department of CSE (AIML)
BIFs (BIMs) in Python for handling strings: Programming exercise
string="python programming"
print(string.capitalize())
str1="artificial intelligence"
print(str1.count("dbms"))
str2="Hi Sreenivasu how are you welcome to world of java"
print(str2.find("ai")) # returns index if str found in string otherwise -1
print(str2.index("are")) # same as find(), but raises an exception if str not found
string3="acd"
print(string3.isalnum())
print(string3.isalpha())
seq="$$"
print(string3.join(seq))
108
27-07-2024 Python Programming Department of CSE (AIML)
Built-in Methods (BIMs) in Python - SET
Python has a set of built-in methods that you can use on sets.
Method name (function Description
name)
add() Adds an element to the set
109
27-07-2024 Python Programming Department of CSE (AIML)
Built-in Methods (BIMs) in Python - SET
Python has a set of built-in methods that you can use on sets.
Method name (function Description
name)
intersection() Returns a set, that is the intersection of two or more sets
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
110
27-07-2024 Python Programming Department of CSE (AIML)
Built-in Methods (BIMs) in Python - SET
Python has a set of built-in methods that you can use on sets.
Method name (function name) Description
111
27-07-2024 Python Programming Department of CSE (AIML)
SET : Operations
#set operations
#difference() => returns a set containing a difference of two or more sets => set1-
#set2
set_a={1,2,3,4,5}
set_b={3,4,5,6,7,9}
print("set_a elements: ",set_a)
print("set_a elements: ",set_b)
print("difference of set_a and set_b: ",set_a.difference(set_b)) # set_a - set_b)
print("difference of set_b and set_a: ",set_b.difference(set_a)) # set_b - set_a)
#symmetric_difference() => returns a set containig symmetric differences of two
#sets
print("symmetric_difference of set_a and set_b: ",set_a.symmetric_difference(set_b))
112
27-07-2024 Python Programming Department of CSE (AIML)
SET : Operations
OUTPUT:
set_a elements: {1, 2, 3, 4, 5}
set_a elements: {3, 4, 5, 6, 7, 9}
difference of set_a and set_b: {1, 2}
difference of set_b and set_a: {9, 6, 7}
symmetric_difference of set_a and set_b: {1, 2, 6, 7, 9}
113
27-07-2024 Python Programming Department of CSE (AIML)
SET : Operations
#symmetric_difference_update() => inserts the symmetric differences from this set
# and another set
# syntax: set1.symmetric_difference_update(set2)
# shorter syntax: set1 ^= set2
set1={'apple','banana','grapes'}
set2={'apple','microsoft','google'}
print("elements of set1: ",set1)
print("symmetric_difference is: ",set1.symmetric_difference(set2))
set1.symmetric_difference_update(set2)
#set1 ^= set2
print("updated set: ",set1)
114
27-07-2024 Python Programming Department of CSE (AIML)
SET : Operations
OUTPUT:
115
27-07-2024 Python Programming Department of CSE (AIML)
SET : Operations : Programming exercises
#python program for demonstrating set-operations
# A Set is an unordered collection of unique elements.
#creating empty set
empty_set=set() # you can create empty set using the set() constructor method
set1=set("apple") #you can provide any type of sequence as the argument to set() constructor method
print("created set1: ",set1)
set2=set("applephone")
print("created set2: ",set2)
# add() method ==> adds an element to the set
set1.add(3)
print("updated set1: ",set1)
#discard() method ==> Removes the specified item
set1.discard(3)
print("updated set1: ",set1)
#remove() method ==> Removes the specified item
set1.remove("p")
print("updated set1: ",set1)
#pop() method ==> Removes an element from the set
set1.pop()
print("updated set1: ",set1)
116
27-07-2024 Python Programming Department of CSE (AIML)
SET : Operations : Programming exercises
OUTPUT:
117
27-07-2024 Python Programming Department of CSE (AIML)
FROZEN SET : Programming exercises
➢Frozen set is a immutable object.
➢Syntax: frozenset(iterable) # An iterable object like list,set,tuple etc.
>>> set1={1,2,3,4,4,5,6}
>>> print(set1)
{1, 2, 3, 4, 5, 6}
>>> #creating a frozenset using frozenset() constructor method
>>> frozen_set1=frozenset(set1)
>>> print("created frozen set: ",frozen_set1)
created frozen set: frozenset({1, 2, 3, 4, 5, 6})
>>> print(type(set1))
<class 'set'>
>>> print(type(frozen_set1))
<class 'frozenset'>
118
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
➢Exception Handling
➢What is Exception?
119
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
▪ Types of Errors:
1. Syntax Error
2. Logical Errors
3. Runtime Errors
➢Syntax Error
➢All compile time errors are called syntax errors. If there is a syntax error within
program; program is not executed.
120
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
➢Syntax errors must be rectified by programmer in order to execute program.
Logical Errors:
121
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
➢Runtime Errors:
➢An error which occurred during execution of program is called runtime error.
➢Runtime errors occur because of wrong input given by end user. When
runtime error occurs, program execution is terminated.
122
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
Advantage of error handling or exception handling:
1. try
2. except
3. finally
4. raise
123
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
Errors / Exceptions are of two types:
❖NOTE: Exception is a root class or base class for all exception types.
124
27-07-2024 Python Programming Department of CSE (AIML)
Errors / Exceptions are of two types
125
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
try block:
Syntax:
try:
statement1
statement2
126
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
except block
• except block is an error handling block. If there is an error inside try block, that
error is handled by except block.
127
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
➢Predefined exception type with description
➢exception ZeroDivisionError
➢ finally
➢ finally is a keyword.
➢ finally block is used to de-allocate the resources allocated within try block.
➢ Finally block contains statements which are executed after execution of try block and
except block.
128
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
Syntax-1 Syntax-2
try: try:
statement-1 statement-1
statement-2 statement-2
except error-type: finally:
statement-3 statement-3
finally:
statement-4
129
27-07-2024 Python Programming Department of CSE (AIML)
Hackerrank coding challenge : Exceptions
t=int(input())
for i in range(t):
try:
a,b=map(int,input().split())
int_divison=a//b
print(int_divison)
except ZeroDivisionError as e:
print("Error Code:",e)
except ValueError as e:
print("Error Code:",e)
130
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
# write a python program for demonstrating exception handling
try:
a=int(input("Enter value of a"))
b=int(input("Enter value of b"))
result=a/b
print(result)
except ZeroDivisionError as e:
print("Dear User number a can not be divided with zero",e)
except ValueError as e:
print("Value error: ",e)
finally:
print("Program is executed")
131
27-07-2024 Python Programming Department of CSE (AIML)
Exceptions: Exceptions in Python, Detecting and Handling Exceptions
# write a python program for demonstrating exception handling (with single #
except block)
try:
a=int(input("Enter value of a"))
b=int(input("Enter value of b"))
result=a/b
print(result)
except Exception as e: # parent class for all exceptions is 'Expection'
print(e)
finally:
print("program is executed")
132
27-07-2024 Python Programming Department of CSE (AIML)