0% found this document useful (0 votes)
3 views12 pages

python paper solution

This document outlines an examination paper for a Python Programming course, including various questions on concepts such as variables, functions, object-oriented programming, and algorithms. It provides examples of code implementations for Fibonacci series, abstraction, and exception handling, as well as explanations of key programming principles like Big O notation and recursion. Additionally, it discusses file operations and the Turtle graphics library in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

python paper solution

This document outlines an examination paper for a Python Programming course, including various questions on concepts such as variables, functions, object-oriented programming, and algorithms. It provides examples of code implementations for Fibonacci series, abstraction, and exception handling, as well as explanations of key programming principles like Big O notation and recursion. Additionally, it discusses file operations and the Turtle graphics library in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
Sub Code: (CAT-008) ROLL NO... (ODD SEMESTER EXAMINATION, 2024-25 1 Year (1* Sem) MCA. Python Programming Duration: thes Max Marks 30 Non ct A se a l Tf the same maybe assumed anda the astumptn made nthe ane, or missing data, Qi. | Anniver any two parte of the following ES 8) Explain the concept of variables and types in Python, with examples. b) Wiite « Python program to implement s Fibonacci series, ) What is abstraction in Python functions? Ihustrate with an example how this feature improves code reusability and readability. QZ Answer any two paris of the following aes 8) Explain the differeaces between tuples and lists ia Python, Provide examples of ‘when to use exch, ) Explain the concept of key-value pairs in dictionaries. c) What are global variables in Python? Mhustrate their usage with an example, QS. Atsver any two parte of the following 2) Whats Objet Orsted Progamming? Eeplain inkesines in OOP wih an example 'b) Write @ Python clas to represent a rectangle, Include methods to ealeuate its area and perimeter. ) What ae exceptions in Pytaon? Write a program tat demonstrates the use of try except and finally blacks with a practical example, Qa, Answer any two parts of the following 8) Explain Big O notation with an example, How is it used to analyze the efficiency. of algorithms? ) Compare linear search and binary search in terms of efficiency. Waite a Python program to implement binary sear «) Explain the advantages and disadvantages of recursion compared to iteration. @5, | Answer any two parts ofthe following 8) What are regular expressions in Python? Explain their basic syntax and provide fn example to match all email addresses ina given text. by Deseribe the basic file operations in Python. ) Explain how the Turtle graphics library can be used for drawing in Python. Waite 1 program to draw a simple geometric shape (eg.a square) using Turtle ') Python Program to Implement Fibonacci Series Marke 3 A Flbonacd serles isa sequence in which each number isthe sum of the two preceding ones, starting from @ and code: def fbonaceseres(n: ab=0,1 resuit= for _inrange(: resultappendla) ab=batb return result intinput"Enter the number of terms forthe Fibonacci series") rini(Fibonaccl series, lbonacd_seres(n) Output Example) Enter the number of terms forthe Fbonacclseies:7 Fibonacci series: [0 4,3, 2,3, 5,8] «) Abstraction in Python Functions Marks 3 Abstraction [Abstraction isa programming princinle that involveshing the composty ofan implementation and ‘exposing only the essential features In Python, this can be achieved using functions, lasses, or ‘modules. Abstraction improves code reusability, readability, and maintainability. Baample: 14 Function to caleulate the area ofa rectangle ef calulate_arealenath width: ‘This function abetracts the formula fr ealculating ares." returalength * wieth 1 Function to calelate the perimeter ofa rectangle ef cakulate_perimeter(lenath, wish): "The funetlon abstracts the formula fr ealulating perimeter!" return2* (length + width) 4 Main program length = lostinput"Enter the lenath ofthe rectangle:*)) Width ~foa{input"Eneer the width of the rectangle: ") rint("Area ofthe rectangle: calulate_areallength, with) rint(Perimeter ofthe rectangle: calulate_perimeter(ength, width) Output: Enter the length of the rectangle: Enter the width ofthe rectangle: 2 [Area ofthe rectangle: 15.0 Perimeter ofthe rectangle: 16.0 Answer Marks 15, Variables A variable n Python ia symbolic name that hol a reference to an objet ia memory. Unlike many other programming languages, Python variables are dynamically typed, meaning they can hold object of any dats type and do nat require explicit declaration, Typesin Python 1. Numerie Types: int, oat, complex 2. Sequence Types lit, tuple 3. Mapping Type: cict 4. Set Types: se. rozanset 5. Boolean Type: bool 6. None Type: None Eramples: Marka 5 4 Numerictypes fusttype fruit =["apple", "banana? "cherry" # Dictionary type person = name! ge: 25} ‘*0olean type ‘s happy = True 1 rinsing variable values and types Type", typ=te) name, Type." typelname) b) Python Program to Implement Fibonacci Series Marks 3 ‘AFlbonacc series sa sequence in which each number isthe sum ofthe two preceding ones, starting ‘rom and 1. Code: def fbonacei_series(: 0,1 result=() range(a): resultappend(a) ab=batb return result input: Number of terms itnput("Enter the numberof terms for the Floonaccl series: ")) print( "Fibonacci series, ibonace_ series) Output (Example) Enter the number of terms forthe Fibonacel series: 7 Fibonacel series: [0 1,1,2,3,5, 8] {) Abstraction in Python Functions Marks 3 Abstraction ‘Abstraction isa programming principle that involves hiding the complexity ofan implementation and exposing only the essential features. In Python, this canbe achieved using functions, classes, or ‘modules. Abstraction improves code reusability, readability, and maintainability. Example: |# Function to caleulate the area of a rectangle Sef caleulate_area(length, width): "This function abstracts the formula for calculating area, return length * width 4# Function to calculate the perimeter ofa rectangle Hef calculate_perimeter|length, width): “Tis funetion abstracts the formula for calelatng perimeter return 2* (length + width) |#Main program length = foat{input(“Enter the length ofthe rectangle: ") width= float{input("Enter the width ofthe rectangle: ")} print{"Area ofthe rectangle”, caleulate_area(length, width) print{"Perimeter ofthe rectangle, calelate_perimeterlength, with)) Output: Enter the length of the rectangle: § Enter the width ofthe rectangle: 3 ‘Area of the rectangle: 15.0, Perimeter of the rectangle: 18.0 Answer 4) Diferences between tuple lists in Python: Marks 1.5 ‘Tuples are immutable (cannot be changed ater creation) LUsts are mutable can be mosifid ater creation), Tuples use parentheses: | or no parentheses in some cases Usts use square brackets: ‘Tuples are faster than lists duc to immutabilty Usts are slower as they allow modifications. Use tuples when data should not change e-8 coordinates, days ofthe week). 12 Use lists fr dynamic collections ofitems (eg. userinpits, to-do lis) amples: Marks 15 ple eample coordinates = (10,20) rint(*Coordirates", coordinates) it ama shopping list = ['gpples" "bananas" Yearrots") shoppinglistappend( dates") print(*Shopping lis" shopoing.ist) ») KeyValue Pars in Dictionaries: marke 1.5 + -Adictionary in Python stores data 2s key-value pais + Keys are unique and immutable eg, strings, numbers). 1 Values canbe of any datatype ad are accessed using thelr keys. Bxample: Marks 15 1 Dictionary with key-value pairs student = ('name": "iq age": 25, "rade "A" prini(*Name, tudent(name") # Acces value using key print Age", tudentl'age") ‘Use Case: Dictionaries are ideal for representing structured data (eg, SON objects, configuration seatings) ©) Global Variablesin Python: Marks 15 (Gobi variables are declared outs of functions and can be acessed/mosified inside functions using the global keyword. void excessive use of global variables for maintainable code Example: Marks 1.5 ‘Global variable counter ‘ef increment) slobal counter counter ‘= 1 print(*Counter incremented, counter) ‘nerement() ‘nerement() print(Final Counter", counter), Output: Counter incremented: 1 Counter incremented: 2 Final Counter: 2 Anower3 12) Object-Oriented Programming (OOP): Marks 1.5 (00P i programming paraclam that organizes dats and behavior into objects. Objects are instances of elasses, which define thelr structure and behavior. Key concepts of OO? include encapsulation, abstraction, inheritance, and palymorphism Inheritance in OOF: inheritance allows a class (child to inherit properties and methods from another dass (parent) promotes code reusabilly. Example: Marks 1.5 ‘arent class clase Animal sefspeaklslf ‘return "I make a sound" 4 Child clas inheriting from Animal cass DoalAnimal: ef speak(slf ‘return "Bark!" 1 Using the classes og ~ Dost) print(dog speck) Output Barkt 1) Python class for a rectangle: Marke 3 class Rectangle: ef _int_{self length, width): sefarealse: ‘return selflength*sewidth Set porimeterislf: return 2*(slflength +selfowidth) bxample usage rect= RectanglelS,3) prini(‘Area:’, rect.area()) Output: Area: 15, print( Perimeter, rect.perimetert)) *# Output Perimeter 16 ) Exceptions in Python: Marks 1 Exceptons ae eos that occur during runtime. Python provides mechanisms ke try, excep, and finally to handle exceptions an ensure program continulty Program demonstrating exception handling: Marks 2 ty: 1 Code that may ralse an exception um = intinpuEntera number: ") result= 20 /nur print(Resul, result) except Valuetrror rint"ivala input Please enter a numeric value. cep! ZeroDivisionEror: print(*Dhision by 2er snot alowed.") finally. Print(Execution complete") ample Output: + Inpu:s. Output: Result: 2.0 Execution complete. + Input:0 Output: Division by zero isnot allowed. Execution complete. = Inputzabe Output: Invalid input! Please enter a numeric value. xecutton complete. Answer 4 3) Big 0 Notation: Marks 2 Big O notation is used to describe the upper bound of an algorithm's time or space complexity in ‘terms of Its input size. It provides an asymptotic upper limit for the worst-case scenario, allowing us to analyze the efficiency of algorithms. ‘Common Big O complexities include: = O(1):Constant time O(n): Linear time * O(n42): Quadratictime = Oflogn): Logarithmic time Example of Big O: Marks 1 Consider the following algorithm to find the sum of elements ina list: def sum_elements(st): total for nur in ist: total += num return total ‘© The loop runs once for each element, so the time complexity is O(n), where n isthe size of the list, ‘+ The algorithm's efficiency depends on how the time grows with the input size. b) Linear Search vs Binary Search: Marks 2 + Unear Search: © Time Complexity: O(0) © Searches through each element one by one. © Efficient for small or unsorted lists, + Binary Search: © Time Complexity: O(log n) © Requires the lst ro be sorted. Efficient for large sorted lists since it repeatedly divides the search space in half. Python implementation of Binary Search: Marks 1 def binary_search(arr, target) while low mid = (low + igh) //2 if ar{mid] = target return mid eli arr{mid) readlines(): Reads all lines as. list. + Writing toa file © write(): Waites a string to the fle. © writelines(}: Writes a list of strings. + Closing file: close() ensures that any changes are saved and resources are released. Example: Marks 1.5 # Writing toa fle with open(‘examplet w/a file: fileswrite(*Hello,thisis a test file") 4 Reading from the fle with open(‘example-tt, '?) as file: content = fileread() print(content) # Output: Hello, tisisa test file, ‘The with statement automatically handles closing the file. {c) Turtle Graphics in Python: Marks 1.5, The Turtle graphics llbrary allows you to draw pictures and shapes using a virtual "turtle" that moves

You might also like