UNIVERSITY OF NORTH BENGAL
B.Sc. Honours 3rd Semester Examination, 2021
SEC1-P1 - COMPUTER SCIENCE
SEC35-E3
PYTHON PROGRAMMING
GROUP-A
1. What are operators in Python? Give examples.
In Python, operators are special symbols that are used to perform operations on operands. Operands are the values or variables on which the operations are performed. Python supports various types of operators.
Here are examples of some commonly used operators in Python:
- Arithmetic Operators: '+', '-', '*', '/', '//', '%', '**'.
- Comparison Operators: '==', '!=', '>', '<', '>=', '<='.
- Logical Operators: 'and', 'or', 'not'.
- Assignment Operators: '=', '+=', '-='.
2. Explain identifiers in Python.
In Python, an identifier is a name given to entities such as variables, functions, classes, modules, or other objects. Identifiers are used to uniquely identify these entities within a program.
Here are some rules and guidelines regarding identifiers in Python:
- Must start with a letter or underscore, can not start with a digit.
- Can include letters, underscores, and digits.
- Case-sensitive.
- Reserved words (e.g., if, else) cannot be used.
# Valid identifiersmy_variable = 10total_score = 95calculate_area = lambda r: 3.14 * r**2MyClass = type('MyClass', (), {})# Invalid identifiers2count = 5 # Invalid: starts with a digitmy-var = "Hello" # Invalid: contains a hyphenif = 10 # Invalid: using a reserved word (code-box)
3. Discuss tuples with the help of examples.
A tuple in Python is an immutable, ordered collection of elements. Once a tuple is created, we cannot modify its contents - add, remove, or change elements. Tuples are defined using parentheses '()' and can contain elements of different data types.
Here's an example:
# Creating a tuple
my_tuple = (1, 2, 3, 'apple', 'banana')
# Accessing elements
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: apple
# Attempting to modify a tuple raises an error
my_tuple[0] = 10 # Error: 'tuple' object does not support item assignment (code-box)
4. Discuss bitwise operators in Python with the help of an example.
Bitwise operators in Python perform operations on the individual bits of binary representations of integers. These operators are often used in low-level programming and tasks where individual bits need to be manipulated.
Here are the bitwise operators in Python:
- Bitwise AND (&): Sets each bit to 1 if both bits are 1.
- Bitwise OR (|): Sets each bit to 1 if at least one bit is 1.
- Bitwise XOR (^): Sets each bit to 1 if only one of the bits is 1.
- Bitwise NOT (~): Inverts the bits, changing 1s to 0s and vice versa.
- Left Shift (<<): Shifts the bits to the left by a specified number of positions, filling in with zeros.
- Right Shift (>>): Shifts the bits to the right by a specified number of positions, filling in with the sign bit for signed integers.
# Example valuesa = 10 # binary: 1010b = 5 # binary: 0101# Bitwise ANDresult_and = a & b # binary: 0000print("Bitwise AND:", result_and) # Output: 0# Bitwise ORresult_or = a | b # binary: 1111print("Bitwise OR:", result_or) # Output: 15# Bitwise XORresult_xor = a ^ b # binary: 1111print("Bitwise XOR:", result_xor) # Output: 15# Bitwise NOTresult_not_a = ~a # binary: -1011 (Two's complement representation)print("Bitwise NOT (a):", result_not_a) # Output: -11# Left Shiftresult_left_shift = a << 1 # binary: 10100print("Left Shift (a):", result_left_shift) # Output: 20# Right Shiftresult_right_shift = a >> 1 # binary: 0101print("Right Shift (a):", result_right_shift) # Output: 5 (code-box)
5. Discuss expressions in Python.
In Python, an expression is a combination of values, variables, operators, and function calls that, when evaluated, produces a result. Expressions can be simple or complex, and they are the building blocks of Python programs.
# Arithmetic expressionresult = 5 + 3 * (2 - 1)# String concatenation expressiongreeting = "Hello" + " " + "World"# Comparison expressionis_greater = 10 > 5# Function call expressionlength = len("Python") (code-box)
6. Discuss debugging in Python.
Debugging is the process of finding and fixing errors (bugs) in the code. Python provides several tools and techniques for debugging to help programmers identify and resolve issues in the programs.
Here are some key aspects of debugging in Python:
Print Statements: One of the simplest and most commonly used debugging techniques is inserting print statements in the code to output variable values and intermediate results.
Using pdb (Python Debugger): Python has a built-in debugger module called pdb. We can insert pdb statements in our code or run our script with the -m pdb option to start the debugger.
IDE Debugging Tools: Integrated Development Environments (IDEs) like PyCharm, VSCode, and others offer sophisticated debugging tools. These tools allow us to set breakpoints, inspect variables, and step through the code line by line.
GROUP-B
7. Explain different data types available in Python with the help of examples.
Python supports several built-in data types that allow us to represent and manipulate different kinds of data. Here are some of the commonly used data types in Python, along with examples:
- int: Integer type represents whole numbers.
x = 5 (code-box)
- float: Float type represents floating-point numbers (decimal numbers).
y = 3.14 (code-box)
- complex: Complex type represents complex numbers.
z = 2 + 3j (code-box)
- str: String type represents sequences of characters enclosed in single or double quotes.
message = 'Hello, Python!' (code-box)
- list: List type represents ordered, mutable sequences of elements.
numbers = [1, 2, 3, 4, 5] (code-box)
- tuple: Tuple type represents ordered, immutable sequences of elements.
coordinates = (3, 4) (code-box)
- set: Set type represents an unordered collection of unique elements.
unique_numbers = {1, 2, 3, 4, 5} (code-box)
- dict: Dictionary type represents key-value pairs.
person = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'} (code-box)
8. Write a Python program to find the GCD of two numbers.
def GCD_Loop( a, b):if a > b: # define the if conditiontemp = belse:temp = afor i in range(1, temp + 1):if (( a % i == 0) and (b % i == 0 )):gcd = ireturn gcdx = int(input (" Enter the first number: ") ) # take first no.y =int (input (" Enter the second number: ")) # take second no.num = GCD_Loop(x, y) # call the gcd_fun() to find the resultprint("GCD of two number is: ")print(num) # call num (code-box)
Output:
c:\Users\ErAgOn\Python\gcdFile.pyEnter the first number: 60Enter the second number: 48GCD of two number is:12 (code-box)
9. Write a Python program to check if a string is palindrome or not.
Python Program to Check if a String is Palindrome or Not Using Native Approach:
Here we will find the reverse of the string and then Check if the reverse and original are the same or not.
# function which return reverse of a stringdef isPalindrome(s):return s == s[::-1]# Driver codes = "malayalam"ans = isPalindrome(s)if ans:print("Yes")else:print("No") (code-box)
Check if a String is Palindrome or Not Using Iterative Method:
Run a loop from starting to length/2 and check the first character to the last character of the string and second to second last one and so on …. If any character mismatches, the string wouldn’t be a palindrome.
# function to check string is# palindrome or notdef isPalindrome(str):# Run loop from 0 to len/2for i in range(0, int(len(str)/2)):if str[i] != str[len(str)-i-1]:return Falsereturn True# main functions = "malayalam"ans = isPalindrome(s)if (ans):print("Yes")else:print("No") (code-box)
10. Write a Python program to add two matrix and find the transpose.
def add_matrices(matrix1, matrix2):result_matrix = []for i in range(len(matrix1)):row = []for j in range(len(matrix1[0])):row.append(matrix1[i][j] + matrix2[i][j])result_matrix.append(row)return result_matrixdef transpose_matrix(matrix):# Using zip to transpose the matrixtransposed_matrix = [list(row) for row in zip(*matrix)]return transposed_matrix# Input matricesmatrix1 = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]matrix2 = [[9, 8, 7],[6, 5, 4],[3, 2, 1]]# Adding matricesresult_sum_matrix = add_matrices(matrix1, matrix2)# Finding the transpose of the sum matrixresult_transpose_matrix = transpose_matrix(result_sum_matrix)# Displaying the matrices and their sumprint("Matrix 1:")for row in matrix1:print(row)print("\nMatrix 2:")for row in matrix2:print(row)print("\nSum of Matrices:")for row in result_sum_matrix:print(row)print("\nTranspose of the Sum Matrix:")for row in result_transpose_matrix:print(row) (code-box)
Output:
Matrix 1:[1, 2, 3][4, 5, 6][7, 8, 9]Matrix 2:[9, 8, 7][6, 5, 4][3, 2, 1]Sum of Matrices:[10, 10, 10][10, 10, 10][10, 10, 10]Transpose of the Sum Matrix:[10, 10, 10][10, 10, 10][10, 10, 10] (code-box)
11. Write a Python program to check if the given number is Prime or Not.
# Program to check if a number is prime or not# To take input from the usernum = int(input("Enter a number: "))# define a flag variableflag = Falseif num == 1:print(num, "is not a prime number")elif num > 1:# check for factorsfor i in range(2, num):if (num % i) == 0:# if factor is found, set flag to Trueflag = True# break out of loopbreak# check if flag is Trueif flag:print(num, "is not a prime number")else:print(num, "is a prime number") (code-box)
Output:
Enter a number: 2929 is a prime number (code-box)
12. Write a Python program to check whether a given number is Armstrong or not.
# take input from the usernum = int(input("Enter a number: "))# Changed num variable to string,# and calculated the length (number of digits)order = len(str(num))# initialize sumsum = 0# find the sum of the cube of each digittemp = numwhile temp > 0:digit = temp % 10sum += digit ** ordertemp //= 10# display the resultif num == sum:print(num,"is an Armstrong number")else:print(num,"is not an Armstrong number") (code-box)
Output 1:
Enter a number: 663663 is not an Armstrong number (code-box)
Output 2:
Enter a number: 407407 is an Armstrong number (code-box)
GROUP-C
13. Explain arrays in Python. Write a program in Python to demonstrate the
implementation of arrays.
In Python, arrays are not built into the core language like in other programming languages. Instead, Python provides a powerful and flexible built-in data type called a list, which can be used to create arrays and perform array-like operations. Lists in Python can contain elements of different data types that are mutable, meaning you can change their size and modify elements.
Here's a program demonstrating the implementation of arrays using lists in Python:
# Creating an array (list) of integersinteger_array = [1, 2, 3, 4, 5]# Creating an array (list) of stringsstring_array = ["apple", "banana", "orange", "grape"]# Accessing elements of the arraysprint("Integer Array:", integer_array)print("Element at index 2:", integer_array[2])print("\nString Array:", string_array)print("Element at index 1:", string_array[1])# Modifying elements of the arraysinteger_array[3] = 8string_array[0] = "cherry"# Adding elements to the arraysinteger_array.append(6)string_array.insert(2, "kiwi")# Removing elements from the arraysinteger_array.pop(1)string_array.remove("banana")# Displaying the modified arraysprint("\nModified Integer Array:", integer_array)print("Modified String Array:", string_array) (code-box)
Output:
Integer Array: [1, 2, 3, 4, 5]
Element at index 2: 3
String Array: ['apple', 'banana', 'orange', 'grape']Element at index 1: banana
Modified Integer Array: [1, 3, 8, 5, 6]
Modified String Array: ['cherry', 'kiwi', 'orange', 'grape'] (code-box)
14. Write a program in Python to calculate total marks, percentage and grade of a student. Marks obtained in each of the three subjects are to be input by the user.
Assign grades according to the following criteria.
(a) Grade A: Percentage > = 80
(b) Grade B: Percentage > = 70 and < 80
(c) Grade C: Percentage > = 60 and < 70
(d) Grade D: Percentage > 40 and < 60
(e) Grade E: Percentage < 40
# Input marks from the usersubject1 = float(input("Enter marks for Subject 1: "))subject2 = float(input("Enter marks for Subject 2: "))subject3 = float(input("Enter marks for Subject 3: "))# Calculate total marks and percentagetotal_marks = subject1 + subject2 + subject3percentage = (total_marks / 300) * 100# Assign grades based on percentageif percentage >= 80:grade = 'A'elif 70 <= percentage < 80:grade = 'B'elif 60 <= percentage < 70:grade = 'C'elif 40 <= percentage < 60:grade = 'D'else:grade = 'E'# Display resultsprint("\n----- Results -----")print("Total Marks:", total_marks)print("Percentage:", percentage, "%")print("Grade:", grade) (code-box)
Output:
Enter marks for Subject 1: 98Enter marks for Subject 2: 99Enter marks for Subject 3: 96----- Results -----Total Marks: 293.0Percentage: 97.66666666666667 %Grade: A (code-box)
15. Explain loops in Python with the help of examples.
Loops in Python are used to repeatedly execute a block of code until a certain condition is met. Python supports two main types of loops: 'for' loop and 'while' loop.
'for' Loop: The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects.
#Iterating over a Listfruits = ["apple", "banana", "cherry"]for fruit in fruits:print(fruit) (code-box)
Output:
applebananacherry (code-box)
#Using range() for Numerical Rangefor i in range(5):print(i) (code-box)
Output:
01234 (code-box)
'while' Loop: The while loop continues to execute a block of code as long as a specified condition is True.
count = 1while count <= 5:print(count)count += 1 (code-box)
Output:
12345 (code-box)
Loop Control Statements: Python provides loop control statements that allow us to modify the execution of a loop. The key control statements are break and continue.
Example: Using 'break' to Exit the Loop
fruits = ["apple", "banana", "cherry"]for fruit in fruits:if fruit == "banana":breakprint(fruit) (code-box)
Output:
apple (code-box)
In this example, the loop is terminated when the value of 'fruit' becomes "banana."
Example: Using 'continue' to Skip Iteration
fruits = ["apple", "banana", "cherry"]for fruit in fruits:if fruit == "banana":continueprint(fruit) (code-box)
Output:
applecherry (code-box)
In this example, the loop skips the iteration when the value of 'fruit' is "banana."
16. Write a program in Python to generate Fibonacci series up to n-terms.
# Program to display the Fibonacci sequence up to n-th termnterms = int(input("How many terms? "))# first two termsn1, n2 = 0, 1count = 0# check if the number of terms is validif nterms <= 0:print("Please enter a positive integer")# if there is only one term, return n1elif nterms == 1:print("Fibonacci sequence upto",nterms,":")print(n1)# generate fibonacci sequenceelse:print("Fibonacci sequence:")while count < nterms:print(n1)nth = n1 + n2# update valuesn1 = n2n2 = nthcount += 1 (code-box)
Output:
How many terms? 7Fibonacci sequence:0112358 (code-box)
.jpg)