Part-I Basic Python Programming
Part-I Basic Python Programming
Part-I
Basics of Programming in Python
2. Write a program to read the name of the user and greet him with a hello message.
Hint: Use input() statement to give a prompt to read a name as well as read whatever you type
on the keyboard.
3. See the following program. The objective of the program is to read two integer values from the
console and print the sum of the numbers. If the following program does not work, do the needful
correction.
num1 = input("Enter num1: ") #Read the first number
num2 = input("Enter num2: ") #Read the second number
©Debasis Samanta 1
4. You have to print the following message in nicely formatted way as given below.
5. In the following program, see the print statements. Run the program and comment on if they work
for you or not. If works, then interpret the output.
print("\n" + fName + " " + lName) #This is another and a better way
Note: See how a comment a large enough to fit in a line in a Python program can be given.
6. The following program gives an idea about more on ‘print’ statement in Python.
The use of sep=’’ allows to separate the text with no space (e.g., sep=’’), blank space (e.g.,
sep=’ ’) and or with any character (e.g., sep=’ * ’.
Also, the end=’ ‘ can be used to end a message with any character including ‘\n’ explicitly.
7. The following program with string modulo operator (%), with which you can print with a number of
format to print numbers.
©Debasis Samanta 2
# Python program showing how to use string modulo operator(%)
8. A few more formatting you can learn from the following Python program. Run and understand how
they work.
print('I love {} for "{}!"'.format('Python', 'Programming', ‘for’, ‘Data
Analytics’))
10. Write a program which will merge the words “Welcome”, “to”, “Python”, “Programming” into a
single string “Welcome to Python Programming”
11. Following is a program. Interpret the statements under Part-A and Part-B, how they make sense.
©Debasis Samanta 3
#Part-A
x = 10 #Here, x is an integer variable
print('x =', x)
x = 20 #Here, x takes another value
print('x =', x)
x = 30
print('x =', x)
#Part-B
x = 10
print('x = ' + str(x)) #An integer value is converted into a string value
x = 20
print('x = ' + str(x))
x = 30
print('x = ' + str(x))
12. Write a Python program to delete an i-th letter from a string. Read the string and i from the user.
Print the string after the removal.
Hint: Use string slicing. Delete the previous string. Hint: Use del command.
Integer, float, and string are the common data types in Python
13. A variable can be declared as integer, string or a float. See the program below.
Note: Different types of variables can be “explicitly” declared by assigning different types of values
©Debasis Samanta 4
14. Assignment may not only changes a variable’s value during its use within an executing program; the
type of a variable can change as well. See the following program.
a = 10
print('First, variable a has value', a, 'and type', type(a))
a = 15.5
print('Next, variable a has value', a, 'and type', type(a))
a = 'ABC'
print('Now, variable a has value', a, 'and type', type(a))
15. See the following program and then explain why the program is not correct?
x = 10
x = y + x #Why this is not correct
y=5
x=y+2
y+2=x #This is not correct either
Note: A variable if it is not assigned a value, then it is not declared and hence invalid variable in the
program. Further, value cannot be assigned to an expression; expression is should be at right
16. The following program will show how to read values of different types and do some operations on
them
©Debasis Samanta 5
17. The following program will show some operations with variables.
18. The following program is written without any error. However, it will produce error, if data is/are not
entered appropriately.
#This following block will work fine for any input value entered
# input
input1 = input()
input2 = input()
# output
print(input1)
print(input2)
Hint: Run this program with a) 567 and 3.1732 b) 1.45e12 and ABC
#However, the following block may produce errors!
# input
num1 = int(input())
num2 = float(input())
©Debasis Samanta 6
19. Typecasting: In Python, you can convert one type of value to another. This is called typecasting. The
following program will show different conversions
# input
num1 = int(input()) #Read an input value from the keyboard
num2 = float(input()) #User should type a float value here
num4 = int(num2)
print(num4, type(num4)
print(num3+ num4)
#Printing the results: Default is float, which is in higher rank
# input
string1 = str(input()) #Anyway, this will read everything as string
# output
print(string1) #Okay
# Or by default
string2 = input()
# output
print(string2)
#Type casting: From string to float: Here, you should enter value: 3.17
y = float(string2)
print(x+y) #You will see the result in floating point values
Note: float to int will result a loss of value as it truncates the value after decimal point
20. Multi-scanning: The following program shows how a multiple input can be read form the keyboard
with a single input() statement (with split())
©Debasis Samanta 7
# Taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
print(x, y, sep=',', end='@')
21. Comma separated input to Python program. Alternative to P 19, you can also read input separated
by comma, instead of blank space.
22. Following are the few programming exercises and you are advised to write programs for them.
Write a program which will read number of seconds. Then it will print in the format: hh-mm-ss. For
example, if you read 1000, then it will print 1-46-40.
Hint: Use // (gives floor of x divided by y, e.g., 25//4 = 6) and % (gives remainder of x divided by y, e.g. 25%4
gives 1). Note, both x and y should be integer values. Similarly, x**y return the value of x to the power y. A
hint of the program is given below. However, first you should try of your own!
©Debasis Samanta 8
# Get the number of seconds
seconds = int(input("Please enter the number of seconds:"))
# First, compute the number of hours in the given number of seconds
# Note: integer division with possible truncation
hours = seconds // 3600 # 3600 seconds = 1 hours
# Compute the remaining seconds after the hours are accounted for
seconds = seconds % 3600
# Next, compute the number of minutes in the remaining number of seconds
minutes = seconds // 60 # 60 seconds = 1 minute
# Compute the remaining seconds after the minutes are accounted for
seconds = seconds % 60
# Report the results
print(hours, "hr,", minutes, "min,", seconds, "sec")
a. When the program runs, it produces -17.778, which is not correct. Why the following program
does not produce correct results? Debug the program and then correct it.
b. Consider the following program that attempts to compute the circumference of a circle given
the radius entered by the user. Given a circle’s radius, r, the circle’s circumference, C is given
by the formula C = 2𝜋𝑟, where = 3.14159
PI = 3.14159
# Formula for the area of a circle given its radius
C = 2*PI*r
# Get the radius from the user
r = float(input("Please enter the circle's radius: "))
The program does not produce the intended result. Why? How can it be repaired so that it
works correctly?
©Debasis Samanta 9
P4: A few more on data types in Python
Integer, float and string we have learned. String is an important data type, which needs a few more
practices to deal with. Further, in Python, there are other data types, such as list, set, tuple, and
dictionary, which we are going to learn and practice.
23. The following program gives an idea about the different data types in Python. You have to Google
search for the data type which are new to you. The program below is not complete. You have to read
the value for each followed by print the value with it’s type.
©Debasis Samanta 10
24. A string is a sequence of characters that can be a combination of letters, numbers, and special
characters. It can be declared in python by using single quote (‘), double quote (“), or even triple
quote (‘’’). These quotes are not a part of a string, they define only starting and ending of the string.
Following program illustrates how a string can be created in a Python program.
25. An element in a string can be accessed by using indexing or slicing. Characters in a string of length n
are indexed from 0 to n-1. Check the following program to know how a element in string can be
accessed.
©Debasis Samanta 11
Continued to…
# Printing the last character
print("\nLast character of String is: ")
print(string1[-1])
#Alternatively
l = len(string1)
print("\nLast character of String is: ")
print(string1[l-1])
Note: Elements in a string is indexed from last to first as 0, 1, 2, 3, …Also, they are indexed from
last to first as -1, -2, -3, …
26. String slicing: Slicing is to find substring of a string. Check the following program, which is self-
explanatory.
# Creating a String
string1 = "Welcome to Python"
print("Initial String: ")
print(string1)
27. String reversing: Reverse a string using slicing. The following program reverses its elements in
opposite sequence.
28. String merging: Two or mor string data can be merged to a single string. The following is a simple
program for you.
©Debasis Samanta 12
# Python Program to merge two strings
string1 = "Python"
print("Initial string: ")
print(string1)
string2 = "Programming"
print("Another string: ")
print(string2)
29. There are some methods for easy some operations with string data. Following program lists some of
the important of them.
There are four collection data types in the Python programming language:
• List is a heterogeneous collection which is ordered, changeable (i.e., mutable) and indexed.
Allows duplicate members. Example, list = [‘Apple’, 35, 45.6, 35]
• Tuple is a heterogeneous collection which is ordered, unchangeable (i.e., immutable) and
indexed. Allows duplicate members.
Example: tuple = (“Debasis”, 56, 9434008349, 56)
©Debasis Samanta 13
• Set is a heterogeneous collection which is unordered, changeable (i.e., mutable), and
unindexed. Does not allow duplicate members.
Example: set = {‘A’, ‘E’. ‘I’, ‘O’, ‘U’, 5}
• Dictionary is a heterogeneous collection which is ordered, and changeable (i.e., mutable), and
indexed. Does not allow duplicate members.
Example: dict = {1: ‘Apple’, 2: ‘Banana’, 3: ‘Mango’, 8: 23.45}
In the following few practice program, we shall learn about each of them.
30. List: List is an ordered, heterogeneous collection of data. It allows duplicate elements in it. List is
mutable, that is, you can add, remove, or change any element in it. Each element in a list is indexed
starting from 0. The following program show you how to create a list and do some operation with it.
x = 5
# Declaring a list
List1 = ["Apple", 'Banana', "Cherry", x, 4+6]
print(list)
©Debasis Samanta 14
31. Tuple: A tuple of a student is (<name>, <marks>, <deptt>). For example, (‘Debasis’, 98.5, “CS”) is a
tuple.
Consider the following listing, which also shows how to create tuples, list of tuples, tuple of lists and
tuple of tuples, etc.
# Creating three tuples
tuple1 = (‘Debasis’, 98.5, “CS”)
tuple2 = (“Appu”, 65.9, 65.9, “EE”)
tuple3 = (“Jyoti”, 99.8, “EC”)
# List of tuples
list1 = [tuple1, tuple2, tuple3] #Putting tuples into a list:
print(list1) #Printing the list
32. Following listing illustrates the difference between list and tuple.
list1 = [1, 2, 3, 4, 5, 6, 7] #Creating a list
tuple1 = (1, 2, 3, 4, 5, 6, 7) #Creating a tuple
print('The list:', list1)
print('The tuple:', tuple1)
# Access an element
print('The first element in the list:', list1[0])
print('The first element in the tuple:', tuple1[0])
©Debasis Samanta 15
Continued on …
# Slicing the list and tuple
print('List slice:', list1[2:5]) Sublist from 3rd to 6th elements
print('Tuple slice:', tuple1[2:5])
33. The following program illustrates a few more features with tuple in Python.
# Creating a tuple with repetition
tuple1 = ('OM',) * 3
print("\nTuple with repetition: ")
print(tuple)
# Tuple unpacking
Tuple3 = ("God", "is", "Great!")
(a, b, c) = Tuple2
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
# Concatenation of tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('A', 'B', 'C')
©Debasis Samanta 16
Continued on …
print(tuple4)
# Slicing a tuple
# Reversing a tuple
print("\nTuple after sequence of Element is reversed: ")
print(tuple5[::-1])
list1[3] = 77
print("Example to show mutability ", list1)
34. Set: A set collection is similar to tuple and list. There are, however, some difference among them.
• All are heterogeneous collection of data.
• Set is an unordered collection, whereas list and tuple are ordered collection. This means, {1, 2,
3} are {3, 1, 2} are the same sets. On the other hand, [1, 2, 3] and [3, 1, 2] are two different lists.
• Set does not allow duplicate elements, that is, {1, 1, 2, 2} is not a valid set, whereas list and tuples
allow duplicate elements; thus (1, 1, 2, 2) is a valid tuple and [1,1,1,1] is a valid list.
• Set and list both are mutable, i.e., changeable unlike tuple, which is immutable.
Following is a program shows the different ways that a set can be created.
#A simple way to create a set
fruits = {"Apple", "Banana", "Orange"}
print(set1, type(fruits))
©Debasis Samanta 17
Note: The element ordering is not preserved, and duplicate elements appear only once in the set.
With set comprehensions and generator expressions, we can build sets. It is also applicable to
list.
35. There are several methods to work with set. To know the different methods for set operation, you
are advised to Google search. In the following, a few examples are shown.
#Set is mutable: You can add, remove, append element, etc.
#Create a set
set1 = set(["a", "b", "c"])
print(“Initial set:”, set1)
36. Following is a listing to illustrate a few set related operations (theses are known in relational algebra).
Opera7on Nota7on Return Operator Method
Union A∪B Elements in A or B or A|B union()
both
Intersec7on A∩B Elements common to A&B intersec7on()
both A and B
Set difference A−B Elements in A but not A-B difference()
in B
Symmetric A⊕B Elements in A or B, AˆB Symmetric_difference
difference but not both
Set x∈A x is a member of A x in A x in A
membership
Set x∉A x is not a member of A x not in A x not in A
membership
Set equality A=B Sets A and B contain A ==B A ==B
exactly the same
elements
©Debasis Samanta 18
# Python Program to demonstrate union oftwo sets
people = {"Jay", "Idrish", "Archil"}
vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}
for i in range(5):
set1.add(i)
print(“Set 1:”, set1)
for i in range(3,9):
set2.add(i)
print(“Set 2:”, set2)
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
print("\nFrozen Set")
print(frozen_set)
38. Dictionary: Dictionary is a collection of key:value pairs. Dictionary holds key:value pair as a
sequence of elements within curly {} braces, separated by ‘comma’. Values in a dictionary can be of
any data type (i.e., heterogeneous) and can be duplicated, whereas keys can’t be repeated and must
be immutable. Ordering of elements is not important.
©Debasis Samanta 20
Continued on …
# Adding elements one at a time
dict[0] = 'Apple' # Add 0:’Apple’
dict[2] = 'Banana' # Add 2:’Banana’
dict[3] = 123 # Add 3: 123
print("\nDictionary after adding 3 elements: ")
print(dict)
# Creating a Dictionary
dict = {1: 'Apple', 'name': 'Banana', 3: 'Orange'}
print("Dictionary =")
print(dict)
#Deleting some of the element with key value 1
del(dict[1])
print("Data after deletion Dictionary=")
print(dict)
39. Few problems for practice is given below. Write program for each.
a. Write a program which will take the following lists and set to create a larger list, which should
include all the elements in the lists list1 and list2 and set set3.
Also, find the union, intersection and difference of the sets obtained from the list list1 and
list2. Print all the sets you have obtained.
list1 = [1, 2, 3, 4]
list2 = [1, 4, 2, 3, 5]
set3 = {'a', 'b', 'c'}
©Debasis Samanta 21
b. The following is a program which shows how to create a set given a list and can be updated.
# Python program to demonstrate the use of update() method
list1 = [1, 2, 3]
list2 = [5, 6, 7]
list3 = [10, 11, 12]
# Update method
set1.update(set2)
c. Given a set and a dictionary as below. Write a program which will include all the elements from
the dictionary to set.
Set1 = {1, 2, 3, 4, 5}
myDict = {6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten'}
Hint: Set1.update(myDict)
d. The following program create a dictionary and then updating elemnets/ key values in it. Run
the program and do the following tasks.
©Debasis Samanta 22
1. Add another element ‘Pine apple’ in the dictionary
2. Delete the element ‘Banana’
3. Delete the element with key value 3
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
©Debasis Samanta 23
Functions Name Description
©Debasis Samanta 24
Methods working with tuple
Method Description
index() Searches the tuple for a specified value and returns the position of where
it was found
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key,
with the specified value
©Debasis Samanta 25
P5: Flow Control in Python
40. Simple if-statement: The syntax for the statement is
If (Condition):
Block 1 #This should be indentation
Block2
Syntax:
if (condition):
Executes this block if condition is true
Execute this block if the condition is false
Consider the following program, which will read two integer values and then print the largest value
print(”\n”)
if (x>y):
print(x, “is the largest”)
print(y, “is the largest”)
print(”\n”)
if (x>y):
print(x, “is the largest”)
else:
print(y, “is the largest”)
42. Consider the following program, which would read any integer number from the user and then print
the digits in word only if it is in between 0 to 5, both inclusive
©Debasis Samanta 26
value = int(input("Please enter an integer in the range 0...5: "))
if value < 0:
print("Too small")
else:
if value == 0:
print("zero")
else:
if value == 1:
print("one")
else:
if value == 2:
print("two")
else:
if value == 3:
print("three")
else:
if value == 4:
print("four")
else:
if value == 5:
print("five")
else:
print("Too large")
print("Done")
43. Check the following listing which is a better program to divide a number by another number.
44. Write a program which will read any integer value (positive or negative) and then print the value only
if it is positive; it will do nothing for a negative value.
©Debasis Samanta 27
45. if-elif-else statement:
If (Condition1):
Block 1 #This should be indentation
elif (Conditin2):
Block2
else:
Block3
Syntax:
if (condition-1):
Executes this block if condition-1 is true
elif (condition-2):
Execute this block if the condition-2 is true
else:
Execute this block
46. Check the program in 45 which have been rewritten with the if-elif-else statement
47. Loop-statement: (while): You can iterate a block of statement. The syntax is
while (Condition):
Block 1 #This should be with indentation
Syntax:
while (condition):
Executes this block
Consider the following program, which will print the sum of first n integer values, that is
©Debasis Samanta 28
Sum = 1 + 2 + 3 + …+n
48. Loop-statement: (for): You can iterate a block of statement. The syntax is
for (Condition):
Block 1 #This should be with indentation
Syntax:
for (condition):
Executes this block
• begin is the first value in the range; if omitted, the default value is 0
• end is one past the last value in the range; the end value is always required and may not be
omitted
• step is the amount to increment or decrement; if the step parameter is omitted, it defaults
to 1 (counts up by ones)
Consider the following program which will show you the looping with for-statement for the same
program as in 51.
sum = 0
n = int(input())
for i in range(n+1): # Condition checking
sum = sum + i
49. The following listing elaborates how you can use for-loop to calculate the following sum
©Debasis Samanta 29
Sum = 1 + 3 + 5 + 7 +. . . upto n-term
sum = 0
n = int(input(“How many terms?”)) #
for i in range(1, 2*n, 2) # Condition checking
sum = sum + i
50. The following listing illustrates a few more task executions with for-statement.
©Debasis Samanta 30
51. For-(or while-) statement with break statement: The break statement can be used to terminate the
execution of a loop. Following are the few examples to illustrate the use of break statement.
#Run a loop to read numbers and quits when a negative value as input
sum = 0
while(True): #This is to loop for arbitrary times
n = int(input(“\nEnter any number (positive or negative): ”))
if (n<0): break
sum = sum + n
print(“Sum = “,sum)
52. For-(or while-) statement with continue statement: The continue statement can be used to bypass
(i.e., skip) some statement inside a loop.
#Run a loop to read numbers and find the sum of all positive numbers
#Quit the loop when it finds 0
sum = 0
count = 0
while(): #This is to loop for arbitrary times
n = int(input(“\n Enter any number (positive or negative): ”))
if (n>0):
sum = sum + n
count +=1
if n == 0: break
print(“\nSum of %d positive numbers is %d“, count, sum)
©Debasis Samanta 31
P6: Functions in Python
Function is a programming paradigm, with which a programmer can define a procedure to solve a problem
and then call the function from the main program or from another function, even the same function (then
it is called recursive function). Function writing supports code debugging, code reusability, code
maintainability, etc.The syntax for defining a function:
Syntax:
def function_name([parameter: data_type]) [-> return_type:]
["""Docstring"""]
# body of the function
[return expression]
The clauses with […] is optional.
53. Following listing illustrates how to define a function and call functions from programs
def my_function():
print("Hello from a function")
function2("Ananya", “Samanta”)
function2("Angelina”, “Fox”)
function2("Maradona", “Diego”)
©Debasis Samanta 32
Continued on ...
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"\n The addition of {num1} and {num2} results {ans}.")
54. You can define many functions at the same time. Following listing illustrates the same.
def sum(a: int, b: int) -> int:
""" This function adds two numbers"""
return (a + b)
# Driver code
a = int(input('Enter 1st number: '))
b = int(input('Enter 2nd number: '))
©Debasis Samanta 33
Continued on ...
# Call with two arguments
var_arg_f("Kareena", "Karishma")
# Driver code
myFun(10) #For this call the default value of y is 50
myFun(15, 25) #For this call the value passed to y is 25
Note: You should always pass the value to non-default argument always
# Function argument if not call with position, it may give wrong result
def nameAge(name, age: int):
print("Hi, I am", name)
print("My age is ", age)
# You will get incorrect output because arguments are not in order
print("\nCase-2:")
nameAge(27, "Suraj")
©Debasis Samanta 34
58. Variable number of arguments passed.
In extension to #60, Python allows to pass a variable number of arguments. For this, define a
function with *argv. Check the following listing.
# Python program to illustrate *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg, end=’ ’)
59. This is the one support when you don’t know how many arguments to be passed while you call a
function and call the function with (key, value) pair(s). Define such a function with **kwargs as
argument. Following is an example illustrating this.
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s=%s" % (key, value))
# Driver code
myFun(roll='CS61061', name='Zebra', marks=98)
myFun(rollNo='CS41043', fname='Lion', lname=' King', marks=86)
myFun(a='A', b='B', c='C', d=86, e='It is a value to key e')
61. Nested function. A function can call other function. Check the following listing to undersand the
concept.
©Debasis Samanta 35
def f1():
print("\n1. I am f1: \n")
def f2():
print("2. I am from f2:\n")
def f23():
print("3. I am inside f2: ")
f1() #fi() is called from here...
# Driver's code
f1()
f2()
62. Recursive function writing: When a function call itself, is called a recursive function. Following
code includes a recursive functions to calculate a) Sum of first n integers and b) factorial of a
positive integer value.
# Driver code
n = int(input( “Enter the value of n :”))
print(f”Sum of first{n} integers is {result}’)
# Driver code
n = int(input( “Enter the value of n :”))
if (n < 0): print(“Invalid entry! Enter positive ineger value:\n”)
else:
print(f”factorial of first{n} integers is {result}’)
Hint: Write the equivalent codes for iterative functions.
For all iterative functions, equivalent recursive functions are possible.
©Debasis Samanta 36
P7: File handling in Python
Concept:
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
63. Following are the small pieces of codes illustrating how the different ways that a file can be handles
and used. You are advised to test each program.
©Debasis Samanta 37
Other ways of file opening
# Alternative Way 1: Using read() method
# Python code to illustrate read() mode
file = open("text.txt", "r")
print (file.read())
file1 = open('test.txt')
for each in file1:
print (each)
©Debasis Samanta 38
Writing some important file handling functions
import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
©Debasis Samanta 39
Python has a set of methods available for the file object.
Method Description
fileno() Returns a number that represents the stream, from the operating system's
perspective
seekable() Returns whether the file allows us to change the file position
---*---
©Debasis Samanta 40