PYTHON PROGRAMMING
Course Outcome ( CO) Bloom’s Knowledge Level (KL)
At the end of course , the student will be able to understand
CO 1 To read and write simple Python programs. K1, K2
CO 2 To develop Python programs with conditionals and loops. K2, K4
CO 3 To define Python functions and to use Python data structures –- lists, tuples, dictionaries K3
CO 4 To do input/output with files in Python K2
CO 5 To do searching ,sorting and merging in Python K2, K4
DETAILED SYLLABUS
Unit I
Introduction: The Programming Cycle for Python , Python IDE, Interacting with Python Programs ,
Elements of Python, Type Conversion.
Basics: Expressions, Assignment Statement, Arithmetic Operators, Operator Precedence, Boolean
Expression.
2 marks important question
Long Answer Question with Answer
Most Frequently Asked Question with Answer
click here
Unit II
Conditionals: Conditional statement in Python (if-else statement, its working and execution),
Nested-if statement and Elif statement in Python, Expression Evaluation & Float Representation.
Loops: Purpose and working of loops , While loop including its working, For Loop , Nested Loops ,
Break and Continue.
2 marks important question
Long Answer Question with Answer
Most Frequently Asked Question with Answer
click here
Unit III
Function: Parts of A Function , Execution of A Function , Keyword and Default Arguments ,Scope Rules.
Strings : Length of the string and perform Concatenation and Repeat operations in it. Indexing and
Slicing of Strings.
Python Data Structure : Tuples , Unpacking Sequences , Lists , Mutable Sequences , List
Comprehension , Sets , Dictionaries
Higher Order Functions: Treat functions as first class Objects , Lambda Expressions
2 marks important question
Long Answer Question with Answer
Most Frequently Asked Question with Answer
click here
Unit IV
Sieve of Eratosthenes: generate prime numbers with the help of an algorithm given by the Greek
Mathematician named Eratosthenes, whose algorithm is known as Sieve of Eratosthenes.
File I/O : File input and output operations in Python Programming
Exceptions and Assertions
Modules : Introduction , Importing Modules ,
Abstract Data Types : Abstract data types and ADT interface in Python Programming.
Classes : Class definition and other operations in the classes , Special Methods ( such as _init_, _str_, comparison methods and Arithmetic methods etc.) , Class Example , Inheritance , Inheritance and OOP.
2 marks important question
Long Answer Question with Answer
Most Frequently Asked Question with Answer
click here
Unit V
Iterators & Recursion: Recursive Fibonacci , Tower Of Hanoi
Search : Simple Search and Estimating Search Time , Binary Search and Estimating Binary Search
Time
Sorting & Merging: Selection Sort , Merge List , Merge Sort , Higher Order Sort
2 marks important question
Long Answer Question with Answer
Most Frequently Asked Question with Answer
click here
Text books:
1. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
2. Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011.
3.John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013
4.Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
5.Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015.
6.Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
7.Charles Dierbach, ―Introduction to Computer Science using Python: A Computational ProblemSolving Focus, Wiley India Edition, 2013.
8.Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013
Python Language Programming Lab (KCS453)
Program 1. To write a python program that takes in command line arguments as input and print the number of arguments.
Solution:
Algorithm
- Start the program.
- Import the sys module to get access to command line arguments.
- Use the len() function to get the number of command line arguments.
- Print the number of command line arguments.
- End the program.
Python code:
import sys
# get the number of command line arguments
num_args = len(sys.argv)
# print the number of command line arguments
print(“The number of command line arguments is:”, num_args)
Explanation:
The above Python code uses the sys module to access command line arguments. The len() function is used to get the number of arguments, which is then printed using the print() function. When you run this program with command line arguments, it will print the number of arguments provided as input.
Program 2. To write a python program to perform Matrix Multiplication.
Solution:
Algorithm for above program
- Start the program.
- Define two matrices A and B as 2D arrays.
- Define a result matrix C as an empty 2D array with dimensions equal to the product of the rows of A and columns of B.
- For each row i in A:
-
- For each column j in B:
- Set the value of the corresponding element in C to the sum of the products of the elements in the i-th row of A and the j-th column of B.
- Print the result matrix C.
- End the program.
Flowchart:
+————————+
| Start the program |
+————————+
|
v
+————————+
| Define matrices A and B |
+————————+
|
v
+————————+
| Define result matrix C |
+————————+
|
v
+————————+
| For each row i in A |
| For each column j |
| in B: |
| Calculate the |
| corresponding |
| element in C |
+————————+
|
v
+————————+
| Print the result matrix |
+————————+
|
v
+————————+
| End the program |
+————————+
Python code:
# define matrices A and B
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[10, 11],
[12, 13],
[14, 15]]
# define result matrix C
C = [[0, 0],
[0, 0],
[0, 0]]
# perform matrix multiplication
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
C[i][j] += A[i][k] * B[k][j]
# print the result matrix
for row in C:
print(row)
Explanation:
The above Python code defines two matrices A and B as 2D arrays and an empty result matrix C with dimensions equal to the product of the rows of A and columns of B. The program then performs matrix multiplication by iterating over each row i in A and each column j in B, calculating the value of the corresponding element in C as the sum of the products of the elements in the i-th row of A and the j-th column of B. Finally, the program prints the result matrix C.
Program 3. To write a python program to compute the GCD of two numbers.
Solution:
Algorithm to compute the GCD of two numbers:
- Take two numbers as input and store them in variables a and b.
- Initialize a variable gcd to 1.
- Loop through all numbers from 1 to the smaller of a and b.
- If the current number divides both a and b, update gcd to the current number.
- After the loop, gcd will contain the GCD of a and b.
- Print gcd as the output.
Python program to compute the GCD of two numbers:
def gcd(a, b):
gcd = 1
for i in range(1, min(a, b)+1):
if a % i == 0 and b % i == 0:
gcd = i
return gcd
# Example usage
a = 24
b = 36
print(“GCD of”, a, “and”, b, “is”, gcd(a, b))
Output:
GCD of 24 and 36 is 12
Program 4. To write a python program to find the most frequent words in a text file.
Solution:
Algorithm to find the most frequent words in a text file:
- Open the text file in read mode and read all the text into a string variable.
- Split the string into words using the split() method and store the result in a list.
- Create a dictionary to store the frequency of each word.
- Loop through the list of words and for each word:
- If the word is not already in the dictionary, add it with a frequency of 1.
- If the word is already in the dictionary, increment its frequency by 1.
- Sort the dictionary by values in descending order to get the most frequent words.
- Print the top n words along with their frequencies, where n is the number of most frequent words to display.
Python program to find the most frequent words in a text file:
def find_most_frequent_words(filename, n=10):
# Open the file and read all the text into a string variable
with open(filename, ‘r’) as file:
text = file.read()
# Split the text into words and create a frequency dictionary
words = text.split()
freq = {}
for word in words:
if word not in freq:
freq[word] = 1
else:
freq[word] += 1
# Sort the dictionary by values in descending order
sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
# Print the top n words and their frequencies
for i in range(n):
print(f”{i+1}. {sorted_freq[i][0]} – {sorted_freq[i][1]}”)
# Example usage
find_most_frequent_words(‘example.txt’, 5)
Note: This program assumes that the text file is a plain text file with words separated by whitespace. If the text file contains punctuation marks or special characters, they may need to be removed or handled separately.
Program 5. To write a python program find the square root of a number (Newton’s method).
Solution:
Python program that implements the Newton’s method to find the square root of a number:
def sqrt(num):
“””Calculate square root of a number using Newton’s method.”””
if num < 0:
raise ValueError(“Cannot calculate square root of a negative number”)
if num == 0:
return 0
x = num
while True:
root = 0.5 * (x + num / x)
if abs(x – root) < 1e-9:
break
x = root
return root
# Example usage
print(sqrt(4)) # Output: 2.0
print(sqrt(2)) # Output: 1.4142135623730951
print(sqrt(0)) # Output: 0
In this program, we define a function sqrt that takes a number num as input and calculates its square root using Newton’s method. The algorithm starts with an initial guess x for the square root, and iteratively refines this guess until it converges to the correct value. The abs(x – root) < 1e-9 condition checks whether the guess x is close enough to the actual square root, and if so, the function returns the final result.
Program 6. To write a python program exponentiation (power of a number).
Solution:
Python program that implements the exponentiation (power of a number):
def power(base, exp):
“””Calculate the result of a number raised to a power.”””
result = 1
for i in range(exp):
result *= base
return result
# Example usage
print(power(2, 3)) # Output: 8
print(power(5, 0)) # Output: 1
print(power(10, -2)) # Output: 0.01
In this program, we define a function power that takes two inputs: the base and the exp (exponent) of the power. The function then uses a loop to multiply the base exp number of times to get the result. If the exponent is zero, the result will always be 1. If the exponent is negative, the function will calculate the reciprocal of the result by using a negative exponent.
Program 7. To write a python program find the maximum of a list of numbers.
Solution:
here is a Python program that finds the maximum of a list of numbers:
def find_max(numbers):
“””Find the maximum value in a list of numbers.”””
if not numbers:
raise ValueError(“Empty list of numbers”)
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
# Example usage
print(find_max([1, 3, 5, 2, 8])) # Output: 8
print(find_max([-1, -3, -5, -2, -8])) # Output: -1
print(find_max([2])) # Output: 2
In this program, we define a function find_max that takes a list of numbers as input and returns the maximum value in the list. The function first checks whether the list is empty, and if so, raises an error. It then initializes a variable max_num to the first number in the list and iterates through the rest of the list. For each number, it compares it to the current maximum and updates max_num if the number is larger. Finally, it returns the maximum value found.
Program 8. To write a python program linear search.
Solution:
here is a Python program that performs linear search:
def linear_search(lst, value):
“””Search for a value in a list using linear search.”””
for i in range(len(lst)):
if lst[i] == value:
return i
return -1
# Example usage
numbers = [3, 5, 1, 2, 4]
print(linear_search(numbers, 2)) # Output: 3
print(linear_search(numbers, 6)) # Output: -1
In this program, we define a function linear_search that takes two inputs: the list lst to be searched and the value to be found in the list. The function then iterates through the list using a for loop and compares each element of the list with the value. If a match is found, the function returns the index of the match. If the value is not found in the list, the function returns -1.
Note that this is a simple and inefficient algorithm for searching in large lists, as it requires iterating through the entire list even if the value is found early. For large lists, more efficient algorithms such as binary search should be used.
Program 9. To write a python program Binary search.
Program 10. To write a python program selection sort.
Program 11. To write a python program Insertion sort.
Program 12. To write a python program merge sort.
Program 13. To write a python program first n prime numbers.
Program 14. To write a python program simulate bouncing ball in Pygame.