0% found this document useful (0 votes)
4 views

Python - 10 Marks Sol. of Previous PUT_Bharat_Agg

The document provides an overview of Python programming, covering its features, history, data types, and operators. It highlights Python's ease of learning, interpreted nature, and extensive libraries, along with a brief historical timeline from its inception in the 1980s to the present. Additionally, it details various operators (arithmetic, comparison, logical, etc.) and data types (numbers, strings, lists, tuples, dictionaries, sets, and booleans) with examples for each.

Uploaded by

adityadhankar9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views

Python - 10 Marks Sol. of Previous PUT_Bharat_Agg

The document provides an overview of Python programming, covering its features, history, data types, and operators. It highlights Python's ease of learning, interpreted nature, and extensive libraries, along with a brief historical timeline from its inception in the 1980s to the present. Additionally, it details various operators (arithmetic, comparison, logical, etc.) and data types (numbers, strings, lists, tuples, dictionaries, sets, and booleans) with examples for each.

Uploaded by

adityadhankar9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 43
Section —C #50 Marks (Medi um/ Long Answer Type Questions ~ Lang Answer Type ( Attempt ALL the questions. Each Que: stion. E; features & History all the basie Operators i ¢. Explain all the data types in pyt as A ttre ou eons stion is of 10 marks. ‘ach question is of 10 marks of Python explain in detail, in python wit 2.7 (CO-1): Attempt any ONE qu a. What are the >. Explain ith suitable example. hon with suitable example. OR (CC a Q.7 (CO-1): Lee rl M Col mel me eld ere Rel ee 1. Easy to Learn and Use: Python has a simple syntax, making it easy to learn for beginners. 2. Interpreted Language: Python code is executed line by line, making debugging easier. 3. Dynamically Typed: Python doesn't require variable declarations, and types are determined at runtime. 4. Platform Independent: Python is portable and can run on different platforms like Windows, macOS, and Linux. 5. Open Source: Python is free to use and distribute. 6. Extensive Libraries: Python has a large standard library and many third-party libraries for different applications. 7. Object-Oriented: Python supports object-oriented programming concepts like classes and objects. 8. High-Level Language: Python abstracts low-level details, making it easier to write and maintain. 9. Support for Multiple Paradigms: Python supports procedural, object-oriented, and functional programming. @_ History of Python (in brief points): im 1980s - Early Development: Python was conceived in the late 1980s by Guido van Rossum as a successor to the ABC programming language. . 1991 - First Release: Python's first version, Python 0.9.0, was released with features like exception handling and core data types. See Cel a Modded] 1th el aCe) 1.0, which introduced functional programming tools like map(), filter(), and lambda(). . 2000 - Python 2.0: Introduced new features like garbage collection and list comprehensions but had design inconsistencies. . 2008 - Python 3.0: A major update with significant improvements, such as better Unicode support and cleaner syntax. It was not backward compatible PUR Aen . Present: Python 3 is the standard for development, with Python 2 officially retired in 2020. Qs \Solution Explain the different types of operators in Python, providing examples of each and | CO1 their specific use cases Python includes several types of operators, which are essential for performing operations on variables and values. The main categories of operators in Python are: © Arithmetic Operators: These operators are used for basic mathematical operations like addition, subtraction, multiplication, etc © + (Addition): Adds two numbers, © - (Subtraction): Subtracts the second number from the first. © * (Multiplication): Multiplies two numbers © / (Division): Divides the first number by the second, always returning a float. © // (Floor Division): Divides the first number by the second and returns the quotient as an integer, discarding the remainder. © % (Modulus): Returns the remainder when the first number is divided by the second. © ** (Exponentiation): Raises the first number to the power of the second Example: y print(x + y) # Output: 7 print(x - y) # Output: 3 print(x * y) # Output: 10 prini(x / y) # Output: 2.5 prini(x // y) # Output: 2 print(x% y) # Output: 1 print(x ** y) # Output: 25 © Comparison Operators: These operators are used to compare two values They return a Boolean value (True or False) ° ° ° ° ° ° Checks if two values are equal. Checks if two values are not equal >: Checks if the left value is greater than the right. < Checks if the left value is less than the right. >=: Checks if the left value is greater than or equal to the right. <=: Checks if the left value is less than or equal to the right. print(a print(a > b) # Output: False ‘© Logical Operators: These operators are used to perform logical operations, typically between Boolean values. © and: Returns True if both operands are True. © or: Retums True if at least one operand is True. ‘© not: Reverses the Boolean value of the operand. Example: rue y= False print(x and y) # Output: False print(x ory) # Output: True print{not x) # Output: False ‘© Assignment Operators: These operators are used to assign values to variables, ‘© =: Simple assignment. © +=: Adds the right operand to the left operand and assigns the result to the left operand. © ==: Subtracts the right operand from the left operand and assigns the result to the left operand. ‘©. =: Multiplies the left operand by the right operand and assigns the result to the left operand. © /5,/!=, %=: Performs division, floor division, and modulus operations, respectively, and assigns the result to the left operand. ‘© **=: Performs exponentiation and assigns the result to the left operand. Example: x=10 x4=5 #x becomes 15 x*=2 #x becomes 30 ‘© Bitwise Operators: These operators are used to perform bit-level operations on integers. © = &: Bitwise AND. ©. |: Bitwise OR. © *: Bitwise XOR. © ~: Bitwise NOT (inverts the bits) ° ° Left shift (shifts bits to the left) >>: Right shift (shifts bits to the right) Example: #0101 in binary y=3 #0011 in binary print(x & y) # Output: 1 (0001 in binary) print(x | y) # Output: 7 (0111 in binary) print(x* y) # Output: 6 (0110 in binary) ‘* Membership Operators: These operators are used to check if'a value exists within an iterable, such as a list or a string, ©. in: Returns True if the value is found in the iterable. © not in: Retumns True if the value is not found in the iterable. Example: fruits = ["apple”, "banana", "“cherry") print(”apple” in fruits) # Output: True print("grape” not in fruits) # Output: True ‘Identity Operators: These operators are used to compare the memory locations of two objects. is: Returns True if both operands refer to the same object. ©. isnot: Returns True if both operands do not refer to the same object. print(a is b) # Output: False Python Data Types: Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instances (object) of these classes. The following is a list of the Python-defined data types. 1, Numbers 2. Sequence Type 3. Boolean 4. Set 5. Dictionary re i Numbers Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with a Python Numbers datatype. Python offers the type() function to determine a variable's data type. The instance () capability is utilized to check whether an item has a place with a specific class. When a number is assigned to a variable, Python generates Number objects. For instance, a=5 . print("The type of a", type(a)) b=40.5 . print("The type of b", type(b)) c= 143) . print("The type of c", type(c)) 9. print(” cis a complex number", isinstance(1+3),complex)) Output: The type of a The type of b The type of c c¢ is complex number: True Python supports three kinds of numerical data. Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An integer can be any length you want in Python. Its worth has a place with int. Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within 15 decimal places. Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3), ete. Sequence Type String The sequence of characters in the quotation marks can be used to describe the string. A string can be defined in Python using single, double, or triple quotes. String dealing with Python is a direct undertaking since Python gives worked-in capabilities and administrators to perform tasks in the string. When dealing with strings, the operation “hello"+" python" returns “hello python," and the operator + is used to combine two strings. Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator. The Python string is demonstrated in the following example. Example - 1 1. str= "string using double quotes" wRen AUwAwn- . print(str) .s=""A multiline . string’ . print(s) Output: string using double quotes A multiline string Look at the following illustration of string handling, Example - 2 « strl = ‘hello world’ #string str] str2 =" how are you' #éstring str2 . print (strl[0:2]) #printing first two character using slice operator . print (str1[4]) #printing 4th character of the string . print (strl*2) éprinting the string twice . print (strl + str2) #printing the concatenation of str! and str2 Output: he oO hello worldhello world hello world how are you List Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in the rundown are isolated with a comma (,) and encased inside square sections []. To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list is handled by the concatenation operator (+) and the repetition operator (*). Look at the following example. Example: 1. list! =[1, "hi", "Python", 2] 2, #Checking type of given list 3, print(type(list!)) 4, 5. #Printing the list] 6. print (listl) 7 8. # List slicing 9. print (listl[3:]) 10. I. # List slicing 12. print (list1[0:2)) 13. 14. # List Concatenation using + operator 15. print (listl + listl) 16, 17, # List repetation using * operator 18. print (listl * 3) Output: [1, ‘hi’, ‘Python’, 2] (2) 1, ‘hi'] [1, ‘hi’, Python’, 2, 1, ‘hi’, Python’, 2 [1, ‘hi’, Python’, 2, 1, ‘hi’, ‘Python’, 2, 1, ‘hi’, ‘Python’, 2] Tuple In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data types. A parenthetical space () separates the tuple's components from one another. Because we cannot alter the size or value of the items in a tuple, it is a read- only data structure. Let's look at a straightforward tuple in action. Example: 1. tup =("hi", "Python", 2) 2. # Checking type of tup 3. print (type(tup)) 4, 5. #Printing the tuple 6. print (tup) 7 8. # Tuple slicing 9. print (tup[1:]) 10. print (tup[0:1]) 12. # Tuple concatenation using + operator 13. print (tup + tup) 14, 15. # Tuple repatation using * operator 16. print (tup * 3) 17. 18. # Adding value to tup. It will throw an error. 19. tf2]= Output: (‘hi’, Python’, 2) (‘Python'’, 2) Chi',) ‘hi’, ‘Python’, 2, ‘hi’, ‘Python’, 2) (hi, Python’, 2, 'hi', ‘Python’, 2, 'hi', Python’, 2) Traceback (most recent call last): File "main.py", line 14, in t(2] = "hi"; TypeError: 'tuple' object does not support item assignment Dictionary A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an associative array or a hash table. Value is any Python object, while the key can hold any primitive data type. The comma (,) and the curly braces are used to separate the items in the dictionary. Look at the following example. . d= {L:Jimmy’, 2:'Alex', 3:john’, 4:'mike’} . # Printing dictionary }. print (d) , # Accesing value using keys . print("Ist name is "+d[1]) . print("2nd name is "+ d[4]) = eCmIAWEYN= 0. print (d.keys()) IL. print (d.values()) Output: Ist name is Jimmy 2nd name is mike {1: Jimmy’, 2: 'Alex’, 3: john’, 4: 'mike'} dict_keys({1, 2,3, 4)) dict_values({'Jimmy’, ‘Alex’, john’, ‘mike')) Boolean True and False are the two default values for the Boolean type. These qualities are utilized to decide the given assertion valid or misleading. The class book indicates this. False can be represented by the 0 or the letter "F," while true can be represented by any value that is not zero. Look at the following example. . # Python program to check the boolean type . print(type(True)) . print(type(False)) . print(false) RENE Output: NameError: name ‘false’ is not defined Set The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and has remarkable components. The elements of a set have no set order; It might return the element's altered sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to create the set or the built-in function set() is used to create the set. It can contain different kinds of values. Look at the following example. . # Creating Empty set . set = set() set2 = {‘James', 2, 3,'Python'} . #Printing Set value . print(set2) . # Adding element to the set set2.add(10) print(set2) #Removing element from the set set2.remove(2) print(set2) Output: {3, ‘Python’, James’, 2} {'Python', ‘James’, 3, 2, 10} {'Python’, ‘James’, 3, 10} tes Q.8 (CO-2) : Attempt any a. What is anonyrr ~b. What “Ha types in python with suitable example. ONE question, Each question is of 10 marks, nous function? How it is created with an example. 's Control Flow Statements and L ea Python Program to Multiply Two Matri Q.9 (CO-3) Attempt any ONE question. 0.8 (CO-2) meee ml irae nme acl | PLC lu ok CEU ue RU Ri Lael Ce BUTS CCT oR role Lee M Ln OAC CeCe Cote eR La defined using the def keyword, anonymous functions are created using the lambda keyword. Because they do not have a name, they are commonly referred to as lambda Ute eT nl eM eee MO] Cel AUS CR Comoe Ra) (I eye um Ue molar Ce Rl miele melt tel They are designed to be concise and are often used in scenarios where a small function is needed temporarily, STURM Ie cn Raunt a Reo higher-order functions like map(), filter(), and reduce(). Key Characteristics of Lambda Functions: 1, Anonymous: Lambda functions do not have a name, which means they are used as temporary functions for quick, one-off tasks. PASO er ee Rll eae LMT eh eld eT TTR ACLU Rie Met em OL Lcd regular functions, it cannot contain multiple expressions CS Clue 3. Multiple Arguments: Lambda functions can take multiple arguments, just like regular functions. However, they can only perform a single operation and return a single result. Se Eat Se ae ec es ood ores Se eee SRO ee Lad er See Cee eee Seto ooo enn) ro Ce ea oad Lambda functions are typically assigned to a variable or Se ea OL eco ood rd reer aoc ea Sa Ce eee See ees + The function is called withthe arguments 3 and 5, Cee Example 2: Lambda Function for Squaring a Number: od cony code Bente ieee core Se ee aes See ents ee ee? eee een ed Pee eee eet eee te tt earn eerie ete) ree oo eo es See ery +The ap() function applies the lambda function to each on prerrsresy omen roo al ca eee eee ee eed ee ce eed Cen ee eeeeter eee perenne cy oon oe ree Se eee eee ed peer eee eee ery CO enone Ceres Cee eee cry eee error eeg ee ey Stet ree enna ee eT CO eed aetna nena 2.1 Control flow statements in Python First and foremost, Control flow statements in Python are how you direct your programs to decide which parts of code to run, By default, programs execute each line of code in sequence, with understanding how things are proceeding. What if you don't want to execute every single line of code? What if you have several answers, and the code must choose which one to utilize based on the conditions? What if you require the software to continually utilize the same code to perform the computations with slightly different inputs? What if you want to execute a few lines of code repeatedly until the application fulfils a condition? It is when control flow enters the picture. Control flow statements in Python direct the flow of your program's execution. It allows you to make decisions, repeat actions, and handle different situations to make your code more dynamic and adaptable. 2.2 Conditional Statements in Python Conditional statements in Python are used to make decisions and execute different blocks of code based on specif conditions. These conditions are defined using logical expressions that evaluate either True or False. Conditional statements in Python control the flow of your program and enable it to respond dynamically to different situations, 2.2.1 if Statement: ‘The if statement is the most fundamental conditional statement in Python. It allows you to execute a block of code only if a specified condition is true, If the condition evaluates to True, the code block is executed. The if statement is used to execute a block of code only if a certain condition is true. # Example of the if statement x=10 ifx>s print("x is greater than 5") Output: x is greater than 5 2.2.2 if else Statement: The else statement is used to execute a block of code if the condition specified in the if statement is false 4# Example of the if-else statement y=3 ity>s print("y is greater than 5") else: print("y is not greater than 5") Output: y is not greater than 5 2.2.3 elif Statement: ‘The elif (else if) statement is used when there are multiple conditions to check. It allows you ta check additional conditions if the previous ones are false. # Example of the if-elif-else statement elifz <0: print("z is negative”) else: print("zis zero") Output: z is zero 2.3 Loops in Python Iterative control statements in Python allow you to execute a block of code repeatedly. They perform repetitive tasks, iterate over data structures, and handle various scenarios where actions need to be repeated. Python has two main types of loops: © The for loop © The while loop 2.3.1 The for Loop The for loop iterates over a sequence (such as a list, tuple, string. or range) or any other iterable object. It executes ablock of code for each element in the sequence to perform actions on each element. Example 1: Using for Loop with a List Code fruits = ["apple, for fruit in fruits: print(f"I love (fruit}s.") Output: code love apples. Tlove bananas. Ilove cherries. In this example, the for loop iterates through the fruits list. and for each fruit, it executes the code block inside theloop. This results in the message "I love [fruit]s.” being printed for each item in the list. Example 2: Using for Loop with a String code word = "Python" for letters in words: print(letter) Output: zoey Here, the for loop iterates through the characters of the string "Python" and prints cach character on a separate line. Example 3: Using for Loop with Range code fori in range(1, 6): print(f” The Square of (i) is (i**2).") Output: ‘The square of 1 is 1 The square of 2 is 4. ‘The square of 3 is 9. The square of 4 is 16. The square of 5 is 25. This example uses the range() function to generate a sequence of numbers from 1 to 5 (inclusive), The for loop theniterates through this sequence, calculating and printing the square of each number. 2.3.2 The while Loop The while loop in Python repeatedly executes a block of code as long as a specified condition remains true. It isuseful when you need to repeat an action until a certain condition is met. Example 1: Basic while LoopCode count = while count <= 5 print(f’The Count is (count}.”) count+ = 1 Output: code The count is 1. The count is 2 The count is 3, The count is 4. ‘The count is 5. In this example, the while loop continues to run as long as the condition (count <= 5) remains true. Example 2: Using while Loop for User Input Gde password = "secret" user_input = input("Enter the password: ) while user_input != password print("Incorreet password. Try again.") uuser_input = input("Enter the password: ") print("A Output (assuming incorrect password inputs before entering "secret"): Enter the password: incorrect Incorrect password. Try again, Enter the password: wrong pass Incorrect password. Try again. Enter the password: secret Access granted, This example uses a while loop to repeatedly prompt the user for a password until they enter the correct password("secret”). Example 3: Using While Loop with a Counter Qe counter = 0 while counter < 3: print("Processing item (counter}") counter+ = 1 Output: Processing item 1 Processing it Processing item 3 Here, the while loop is used to process items in a task. The loop continues until the counter reaches 3, at whichpoint it stops. Q.8 (CO-2) mE eRe M UC ham ReMi Ulett) Pare mL em iol (Cel uray foc od rows_A = int(input("Enter the number of rows for crliet a CD cols_A = int(input("Enter the number of columns for Cryst a CD rows_B = int(input("Enter the number of rows for matrix B: ")) cols_B = int(input("Enter the number of columns for hae a: Fed) chat Oe) es print("Matrix multiplication is not possible.") Pee Pies Gah ee ee a | meer Cr eon row = list(map(int, input().split())) OE lea) print("Enter the elements of matrix B:") B= IE ener Grae row = list(map(int, input().split())) B.append(row) result = [[0 for _ in range(cols_B)] for _ in il tee ee aeRO Gr eee ep U TC ea) E ae OMCs Ce Ucses ep Meccer vest sma SI6p ULC oes Ue ast aet Om Une print(* '.join(map(str, row))) BLY two Vlatrices without using built in function, 9 (CO-3) - Attempt any ONE question. Each question is of 10 Meare, clan doch, Mra ~a. Explain the Different types of arguments used in functions, “= b. Describe the syntax for the following functions and explain with an example. 3) abs() b) maxG) ) divmod() d) pow()e) len() ¢. Compare list and dictionary data structure. Explain various dictionary methods with suitable examples. Yintrr az Q.9 (CO-3) Eee Ue mh ee ee meen) te tell In Python, functions can accept arguments, which are WER OR el eC eRe eC CCU Cea CCR UCaccUn CRC CRUE tet es Dee as See eC Cee Rc value if a value is not provided by the caller. Se ne Ree ae rao TRU Reem ee Pe oe ot fener CeCe ease) Petcare seer) Pe aTeLeE Cas etc # Output: Hello, Alice # Output: Hi, Bob ee Cuter on SETS MEM RO CSS RCC cag reece © This can be achieved using *args, where args isa UCU eee reece a cs) RUT RO Te ola PC oe ray fer Reo cee Oe return sum(args) print(sum_all(1, 2, 3, 4)) # Output: 10 print(sum_all(5, 10)) Bae ae SSCS © Keyword arguments allow you to pass arguments by Pa eee ee and allows arguments to be passed in any order. oon ood fair coe} car co Pee eee een eee) Liscrsarsor eerie tttes 4, Arbitrary Keyword Arguments (**kwargs): CRE eC eee ad Pn mee eed Se ee ons co foro Poa emUerones) arma Om Tong arto) eon York") oe ome Cees DR ed are passed to the function in the correct positional ord Example: aoe ound aon, Prony CoC ERE eae) ene Nd © These arguments must be specified by keyword, not by positional arguments. They are defined after a * in Sea Cu Cas focu ood falters Ce eee rt) Cae en) Pte ttre eee Tee '. Describe the Syntax for the Following Functions Perera sees aso: eee ne em ood Oey oe mae me emt od Oe erent co ie food oo co ne Oe ee ers Pens co cond fo oo oa emt RS ees ae ts ce ed See eee ne eee are eet One eey epee errr na Cte See ened Sete ee cr ee ek eer Cee et ee ere ee rs eee Comparison Table: cd et food oc on ee po panera oo ono) ren pees one by ey Perera el changed) cd rear ts coo one supheate cong Coe eens eae) eed foro eee ane ry oo paren a) 2) fe ood Cd Go) ned Ca aa cro Sedeteacettesateerad ner frees Seemeitetateteestened oa oo a ro peeeienme rere a co pocepereonretuae tien) a rd EEE SEIN Cactionary methods with suitable examples. Q.10 (CO-4) : Attempt any ONE question, Each question is of 10 marks, a, Write a program to read lines from a text file starting with ") ~b. Write a program in Python to count the num! c. What are different modes to oj ).11 (CO-S) : Attempt any ONE questi or "T" with a suitable example ber of lowercase alphabets present in text file pen a file with a suitable example. ion, Each question is of 10 marke Q.10 (CO-4): Attempt any ONE question. Each Ce ey me (a) Write a program to read lines from a text file starting with "M" or "T" with a suitable example. Curl lao eC ee CLC ace) Pee Gee CMU ema) Peele Urea gs

You might also like