Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
458 views
79 pages
Python Programming Quantum
Nnnnn
Uploaded by
Khushi Pandey
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Download as pdf
Save python-programming-quantum For Later
Download
Save
Save python-programming-quantum For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
458 views
79 pages
Python Programming Quantum
Nnnnn
Uploaded by
Khushi Pandey
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Download as pdf
Save python-programming-quantum For Later
Carousel Previous
Carousel Next
Save
Save python-programming-quantum For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
Download as pdf
You are on page 1
/ 79
Search
Fullscreen
Introduction and Basics OIL Ninn 1-27 (CO-Sem-3 & 4) inane Long Answer Type and Medium Answer Type Questions | for Python, Python IDE, n Progr Questions-Answers CONTENTS 2) Part-l + 127 to Ler Introduction : The ... Programming Cyele for jing with Python Programs Part-2 : Elements of Python, 1-67 to 1-127 ‘Type Conversion Part-3 : Basics : Expressions, . ones LARD to 1-137 Assignment Statement Part-4 : Arithmetic Operators... 1-18T to 1-18T Part-5 : Operator Precedence, . |-18T to 1-287 Boolean Expression 1-11 (CC-Sem-3 & 4) Que 1d. | Explain the programming eycle for Python. Python's programming cycle is dramatically shorter than that af 4. Incases where dynamic module reloading can be use to change and reload parts of a running program wit all. 5, Fig. 1.1.1 shows Python's impact on the programming cycle. ‘Test behavior ‘Test behavior a Edit program code ‘Stop the application Edit program code th module reloading (a) Python's programming cy Fig Lut. there is a rapid tura ‘on’s parser is embedd ‘at runtime, yaround after program 6 Since Python is interpreted, a puaantes changes. And beeause Pythi ystems, itis easy to modify programs Que Ta] What is 1pHt Discuss some Pyenon mE.Python Programming 1-97 (CC-Sem-3 & 4) woe ea dahiware package that consists of several tol for developing An IDE helps the developer by automating the process. IDEs integrate many tools that are designed for SDLC. IDEs were introduced to diminish the coding and typing errors. ‘Some of the Python IDEs are a. PyCharm :PyCharm assists the developers to be more productive and provides smart suggestions. It saves time by taking care of routine tasks, hence increases productivity. Features of PyCharm : i Ithas smart code navigation, good code editor, a function for quick refactoring. ii. The integrated activities with PyCharm are profiling, testing, debugging, remote development, and deployments. iii PyCharm supports Python web development frameworks, ‘Angular JS, JavaScript, CSS, HTML and live editing functions b. Spyder : Spyder is widely us a seience works. used to create a secure and scientific environment Spyder Python uses PyQt (Python plug-in) which a developer ean add as an extension Features of Spyder: It has good syntax highlighting and auto code completion features, ii Spyder Python explores and e fii Itperforms very well in multi-langu: ¢. PyDev:lt is an external plug-in for Python interpreter. Features of PyDev: i. PyDevhas trong parameters like refactoring, debuexing VP hinting, code analysis, and code coverage function fi PyDev supports tokens browser, PyLint integration, interactive console, remote debugger, Unittest integration, ete TLE: IDLE is abasic IDE mainly used by beginner level develoPer EP) IDLE Python is a crose-platform IDE, hence it increases the flexibility for users. at: i Ttis developed only in Python in collaboration with Twinter GUL toolkit. .dits variables directly from GUL age editor. we and is very popular as 1-47 (CO-Sem-3 & 4) Introduction and Basics iii. ‘The feature of multi-window text editor in IDLE has some paid and free versions in the market with great features. QueASe | Discuss interaction with Python program with example. “Answer 1. The Python program that we have installed will by default act as an interpreter. 2. An interpreter takes text commands and runs them as we enter text 3. After Python opens, it will show some contextual information like this Python 3.5.0 (default, dec 20 2019, 11:28:25) {GCC 5.2.0] on Linux ; ‘Type “help”, “copyright, “credits” or “license” for more information 4. The prompt >>> defines that we are now in an interactive Python interpreter session, also called the Python shell. code for Python to run such as print(“Hello should appear on the next line like this 7. After showing the results, Python will bring you back to the interactive prompt, where we could enter another command or code. 8, Python program communicates its result to user using print statement: WERT] wats Python? ow Python isinterpreted What ore the tools that help to find bugs or perform static analysis ? What [ARTO 2019-20, Marks 10] are Python decorators ?Python Programming eee is again translated 3. The python code we writ ere BRGRGGkAcaie et eee 4. The bytecode compilation happer er eres ae en eememee 5. Compilation is simply a translation step, and byte code is a lower-level, and platform-independent, representation of source code. : 6. Each of the source statements is translated into a group of bytecode instructions, This bytecode translation is performed to speed execution, Bytecode can be run much quicker than the original source code statements 7. The .pye file, created in compilation step, is then executed by appropriate virtual machines. 8. The Virtual Machine iterates through bytecode instructions, one by, one, to carry out their operations 9. The Virtual Machine is the runtime engine of Python an¢ present as part: ‘of the Python system, and is the comp runs the Python scripts. 10. It is the last step of Python interpreter, Following tools are the static analysis tools that help to find bugs in python : 1. Pychecker :Pychecker is an open sours tool for detects the bugs from source code and warns complexity of the bug: 2 Pylint: ‘a Pylintis highly configurable and it acts contro} warnings and errors, it is an exte ssis and it looks dard. ‘as Pyeharm, Spyder, Python decorators : 1. Decorators are very powerful and aseful tol in Pyt ‘programmers to modify the behavior of funetion oF class. hon since it allows Sere tn ner Que 15) What do you mean by comments in Python ? ‘grammer to explain the piece of code to rogrammer in a simple language. Every pr 3, Python uses the hash character (#) for comments. Putting # before = text ensures that the text will not be parsed by the interpreter 4, Comments do not affect the programming part and the Pythoa interpreter does not display any error message for comments For example : Commenting using hash mark (#) poo +9 ‘addition " Output >>> 2) sie example, ‘ation’ ia written with « bash mark, Hanes the interpreter understands tas a comment and does not display any more messages, Tae | Favtsin identisions and keywords with example. 1A Python identifier is the name given 1% module or other object. variable, function, last,Python Programming 2. Anidentifier can begin with an alphabet (A ‘and can —___ MT (€¢-sem-s &4) de any munber'ere 2), oran underscore spaces are not allowed, 8. Python will not accept @ $ and % as identi 4. Python is a case-sensitive langua different identifiers. In python a lace oy capital letter. _ ‘Table 1.6.1. Examples of Identifiers Valid Invalid MyName My Name (Space is not allowed) My_Name Safig (cannot start witha digit YourName | Your#Name (Only alphal Underscore (_) and numeric Reserved keywords : Python has a list of reserved words known as keywords, Every keyword has a specific purpose and use. Some of the reserved keywords in Python: and assert break class continue del elif else except false finally for Java, ete. In Python, variabl reserve memory spaces as in other progr: je holds a value that may change. the variable name is called declaring the variable do not need to be declared explicitly in order to amming languages like C, Je in Python, Python Interpreter mn process. 1. The general format of assignment statement is as follows : ‘Variable = Expression LAT (COSem3 44) Introduction and Basies Example of >>>year=2 >>> name=‘Albert! The two give serve two memory spaces with variable names year and nat 16 and Albert, are stored in these memory spaces. Que 1,8. | What do you mean by data types ? Explain numeric and string data type with example. ‘Answer Data types : i. The data stored in the memory can be of many types. For example, a person's nameis stored as an alphabetic value and his addrese is stored 1. Numeric ly divided into integers and real numbers stegers can be positive or negative. al numbers are called, floating point numbers in programming languages. Such floating point numbers ‘contain a decimal and a fractional part. For example : >>> num1=2 # integer number >>>num2=2.5 real number (float) >>>numl 2 # Output >>>num? 25 # Output >>hon Prograramin Haibes Eevee oa (Conca) String: = 1 Single quotes or double quotes are used to represent strings. 2 Astring in Python can be as ‘and special characters. For example : ries or a sequence of alphabets, numerals >>> sample_string=“Hello” # store string value >>>sample_string ¢ display string value ‘Hello’ # Output Que 1.9. ] Discuss list and tuple data types in detail. Answer List 1. Alist can contain the same type of items, 2, Alternatively, a list can also contain different types of items, To declare alist in Python, we need to separate the items using commas and enclose them within square brackets ({]) Operations such as concatenation, repetition and sub-list are done on list using plus (+), asterisk (*) and slicing (2) operator For examp! >pofirst = [1, “two”, 3.0, “four”] # 1* list >>second = ["five", 6] #2" list, >>>first # display 1"list wo", 8.0, four’) # Output ‘Tuple: 1. A tuple is also used to store sequence of items 2, Like alist, a tuple consists of items separated by commas. 3, Tuples are enclosed within parentheses rather than within square brackets, For example: >>athird =(7, “eight”, 9, 10.0) >>othird (7, eight’, 9, 10.0) # Output RETA] Expiain dictionary and Boolean data type. Dictionary : 1. APython dictionary is an unordered collection of key-value pairs. 1-10 T(CC-Sem-3 & 4) Introduction and Basies 2, When we have the large amount of data, the dictionary data type is used. 3. Keys and values can be of any type in a dictionary. Items in dictionary are enclosed in the curly-braces {) and separated by the comma: 5. Acolon bracket For example : is used to separate key from value. A key inside the square used for accessing the dictionary items, first line”, “second”: 2) # declare dictionary ="third lay dictionary e” #add new item >>> diet #4 [1 first Line’, ‘second’: 2, 3:‘third line’) # Output Boolean : 1. Ina programming language, mostly data is stored in the form of alphanumeric but sometimes we need to store the data in the form of "Yes! or ‘No’ 2, In terms of programming language, Yes is similar to True and No is similar to False. 3, This True and False data is known as Boolean data and the data types which stores this Bi data are known as Boolean data types For example: >>> a= True >>> type (a) -
Que 1.11. | What do you mean by type conversion ? aul 1. The process of converting one data type into another data type is known as type conversion, 2 There are mainly two types of type conversion methods in Python a, Implicit type conversion : i. When the data type conversion takes place during compilation or during the run time, then it called an implicit data type conversion. ii, Python handles the implicit data type conversion, so we do not have to explicitly convert the data type into another data type.Python Programming 1-11 T(CO-Sem-3 & 4) eee For example: b=55 sum =a+b print (sum) print (type (sum))# ty variable Output : 105 ‘
el) is used to display the datatype ofa Inthe given example, we have and float data types and added Further, we have declared stored the result of the adi When we checked the data ty, see that the data type of th taken two variables of integer them, ‘ariable named ‘sum’ and the sum variable, we can um variable has been automatically converted into the float data type by the Python compiler. This is led implicit type conversion, Explicit type conversion is also known as type casting, Explicit type conversion takes place when the programmer clearly and explicitly defines the variables in the program. For example: # adding string and integer data types using explicit type conversion a= 100 b="200" result =a +b b=int(b) result2=a+b print (result2) Output : Traceback (most recent call last): File“, line 1, in ‘TypeError: unsupported operand type (s) for +: ‘int’ and'stt” 300 In the given example, the variable a is of the number data ‘ype and variable is of the string data type. Introduction and Basics , and when pri PART-3 Basics : Expressions, Assignment Statement. 300 as output. " Questions-Answers Long Answer Type and Mediam Answer Type Questions ‘Que 1.12. | What is expression ? Answer 1. Anexpression is a combination of symbols that evaluates to a value. 2 An expression is a combination of variables, operators, values sub-expressions and a reserve keyword. Whenever we type an expression in the command line, the interpreter evaluates it and produces the result, Expressions that evaluate to a numeric type are called arithmetic expressions. 3. 4 5. Asub-expressionis any expression that is part ofa larger expression. ‘Sub-expressions are denoted by the use of parentheses. For example: 4 +(3* 4) An expression can also consist of a single literal or variable. Thus, 4,3, and kare each expression. ‘This expression has two sub-expressions, 4 and (3 * &). Sub-expression '3* k) itself has two sub-expressions, 3 and &. 5| What do you mean by assignment statement? 1, Assignment statements are used to create new variables, assign valves, and change values. 2 Syntax of assignment statement : # LHS <=> RHS Variable = ExpressionPython Programming 1-13 T (CC-Sem-3 & 4) 3. There are three types of assignment statements i, Value-based expression on RHS ii, Current variable on RES ‘i, Operation on RHS ‘Que 144, | Discuss types of assignment statements with examples. ‘Types of assignment statement : 1. Value-based expression on RHS : In this type, Python allocates a new memory location to the newly assigned variable 2524751071304 2. Current variable on RHS : In this type, Python does not allocate new memory location. For example ype, we have an operation on the RHS of fining factor of the type of our statement. 1-14 T (CC-Sem-3 & 4) 1. An operator is a symbol that represents an operation that may be performed on one or more operands. Operators are constructs used to modify the values of operands. .e one operand are called unary operators, .wo operands are called binary operators, 'y operators are categories into following seven Introduction and Basies i Arithmetic operators. ii Assignment operators iii, Bitwise operators. Discuss arithmetic and comparison operator with Brea operators : These operators are used to perform arithmetic ‘operation such as at subtraction, multiplication and division. ‘Table 1.16.1. List of arithmetic operators. [Operator Description 2 Example + Addition operator to add two operands. 10 + 20 = 20) - [Subtraction operator to subtract two operands. /10—- 20 = ~10| x {Mult tion operator to multiply two operands, 0 x 20 = 200 i m operator to divide left hand by 5/2=25| right hand operator. + | Exponential operator to calculate power. 5772225 % _ |Modulus operator to find remainder. 5%2=11 71 |Floor division operator tofind the quotient and | 5//2=2) |remove the fractional part. ‘Comparison operators : These operators are used to compare values. It is, ‘also called relational operators. The result of these operator is always a ‘Boolean value i.e., true or false.Python Programming 1-15 T(CO-Sem-3 & 4) ‘Table 1.16.2. List ofcomparison operators, Operator Description Example == | Operator to check whether two operand | 10=— CES eran (0 == 20, false "sor | Operator to check whether two operand | 101=20, as are not equal. ‘| | > | Operator to check whether first operand 10>20, false is greater than second operand, 1-16 T (CC-Sem-3 & 4) Que 1.18, | Define bitwise operator with example. eee] Bitwise operators : These operators perform bit level operation on operands, Let us take two operand x = 10 and y = 12. In binary format this can be List of bitwise operators. Description Example | < | Operator to check whether first operand 10< 20, true| is smaller than second operand, jE >= | Operator to check whether first operand | 10> = 20, false is greater than or equal to -cond operand <= | Operator to check whether first operand is smaller than or equal to second operand. 10<=20, true ‘Que 1.17, | Explain assignment operator with example. =e] Assignment operators : This operator is used to store right side operands in the left side operand. ‘Table 1.17.1. List of assignment operators IThis operatar performs AND operation| x & y AND between operands. Operator copies bit if it exists in both operands | 1000 |= lyresutstin0 | [Bitwise | This operator performs OR operation OR —_|between operands. Operator copies bit ifit exists in either operand [ Bitwise | This operator performs XOR operation| = Ay remults 0 XOn en operands, Operator copies existsonlyinone operand. _| |-titwise [This operators «unary operator weed |= remalts 010i inverse _[toinverse the bite ofopersad |
> 2 results 0010 | = |Storerightside operandin left side operand, [a=b+e bits towards right +=. | Addright side operand tolef side operand and _|a+=bor 3 ; is : eee siti Uh tlds oncrand Goeee Que719] Discuss logical and identity operator with example. == |Subiractright side operandtoleftside operand [a—=bor | Bmawenl] and store the result in left side operand a=a-b Logical operators : These operators are used to check two or more conditions. The resultant of this operator is always a Boolean value. Here x and y are two operands that store either true of false Boolean values.Python Programming — — nel eS 1-18T(CC-Sem-3 & 4) = Introduction and Basies ‘Table 1.20.1. List of Membership operators, Perator perform OR operation | andy rea ‘een operands. When any operand 3 y results true} true, the resultant become true, ot logical | This operato ator is used to rev fe operand state “ees Identity operators : These oj operands are same or not. Supy 40. Then x is y returns false and x not turn true ‘ot in PART-5 Operator Precedence, Boolean Expression. - Questions-Answers Table 1.19.2. List ofidentity operators F Eo hes ; ‘Long Answer Type and Medium Answer Type Questions is _| Return true, if the operands are same. 7 Return false, ifthe operands are not notis | Return false, if the operands are same. | x notisy, results tru the operands are not Que 120. | Explain membership operator with example. Membership operators : 1, These operators are used to chee string, a list or a tuple. Jc an tem or an element that is part of an element: 2 Amembership operator reduces the effort of searching an clement 2 the list. 3. Su yse x stores a valus and 40, Then x is a part of the list y bees inthe list containing items 1 1 20 and isthe I the valve 205i ‘Que 121s | What do you mean by operator precedence ? =] 1, Whenan expression has two or more o the expressio For example 10+5/5 ‘When the given exp becomes 3. fight, the final answer the expr is evaluated right ‘This shows that changing the s are evaluated in the given expr eft, the final answer snce in which the jon also changes the condition that specifies the importance of each 0 the other. 3. Precedence ‘operator relPython Programming 1-19T (CC-Sem-3 & 4) Table 1.21.1. Operator precedence from lower precedence to highe Operator Description NOT, OR AND Logical operators ee ‘ot in in, not ‘Membership operator es is, not is operator = %, l= thay =, +=, *=, **a= | Assignment operators Eke} Equality comparison operator Comparison operators 1-207 (CC-Sem-3 & 4) Introduction and Basics 0 # Output 6561 # Output QueiZH] What do you mean by Boolean expression ? oR Write short notes with example: The programming cycle for Python, elements of Python, type conversion in Python, operator AKTU 2019-30, Marks 10 precedence, and Boolean expression. Bitwise XOR and OR operator Bitwise AND operator Bitwise left shift and ri hit Addition and subtraction Multiplication, Division, Modulus and floor division sr Exponential operator Que 1.22, | Explain operator associativity. Answer Associativity : 1. Associativity decides the order in which the operators with same precedence are executed. 2. There are two types of associativity a. Left to right : In left to right associativity, the operators of same precedence are executed from the left side first. b. Right to left : In right toleft associ he operators of same precedence are executed from the right side first. 3. Most of the operators in Python have left to right associativity. 4. Left toright associative operators are mult mn, floor and ** operator is right to left associative. 5, When two operators have the same precedence then operators are evaluated from left to right direction. For example: >>> 394/16 2 # Output >>>3*(4//6) ‘Answer | Programming cycle for Python : Refer Q 1.1, Page 1-27, Unit-1 Elements of Python : Refer Q. 18, Page 1-81, Refer Q. 1.9, Page 1-91, and Refer Q. 1.10, Page 1-9T; Unit-1 ‘Type conversion in Python : Refer Q. 1.11, Page 1-107, Unit-L 187, Unit-l. ion may have only one of two values: True or False For example : In the given example comparison operator ==) is used which compares two operands and prints true if they are equal otherwise print false >>> 5==5 True # Output >> 5==6 False # Output Que 1.24. | How memory is managed in Python? Explain PEP 8. Write a Python program to print even length words in a string. Aawwer | Memory management : L_ Memory management in Python involves a private heap containing all Python objects and di rructures. 2. The management of this private heap is ensured internally by the Python memory manager. 3. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or eaching, 4. At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing all Python-related¢ interacting with the memory manager of the operating systPython Programming integer objects are tuples or dicts managed differently aries because integers ements and speed/space tradeoffs, rua hon memory manager thus delegates vane object-specific allocators, but e1 es ork to the nsures, latter opera the bounds of the private heap, nat ‘he latter operate within PEP8; 1 = a ie design document providing information to the Python muanity, or describing anew feature for Python or its processes st environment. 2. ‘The PEP should provide a concise technical specification of the feature 3. PEP is actually an acron; ym that stands for Python Enhancemen Proposal m i PEP 8 is Python's style guide. Itis a set of rules for how to format the Python code to maximize its readability. A PEP is a design document providing information to the Python community, or describing anew feature for Python or its processes or environment. Program to print even length words in a string: def printWord # split the string s=s.p) # iterate in words of string for word in s: # if length is even if len(word)%2== print(word) # Driver Code 5 =“iam muskan” printWords(s) Output : am muskan + the following What will be the output afte Ee 8 a = i 4) |; jue 126, statements? x=8 y=2 print(x//y) i What will be the output after the if @Qaei27.| What will be the output after the following statements ? iP a)% Ee é (28)| What will be the output after the following statements ? x=3 What will be the output after the following ments? iB) Gt ‘Ek q statements ? x=6 yes print(x/y) What will be the output after the followingsUeeeeeewmaags 123 T(CC-Sem-3 & 4) y=7 ras xeey print(x) =a 2 1-247 (CO-Sem-3 & 4) cee ‘QueT31-] What will be the output statements ? x=3 ya7 print(x == y) after the following What will be the output after the following output after the following What will be the output after the following output after the following print(not y) Answer ‘True Que139.| What will be the output after the following ESHER] what witt be the output after the following aeiceente® statements ? x=20 x-72 y=40 y= 64 z=yif(y>x) clsex Printix
>> number = int (input (“Enter an integer number :") >>> if (number % 2) == 0: print “Number is even" cle; print “Number is odd” Enter an integer number : 6 Number is even Output ERA write « program to check the largest among the given three numbers. 2>> x= int (input (“Enter the first number :”)) Enter the first number : 14 797 =int (input (“Enter the second nuraber :”)) Enter the second number : 21 >> 1 int (input (“Enter the third number :”)) Enter the third number : 10 >> ifa> 9) and (x > 2): I= x ily > w) and ty > 2): ley hee: dew BIT te «Pinon program oct eines yar ina joap yeor oF 00%. aes BRB wee « ryinonprorra to cna te Fbonaze perenne x27) So> number = int Ginput ("Enter the valve for x here x> 2}1 jon Programmil DoT Ces Python Programming TCO-Boms & 4 print (x1), ay else print (*Fibonacei sequence is") xth=x1+x2 print (xth) update values xl=x2 x2=xth count +=1 Output : Enter the value for n (where n > 2)? 10 What do you mean by expression evaluation ? Tn Python actions are performed in two forms : 2 Expression evaluation, b. Statement execution, ‘Thekey difference petween these two fo ii sion. Ee tants onze varias ene rain Sue ree ae nee oes More statements, A statement Python. ing it bone, tet extatement by evaluating its expressions to values one Conditionals and Loops mn by evaluating the sub-expressions and Output Output 9 always a mathematical expression in Python. A QeTAL | Discuss float representation in Python. awe] Floating point representations vary from machine to machine Python float values are represented as 64-bit double-precision values ‘The maximum value any floating-point number ean be is approx 1.8 «10. ‘Any number greater than this will be indicated by the string inf in Python. Floating-point numbers are represented in computer hardware as base 2(binary) fractions. ape Forexample, the decimal fraction 0,125 has value Y/L0-+ 2100 + ‘and in the same way the binary fraction 0,001 has value 02 + 04 + 18. ‘For example :# Python code to demonstrate float values. Print(1.72308) ‘greater than 1.8 * 10°308 alae
, If itis true, then the program enters the loop and executes the body of the while loop, © Te continues to execute the body of the while loop as long as the condition is true, 4 When it is false, the program comes out of the loop and stops repeating the body of the while loop. For example : >>>eount = 0 while (count <9) print ‘The count is, count Entering for loop for each item in sequence Exiting loop ody of for loop “Statement after the for loo ‘The countis ;4 The countis: 521ST (CC Sema g 4 RBA wnat tn nested loop 1 Explain. 1. Loop defined within another loop is known us nested loop. 2 Nested loop are the loop that are nested inside an existing lon loops are the body of another loop, a Syntax: for condition for condition? : Body af for loop 4 Forexample: for iin range(1.9,2) for} in rangeti) printi i, end =*”) Print) Output : 1 333 55555 7777777 EBB] wnat is wreak statement in Python ? Pe csc) Oe ee) ee 2167 (CC-Sems & 4) 1 The break keyword terminates the loop and transfers the control tothe Conditionals and Loops 10 EBA exten continue statement with example 1 ‘The continue statement causes execution to immediately continue ot the start ofthe loop, it skips the execution of the remaining the loop. The continue keyword terminates the ongoing it the control to the top of the loop and the tion is evaluated ‘again. Ifthe condition is true, then the next takes place. Just as with while loops, the eantinue statement can alo be used in Python for loops For example: >>> for iin range (1, 10): Him 2 =O: ‘eontinue #ifcondition becomes true it skips the print part intipython Progamming Output : 2 2ATT(CC-Sem-3 & 4) 4 6 8 GEEHIT] explain the purpose and working of loops. Discuss brealc and continue with example, Write a Python program to convert time from 12 hour to 24-hour format. [AKU 2019-20, Marks 10] ‘Answer Purpose and working of loops : Refer Q. 2.13, Page 2-11T, Unit-2. Break statement : Refer Q. 2.17, Page 2-15T, Uni [-2:] =="AMP and strif-2] == "12": “007 + stri(2-— 2] HOMIE yee recgreerts arsonists tite any wih ote >>> count = 0 counter = count +1 else: print ("Inside the else statement”) Output : aside the while loop Inside the while loop 1 Inside the while loop 2 Inside the else GaeFAL| Write a python program to print jhe numbers for a user provided range. "~ Pythons program to print the prime numbers for & user provided range ‘input renge is provided from the user >>> low = int(inputt“Enter lower range -")) >> up = int (input(Enter upper range :")) >>> for nin range (low, up + 1) ifn> for in range (2, 0) f(a ei) ==0: break else print (n) Output : Enter lower range : 100 ‘Enter upper range 103, 107 109) us 121 11 137 1239 ug 351Python Programming 219 T(CO-Sems @ 4 187 163 167 173 QeeFAA_] Ditrerentiate between for and while loop. Properties For Format Initialization, condition| 0: ichecking, iteration statement | c checking is done at 2207 (CCSem-B&4) Conditionals and Loope 121212 Gue2Zs.| What will be the output after the following statements? fare written atthe the top of| Toop. oS ebeneen, ‘print(‘not false’) \Use ‘The ‘for’ loopis used only when| The ‘while’ loop is used onl wwe already knew the number | when the number of Seer: afiterations. are not exactly known false (Condition [Ifthe condition isnot given in| Ifthe condition is not given in ‘for’ loop, then loop iterates) ‘ infinite times. in ‘for’ loop the initialization| lonce done is never repeated. |done during condi ‘checking, then initializations| done each time the loop! iterate, bon ae =e 2; cine print(y, end='') GeSTE] wnat wittbe the output ater the fellowing statements? TERRE we we te ot ater the fetlewing statements? my=25 eee peiry. ends) “yerd 1045 TERR] wnt wine ne output ater th lowing statements? soresPython Programming. Z2ITCOSem9 gy Sees print onde? eit 1621 TEERIT] what wine the output ater the following natementay ea (Py, 8,0, 01 foriinx print(i, end="”) JERR] wan wave tne output after te fllowing statements? fori in range(l 5 tied Exeee print end) er) SHB] wat witbe the output after the following statements? x=15 ifx> 15: ea What willbe the output after the following statements? itx> 15: Conditionals und Loops print(ino’) ‘Answer GaeFSA| What will be the output after the following statements? x=50 i> 10 and x1: elif > 28 and x 235: print( false’) else: print(not false’) =z not false QueSSS)] What will be the output after the following statements?” “print(‘not false’) not false [GaEEIE wnat witbe te output ater the following vtatemenn? xx15 if > 10 and x<= 15: print(true) clifx> 15 and x <25:abstain nH 100Smse, print(‘not true’) ig paige @ oe aies Bee UNIT ©6O Functions and Strings CONTENTS Part-1 + Function : Parte of @ccrocrsmamuanns S2T to 37T Function, Execution of a Function, Keyword and Defaalt Arguments, Scope Rules Part-2 : Strings : Length of the —--..-- S-8T to S107 String and Perform Conestenation and Repeat Operations in ft, Indexing and Slicing of Strings Part-3 : Pythons Data Structure ©... SAT bo $19 ‘Toples, Unpacking Sequences, Lists nantes SOT to -26T + Mutable Sequences, Liat Comprehension, Sets and Dictionaries Objects, Lambda Expressions S17 (CC-Sem-3& 4)[Documentation omens] | Galle action — 2 Once a function i creatd by the programmer fora specif ask, this ele function ean be called anytime to perform that task. 3. Each function isgiven a name, using which we call it. A function may or ‘may not return a value. Function name: We define the function same for identification or to eotty en caampe, he Fanti sae 4 There are many builtin fuetions provide by Python suc as dir, Cen Ne ering liens Oa ene rdaetoreing eae Jabs (), et. iommex. Function a ws Python, 5, Users can also build their own functions, which are called user-defined ©. Alas Oe nee ed el ok tie ee ee 44. Angumente: Arguments are the values pamed othe fonctions beoreet Advantages of using functions . parentheses. In the given example, two arguments are used, = and» ‘They reduce duplication of code in ‘These are called formal arguments ee Body tion : The body processes the arpueats ‘They break the large complex problems into small parts Fy a ee ocean gl, body ete Soncon is noedd 3. They help in improving the clarity of code (i., make the code easy to wont the def keyword, vedeoriandl. & Documentation comment (doestring) : 4 documeniason SSS 4 Apiece ofeade can be reused as many times as we want with the help of (Goering) ta doneribe what the, amet dacs, = Pian “return maxisnim among x and y” isthe docsting REBAA] How to define and call function in Python ? Explain & Function call: To execute a function, we have to call. the oe different parts of a function, example, a = max (8, 6)is calling function with 3 and 6 a8 aTis== Tower |] TRE cen te ene af eas ae Punction is defined by “def ord f Frain Keyword following by function name and cxample, ‘Syntax of function definition ; def function_aame ( ):suTiCCSem3£4) ——Punetions, 224 String, —_—_— ris = Python Programming a BOC Hema Let consider an example to understand the execution of function ree % PDR Output = eos ee Fh att cre xox function square at OxS21B2DO0> when the onde is exceuted. aie 5 WaeTA |] Wat do you mean by key ameeat b Which it gives when we simply use “print x*x" code, but when yy, S “i ee on eee fection print equa” gives-Nonc” as mn outpt. =e © This is because when we call the fanction, recursion does not hay pease and leads to end of the function. oe eae : ee ohiestes 1 Keyword arguments arv related to the function calla Symene tailing. ‘the fanctio 2. When we use keyword arguments ina function cll, the caller identifies eens the arguments by the parameter name squares): 2, This allows us to skip arguments or place them out of order bees the ‘prints Python Interpreter in sble to use the keywords provided te match the ieshequare/4)) ‘values with parameters : ‘or example 6 def printmnel str ae “This prints a passed string into this function’ Step 2: When we retrieve the output using “return” command : ee hen re ee the “returs” function and exeeute te code, it will gve the 4 Now you can cll priate faction For example: rintme ste = "My string} ae Output : eee): My steing returala*s) a Default arguments : piace 1 Adefault argument is an argument that asmumes a default value if a ert ‘value isnot provided in the funetion eal for that argument. ‘or example : sr ‘When function is treated as an object : # Function definition is here * Tunetion en Python ae themselves a object, and an object has some ef printinfol name, age = 35: “This prints a passed info into this function’ 6 Whee we run the command “print square” # returns the value of the print "Name:", name © Since we have not pam print “Age”, ge facetion to run hence it 207 argument, me do not have any specific return ; the location of the apne 8 Seta value OxO21B2DI0) which is # Now you can call printinfo function For example : Printinfol age = 50, name =“miki* ) def scquaretx) : printing, name-=“mili”) retarmlxts) ‘Output: ‘Name: mikisarwosemseé) _Tueinaen ‘Age 50 Name: miki dees ERGHT] Pincus th ope rales in Python. Seope of a name is the part of the program in which the name can be used. 2, Two variables can have the same name only if they are declared in separate scopes. |. Avariable cannot be used outside its scopes. 4, Fig. 25.lillustrates Python's four scopes. Built-in (Python) [Names preassigned in the built-in names module: open, range, Enclosing function locals rope of any and all enclosing functions in any way within a function (def or lambda), and not declared global in that function. 5. The LEGB rule refersto loca so oe ‘eflers to local scope, enclosing scope, global scope, and 6. Local scope extends forthe body ofa indented the function definition including the parameter, that , that are defined in the body of © are local to that: functi Bie on ar el th funtion an eanot Be accessed utd 8. Theenclasing sope refers to variable ‘Toeelacing scape refers to variables that are defined outside a funcioe 9. Ia funtion i defined with vases ar vali aie nn ge arble an hs the cnslonng cope are svallbletostalomentenea ee fon and refers to anything 8-17 (CC-Sem-4& 4) Python Programming al GRETA] viscune function in Python with ite parts and seope. eplain with example, Take simple ealeulator with add, subtract, division and multiplication). Pas Scope : Refer @. 3.5, Page 3-61, Unit-3 For example : Simple calculator using python ‘tion adds two numbers xty ‘subtracts two numbers ” y ‘multiplies two numbers =", ade(num!,num2)) #2, subtract(aumi,num2)) jultiply(num1,num3)) =", divide(num1,aum2)) pprint(“Invalid input”)S-8T(CC-Sem3 & 4) Functions and g, Strings eee rig La ee 1. Strings are created by enclosing various characters within quotes. Python does not distinguish between single quotes and double quot Python, can be used as a single data type, o essed in parts. This makes strings really use! handle in Python, For example : >>> varl = Hello Python!” >>> var2.= "Welcome to Python Programming!” >>> print var Hello Python! # Output >>> print var2 Welcome to Python Programming! # Output For example: >>> var =“Hello Python!” Python Programming 3-97 (CO-Sem-3 & 4) string with house of quar races. bring hich consist of ears between tterat index but exsuding tbatatm Dhindex Hor einige poner «oo ythontsuoTCCSemS8 >>> print alphabet (1: 8:3) beh # Output Inthe given example, the slice is (1:8: 3], which meansit will take the element st 1*index sd tll 7 element. Since step is it will will print 1 clement, then 4° element and then 7* element he bed RSG Expiain the term indexing in Python, 1. Indexing means referring to an element of an iterable by its position within theiterable. 2 Forexample : Create a list using a list comprehension,: ‘my list = [_for_in ‘abedefhi) smy_list (at, "ee, 2, ‘Now to retrieve an element of the list, we use the index operator (()), For example: sy_List{O} | Tn Python, lists are “zero indexed’, so [0] returns the zeroth (ie, the Jeft-most) item in thelist. Inthe given example there are 9 elements in i ‘We want to access my_list(9] then it throws an of range. Python also allows to index from the end of the list P o ind e ‘using a negative a atest indices, we start counting from the right instead Negative indices start from—1, through [8)) and if list index out Python Programming PART-3 ‘Pythons Data Structure : Tuples, Unpacking Sequences, Lists. months in a year can be defined in a tuple /, February, ‘March’ ‘Apri, ‘May, June’, Suly’s12T(CC-Sem3 &4) Functions ang Strings peas, >otuple = 49, 6, ‘house! >>>print tuple (49,6,"bouse’) # Output BE How are the values in a tuple accessed ? ‘Accessing values in tuples : ss the values in tuple, it is in square brackets along wi Output TERSAM] explain tuptes as return values and variable-length arguments tuples with the help of example. Tuple as return values : 1. Tuples can also be returned by the function as return values. 2. Generally, the function returns only one value but by returning tuple, * function can return more than one value For example If we want to compute a division Want to know the quotient and the remainder ‘the remainder can be computed at the same ae i a aoe Ss Ts Yat ac returned. quotient and remainder, by using the tle a8 >>>defdiv.mod(a,b): # defining function Python Programming, 3-13 T(CC-Sem-3 & 4) remainder # function returning two values ‘two tuples, This is done by using + operator in Pythong-14T (CC-Sem-3 & 4) » - Functions and Sting Repetition : The repetition operator repeats the tuples a given numbe, trames. Repetition is performed by the * operator in Python, i Gee ahs in no, it give: ance put, otherwise false. For example: >>>tuple = (10, 20, 30, 40) >>>20in tuple True # Output Interation : It can be done in tuples using for loop. It helps in traversing the tuple. For example : >eotuple =(1, 2,3, 4, 5,6) >>> for x in tuple printx REBAR] wnat ao you mean by unpacking sequences ? G** example to explain. SAS T(CC-Sem3 & 4) smponents of the sequence into ents can be performed simultaneously ents in Python where we can have multiple LHS sige rom conespntiog values at the RHS, This isan example ‘and RBS must have equal length That i RS should he assigned to LHS, 5. Strings and tuples are example of sequences. Operations applicable on sequences are: Indexing, repetition, concatenation, For example >>> atudent Aditya’, 27, (Python, ‘Abha’,303)) ‘>>> name, roll, regdcourse = student (Python Aba’ 305) 6. Since strings are also sequences, we can also get individual characters in the string using unpacking operation For ‘abba! >>> print (x1, x2, x3, x4) abha HEB site sere note ost A list is also a series of values in Python. Ina list, all the values are of any type. ‘The values in a list are called elements or items A list is a collection of items or elements. ‘The sequence of data in a list is ordered and can be accessed by their veerspserecosems@a) __Funstions and Siig, 2 # Output ie >>> list [3] 4 # Output ene] Explain the copying method in list. aver | Wecan make a duplicate or copy of an existing list. ‘There are two ways to make copy of a list. L Using[:] Operator: >>> list_original = [1, 2, 3, >>> list_copy =list_original []_# Using [:] operator >>> print list_copy 11, 2,3, 4) 2 Using built-in function : Python has a built-in copy function which can be used to make copy of an existing list. In order to use the copy function, first we have to import it. For example : >>> from copy importcopy # Import library >>> list_original = (1, 2,3, 4] >>> list_copy =copyllist_original) # Copying list ‘>>> print list_copy 0, 2,3, 4) [EERIE] How clements are deleted from alist ? 1. Python provides many ways in which the elements in a list can be deleted. ‘Methods of deleting element from a list : 1. pop operator : 4. If we know the index of the element that we want to delete, then we can use the pop operator, 110,20,401 # Output The op operator deletes the element on the provided inde® = co lement ina variable forfurther wie. operator: The del operator deletes the value on the provided nd?® b but it does not store the value for further use. python Programming BATT (CCSem-3 & 4) (w,¥.'2] # Output 3, Remove operator: a, We use the remove operator if we know the item that we want to remove or delete from the list. (20, 30, 40] # Output b. _Inorderto delete more than one value from a list, del operator with slicing is used >>>print list 11, 4,5, 6, 7, 8] # Output FBEEE) Discs bustin st operators in detail Built-in list operators are as follows : 1. Concatenation : The concatenation operator is used to concatenate two lists. This is done by the + operator in Python. For example : >>>listil = [10, 20, 30, 40] >>>list2 = [50, 60, 70] >>plist = list] + list2 >>>print list (10, 20, 30, 40, 50, 60,70] # Output 2 Repetition : The repetition operator repeats the list for a given number of times. Repetition is performed by the * operator. For example: >>olistl = [1, 2, 3] >>olist 14 (1,2,3, 1,2,3,1,2,3,1,2,3] # Output & Inoperator : The in operator tells the user whether the given string existsin the list or not.Functions and g suriccsmseo ees ean opt tar ofa a eS tre eww otherwise, false For example: sozlist = [Hell’, Python’, Program’) >>> Hell in ist ‘True # Output >>> World in list False # Output [eB] Write various built-in list methods. Explain any thrg with example. Python includes many built-in methods for use with list as shown in Table 821.1. ‘Table 8.21.1. List ofbuilt-n list methods | S.No. Method : Description T | emp(tstt, list2) | It compares the elements of both lists list and list2 2 | maxdist) Tt returns the item that has the maximum value ina lst. 3. | min ist It returns the item that has the minimum value in a list. Tt converts a tuple intoa Ttadds the item to the end of Ttreturns number of times the item 9eeu's inthe list. 7. |listextend (seq) | Ttadds the elements ofthe sequence ath fend of the list. 8. _| list. remove tem) | _Itdeletes the given item from the Ttreverses the position (index number the items in the lst. 10, | istsort ({fancl) | Ttsorts the elements inside the ‘compare function if provided. 9 [listreverse() Tist and 2 Append method : This method canada new element o #0? toa Python Programming 2197 (CCSem-9 4 4) ey, # Output Sort method : This method arranges the list in ascending order. For example = post = 14, 2,5,8, 1,91 >>>list.sort() >>>print list 11,2,4,5,8,9) ‘Python represents allits data as object, Mutat of pects determines byits type. 2 Some of these objects like lists and dictionaries are mutable, meaning ‘we can change their content without changing their identity 3. Other objects like integers, oats, strings and tuples are immutable, ‘meaning we cannot change their contents4. Dictionaries are mutable in Python : ‘a Dictionaries in Python are mutable. bh. The values in adictionary can be changed, cc. Ifthe key is present in the dictionary, the: with that key is updated or changed; othe: pair is added. ('age’: 30, ‘name’:‘Akash') # Output >>> dictI(address]]=‘Alaska’ # adding a key: value >>pprint dict ‘tage’: 30, name'‘Akash’, ‘address’ ‘Alaska') # Outpu Inthe given exampl ka’ is added tothe dictionary. >>> var = ‘hello Python’ >>>-var [0] =p! Output: ‘Type error :'str’ object does not support item assignment Here, we try to change the O* index of the string to a character PD the python interpreter generates an error. pained ie ce is to generator a new string rathe® For example: >>> var = "bello Python’ >>> new_var ='p' + varll >>> print new_var palloPython # Output python Programming eae ————— 3-217 (CC-Sem-3 & 4) In the given exampl concatenate it ‘not have any effe the original string and insert in the string. It does 6 For example: >>> list = (10, 20, 30, 401 >>> list (1) 20 # Output Inthe given example, we act index number and the inter Now, if we want to change a valiue For example : >>> list [3] =50 # Output alue of the 4" element is changed to 50. Set builder notation isa notation i amathematical notation for describing ect by stating the property that ta members should satisfy. The syntax [cexpression> for
in
if
>> print intersection set({1,2, 51) # Ovtput >>> union = set] | set2 # Union of set] and set2 >>> print union set ({1, 2,3,4,5, 8,91) # Output >>> difference = set1—set2 # Difference of set 1 and set2 >>> print symm_diff set ((3, 4, 8,91) # Output Que 325) What is dictionary in Python? 1. The Python dictionary is an unordered collection of items or elements. 2. All other compound data types in Python have only values as their elements or items whereas the dictionary has a key : value pair. Bach value is associated with a key. In dictionary, we have keys and they can be of any type: Dictionary is said to be a mapping between some set of keys and values ‘The mapping of a key-and value is called as a key-value pair and together they are called one item or element. A key and its value are separated by a colon: ) between them. ‘The items or elements ina dictionary are separated by commas and al the elements must be enclosed in curly braces. A pair of curly braces with no values in between is Known as a8 =P dictionary. 9. ‘The vahiee in a dictionary can be duplicated, bt the heya inthe icSonary are unique. TERBG] row do we create a dictionary in Python?s2AT(CC-Sem3 & 4) 1. Creating adictionary is simple in Python. 2. Thevaluesin adictionary can be of any dat ofimmutable data types (such as string, jonary with mixed keys = (name’ ; Rabul’, 3: (Hello’, 2, 3]) 1 3}, name’ :‘Rahul) # Output Explain the operations performed on dictionary with ‘This example prints the key: value pairsin the dictionary dict 2 Membership: Using the membership operator (in and notin), we can test wt ‘akey isin the dictionary or not. ii Tnoperatortakes an input key and finds the key inthe dction® python Programming ee 8,3: 27,4:64,5: 125, 6: 216) Re # Outpat 35> 1T notin cubes ae. # Output Gata | Write some built in dictionary methods used in Python with example. ‘There givenin Table 3.28.1 ‘Table 3.28.1. Built-in dictionary methods, ‘are some built-in dictionary methods which are included in Python [No] Fonction 7, | all(diet) 2 | aay (dict) Tt is also a Boolean type function, which returns true ifany key ofthe ditionary is true. It returns false ifthe dictionary is empty. 3. [Jeataien the numberof items length) in 5 G 7__| dict. copy () Tt returns a copy of the dictionary. & | dict.get (key, For key key, returns value or default if default =None) | key notin dictionary. 9 | dictitemsO) Te returns list of entire key: valve pai of dictionary. 10. | dictkeyaO Teretur teLit ofallte keys in dion 11. _| dictupdate (aiet2 "dds the items from diet to diet. 12 dict.values () “qurns all the values in the dietionsry.3-267 (CC-Sem-3 & 4) Seca AO __Festony And Stein, ann String 8,3: 27,4: 64, 5: 125, 6 : 216) >>>all (cubes) ae 4 Output >>>any (cubes) Oar # Output >>>len (cubes) é # Output >>>sorted (cubes) # Output 4 64,5: 125, 6: 216) Output PART-5 (Order Functions : Treat Functions as First-Class Objects, Lambda Expressions, a ions and classes are treated as objects which are jets, allowing them to be manipulated in the same waysas built-in data types. 2 Bydefinition, first class objects are the following which is: a Createdat runtime b. Assigned asa variable or in a dat and _- return Lifn <2 else n* factorial(n ~ 1) >>> factorial (42) ‘python Programming _ S217 (CC-Sem & 4) qaesa| ‘Explain Lambda expression. Tower | “Lambda expressions is used to create the anonymous function. 2, ‘The anonymous functions are the functions created using a lambda keyword 9, They are not defined by using def keyword. For this reason, they are called anonymous functions, 4 Wecan pass any number of arguments to a lambda form functions, but still they return only one value in the form of expression 5. Ananonymous function cannot directly call print command asthe lambda needs an expression. 6 1s the parameters that are not defined in its own, 1 yymous function is a single line statement function. & Syntax: lambda fargl {,arg2, ...., argu] expression lambda fanction is a single statement For example : # function definition here >>>mult =lambda val1, val2:vall*val2; ‘function call here >>> print “value:", mult(2040) Value: 800 # Output Inthe given example, the lambda function is defined with 9 val and val2, The expression vall*val2 does the twovvalues, Now, in function call, we can direst with two valid values as arguments and produce given exampleFunctio; a tlt, ee in higher order function with respec Ques3l ‘Explain high Pect to lambgy expression. Write a Python code to count occurrences of an ¢} Teme, AKTU 201620, Hania yp ina list. “Answer 1. Reduced), filter, map() are higher order functions used in Python smbda definition does not include a “return” statement, it aly, 2 Lane i expresin whichis returned - ‘We can also put a lambda definition anywhere a function is expecte + awe do not have to assign it toa variable at all pected, ‘4 Lambda functions can be used along with built-in higher order functions like filter), map() and reduce(). ‘Use of lambda with filter( = 1 Thefilter() function in Python takes in a function and a list as arguments 2. This function helps to filter out all the elements of a sequence “sequence” for which the function returns true. For example : Python program that returns the odd numbers froman inputlist # Python code to illustrate filter i= (5, 7, 22, 97, 54, 62, 77, 23, 73, final_list = list(filter(ambdax: (x*%2!=" print(final_list) Output : 15, 7,97, 77, 23, 73, 611 h lambda argument. 2, The function is called with a lambda function and a list and reduced result is returned. This performs a repetitive operation °v>> hef (20, 40) 20 #Output >>phef (529, 456) 1 #Output value of * +a +" is", ord (a)) is',65) #Output #Finding ASCII value of space ("The ASCII value of ‘’ is", 32) #Output tots TREBBA] Write a function to convert a decimal number binary, octal and hexadecimal equivalents. d.| Write a function to find the ASCII value of the character. priton Programming : Eton ‘Finding binary, octal, hex value of 10 #Ontput hexadecimal equivalent’) 060Sieve of Eratosthene, and File 1/9 CONTENTS Part-l Sieve of Eratosthenes vo 427 to 44 Parta : File YO : File Inpat and. 44 to ert Output Operations in Python Programming Part-3 : Exceptions and Assertions 47T to 4197 Part-4 + Modules : Introduction, . 4-187 to 417T Iniporting Modules, Abstract Data Types : Abstract Data ‘Types and ADT Interfere in Python Programming Part-5 : Classes : Class Definition . 4-177 to 4207 and other Operations in the Classes, Special Methods (Guch as_init_, _str_, Comparison Methods, Arithmetic Methods, etc), Class Example + Inberitance : Inheritance and OOPS 417(CO.Sem. kd) 427 (CC-Sem-5 & 4) al 1. Let us take an example when n = 50. So, we need to print all print ‘numbers smaller than or equal to 50. 2. We create a list of all numbers from 2 to 50. “PART: Sieve of Brat ‘mumber (which is the next pr QeeTR" | Explain Sieve of Bratosthenes with example. is Sieve of Eratosthenes ? Long Answer Type and Medium Answer Type Questions ‘and repeat from step. a[s[e[s[el7]s][s| 0] hae bas pe fas fae a [ie [8 | ao a) ae [an | oe [ as | a8 [ar | oe | 29 [90 pe | ss fe fas [as |] el 0 apelele |e ]«>a |e] elopython Programming to the algorithm we vill mark, 3, According 1 nd orogrester than or equal 5 | 6 qs | 16* [17 25 | 26 | 27 29 | 30° 33 | sar_| 35_| 36 | 37 39 | 40 a |e | 45 | 48" | 47 49 | 50° Gext unmarked number 3 and mark all the numbery 4, Nowwemove to our Now very multiples of and are greater than or equal tothe square xt it omnes ees Suen] eB Te [| a7_| 28" [19 [ane Tr fase | 1s [ae | 15° aie (aa | 23 | exe | 25 | 26% | ee | oer | 29 om Tile [rss roses ioor)|) az ser | 59°) oe sig Ose ees (ese en ee || 4 | 4 | ‘ur next unmarked nusmber 5 and mark all multiples of5 ‘rthan or equal to the square of it e | 7 | 8 a6" | iz? | 18 5. We move to and are greate! ullikainl|Lae ii _|aze | 13 | 14" 4 driver program if_name_‘=='_main_’ n= 30 print “Following are the prime numbers smaller”, print “than or equ: * SieveOfEratosthe: - File 1/0: File Input and Output Operations in Python Programming. gir [aoe | 2a | 24" ger | 27* | 28* a1 [aot | ag | aan | ase _| 36" | 97" | 98" aa fae | 43 | ae a5e | 46" | ae | 48" ‘We continue this process and our final table will gears eare|oeb. 68 | 7 ti faz | 13 | a4* [ 15" | 16* | 17 ait [aoe | 23 | 24 | 25* | 26% | 27° a1 [aan | 33% | 34" | 36+ | 36* | 37 41 faze | 43 | 4ae | 45* | 46" | 47 So the prime numbers are the unmarked ones :2, 3,5, than or equal to 7 using Sieve of Eratosthenes. def SieveOf Eratosthenes (n) : Create a boolean array “prime(0. .n\” an # allentries it as true. A value in primeli] will jtialize GRETA] wrat are files ? How are they useful? Answer] 1. A file in acomputer is a location for storing some related data. 2. Ithasaspecifie name. 8. ‘The files are used to store data permanently on to a non-volatile memory (such as hard disks), 4. Aswe know, the Random Access Memory (RAM) is a volatile memory type because the data in tis lost when we turnoff the computer. Henes- ‘we use files for storing of useful information ‘or data for future reference. REGED] Describe the opening a file function in Python.python Programming Lek phe Sean 1. Python has a. 4-6 (COSomes g : C-Som-5 4) open () function to open files from are mainly needed by the open contains a string type value cont fe want to access. by Access_mode : The value of access_mode specifies the mod Access tant to open the file, ie, rend, write, append ete. 3 Syntax: fle_object = openifile_name |, aecess_mode]) For example : >>of= open (‘test.txt”) ‘Opening file current directory ‘>ef'= open (“CyPython27/README. txt”) #Specifying full path —-40utput poof open file‘C/Python27/README.‘xt' mode rat Ox02B05128> #0 vtput GEGAET | Explain the closing a file method in Python. Answer TL When the operations that are to be performed on an opened file are finished, we have to close the file in order to rele 2, Python comes with a garbage collector responsi earntorenced objects from the memory, we must not rely onit t
>> f= open (*test, txt”, “wh") # perform file operations >>> f.dlose() # close the file TERRA] Discuss writing to a file operation. a. We sbould overwriting persists in case: >of. write (writing to the file Ene 4) # clos the file after writing >>> felose () ‘The given example creates a file named test tx: overwrites intoit ifit exists If we open the file, content in it. Output: Writing to the file tine 1 Writing to the file line 2 Writing to the file line 3 Writing to the fileline 4 not exist, and ‘ind the following RRSTRD] explain reading from a file operation with example. “Aaswer | 1 Inorder toed fom lene mst pent inte eg made). ‘We can use read (size) method to read the data specified by size Ino size is provided, it will end up reading to the end of the file. The read() method enables us to read the strings from an opened Sie Syntax: file object. read ({sizel) For example: open the file peeHTT COBem.9 4 4) ryuhon roam _—— cc sPython’ ofaata EEE Discuss te VO in Python. How to perform open, read, Heed cose inte a Mle? Write «Python program to read fl 1 W187, Mark tine-by-tine store it into a variable. File YO: Refer @. 4.4, Page 4-47, Unit-4 ‘The syntax for assert is: assert Expression |, Arguments} iz, 3a 4, -AnAssertionError exception is raised if the condition evaluates false 5 6. _ Ifthe assertion fails, Python uses ArgumentExpression as the argument Open, read, write and close into a file : Refer Q. 4.5, Page 447, far the AssertionExror. me age (eT, Refer Q. 4.7, Page 4-5T, and Refer @ 45, RE sasnte'= : ‘Consider a function that converts a temperature from degroes Kelvin ror - *Students\n" degrees Fahrenbet. Since zero degrees Kelvin aa cold as gta, pad # writing to file function fails if it sees a negative temperature = fel =opentmyfile txt’, *W) ‘#Jaser/bipfpython ee 1) def KelvinToF ahrenheit(Temperature) ‘# Using readlines() assert (Temperature >= 0),“Colder than absolute zero” Sa sist?) return ((Temperature — 273)*1.8) + 32 Lines = filel_readlines() print KelvinToFahrenbeit (273) count = 0 print int(Kelvin’ +#¢ Strips the newline character sea 1ToFahrenheit (505.78) for line in Lines: B 1ToFahrenheit (— 5) print(line.strip() When the above code is executed, it produces the following result print(*Line(): ()" formaticount, line.strip)) 320 neat 451 BRR wn ao you moan by exceptions? 1L While writing a program, we oftea end up making some errors TRere ‘are many types of error that can occur in 8 PrograPython Programming a= py writing an improper these are also called comy ‘at runtime and these runt ‘The error caused or parsing ero": Brrors can also occur as exceptions. OFS are known, here are various types of runtime error it Python. saple, when a file we try to open does not exit, we Fr ert poordErer. ie a6 division by zero happens, we get 5 Filet etjsonBror, When the module we are trying to import doe exist, we get an Import Error. Python creates an exception ot time errors. ‘The user must write a piece rot eapable of handling the error, the program prints atrace back eae along with the details of why the error has occurred For example: Compile time error (syntax error) ject for every occurrence of these run of code that can handle the error. pppa=3 >>> iffa<4) # semicolon is not ‘included SyntaxError invalid syntax # Output ZeroDivisionError = >>>510 Output : ‘Traceback (most recent call last) : File “cpyshell#71>”, line 1, in
5/0 ZeroDivisionError : Integer division or modulo by zero Queda, | Explain exceptions handling with syntax. 1 2 a ‘Whenever an exception occurs in Python, it stops the current proce ‘and passes it to the calling process until itis handled. Ifthere isno piece of code in our program that.can handle then the program will crash. For example, assume that a function X calls the function Y, which in turn calls the function Z, and an exception occurs in 2. IF this exception isnot handled in itself, then the exception is passed to Yand thento®, Ifthis exception is not handled, then an error message Wille aisplaye ‘and our program will suddenly halt. the exceptio”: Ba ic the operation which can cause exception here, ifthere is exception, execute this. except Exception? = ifthere is exception?, execute this. else if no exception occurs, execute this. Python has optional finally clause that can be associated: b. Thestatements written in finally clause will alwaysbe executed by the interpreter, whether the try statement raises an ‘exception or not. try clause, we can use either except or finally, but not both. d. We cannot use the else clause along with a finally clause Peete ccm: >ostry: file = open(“C/Python2i/test.txt",-W") file write(“hello python”) exeeptlOError : print “Error: cannot find file or read data else 2 print “content written successfully”sea Propemming Ta ‘Sem 4g ate Gren cumple wea A aes access mode, and want t write to that file. ‘added ee ‘ except blocks the required file is not found 9° tine file, an exception is raised ite 4, The exception is handled by the except block and the following statemen. Pimor eannot find file or read data Tata is written to the file then the else bck print the following. Output : Content written successft FEPTEE cive nampa: poo try i function is, file = opent“testfile”,“w") try file. write(’Write this to the file") 1. Inthegiven example, try block, the 2 ‘Aner al the statements inside the nally block are © aes rcion in, rained agnin and is handled by the exept block that is aaeseiated with the next higher layer try block- Discuss exceptions and assertions in Python. How to handle exceptions with try-finally ? Explain five built-in exceptions — (arms. Taswer_|] Exception : Refer Q. 4.11, Page 4-8T, Unit-4, ‘Assertions : Refer Q. 4.10, Page 4-8T, Unit-4. Handle exceptions : Refer Q. 4.12, Page 4-9T, Unit-4. exception At Five built-in exceptions: oc Ka Alsibuiotrroriavaised L lin ert Tina tho bane class for hate aly such as when a non- sree ray orien aaden amare = ‘or example : invalid or not found. The exceptions raised are : 6lass Attributes(object) a KeyError __ Pass eee Rk bo IndexError : Print object. attributeaxe Peas __ +8 TCCSema ay Hs ee? atest got recent calls a cis acta Yn tribute ‘Goror.’Attributes' object has no attribute attribute’ ' ules Introduction, Importing Modules, Abstract Data ‘ Mogae Iran I nero n Prion Progaming GuedAG| Define the term modules. J Amoriuleis file containing Python definitions and statements, Amorile can define functions, classes and variables, 2, Iwallows.us to logically organize our Python code. ule name with the suffix py appended. clude runnable code. Grouping related code into s ‘module makes the code easier to understand and use. 5 Definitions from a module can be imported into other modules or into ‘the main module. For example : Here is an example of a simple module named as support py def print_funel par ): print “Hello”, par return GaeAAE | Explain the import statement with the help of example ewer | 1. Theimport statement isthe most common way of invoking the impot ‘machinery. te 2, Animport statement is made up of the import keyword along wit name of the modul ane 3, Theimport statement combines two operations it searches "1" aa module, then it binds the results of that search to a name !2 scope. 414 T(CC-Sem-3 & 4) se For example: to import standard module math and File VO Answer 1. Abstract Data type (AD’ by aset of value and a 2. There are three types of ADTs a. List ADT: The di head structure cor function needed to comp: b. Stack ADT: In stack ADT Implementation inst Eee hemes stead of data heing stored in ii The program allocates memory passed to the stack ADT. we data and address is ‘The head node and the jode and the data nodes are encapsulated in the ‘The calling function can only see the pointer tothe stack: The stack head structure also cont structure also contains a pointer to top and count of number of entries currently in stack. : © Queue ADT: i The queue abst data type (ADT) follows the basic design of data type. contains a void poi to the data and the link iii, The program allocates the memory for storing the data. BEER] explain ADT interface in Python programming. 1 ae ADTony defines as what operations arto be performed but st how se operati ented Il be organized in memory and'what lementiig the operations4 The process of pr ng only the esse Tatertace Application Program, Data Structures Linked List Memory Fig. 4.19.1. need to know how that data t 5. The user of data type does not need to know hi types Jmplemented, for example, we have been using primitive values like int, lost, char data types only with the knowledge that these data type can operate and be performed on without any idea of how they are implemented. 6 So,auser only needs to know what a data type can do, but not how it will be implemented. GaeABE]] Discuss ADT in Python. How to define ADT? Write cade for a student information. ‘Answer ee ADT in python : Refer Q. 4.18, Page 4-14T, Unit- ? ‘The een Stack are used to define Abstract Data Types (ADT) 19 Python. Code for student information : class Student : #Constructor def init__(self, name, rolino, m1, m2): self.name = name self.rollno = rollno self] = m1 selfm2 = m2 # Function to create and append new student def accept(self, Name, Rollno, marks1,marks2): _ # use ‘int(input())’ method to take input from user ob = Student(Name, Rollno, marks1, marks?) |s.append(ob) 4-16T (CC-Sem-3 & 4) sthenes and File VO 4 Function to display a def display(self, ob print(“Name -* ifflsfil.rolino == rn) return i 4# Delete Function # Update def update(self, rn, No}: obj.search(rn) # Create alist to add Students Is =f] # an object of Student class obj = Student’, 0, 0, 0) S \s used, ”) Print(*\n1 Accept Student details \n2 Display Student Details\a"/ /*3.Search Details of a Student \n4 Delete Details of Student” /*\nb.Update Student Details \n6 Exit”) ch =int(input(“Enter choice:”)) itch == 1): ‘obj. accept(“A”, 1, 100, 100) obj.accept(“B”, 2, 90, 90) obj.accept("C”, 3, 80, 80) eliftch == 2): print(“\n") print(*\nList of Students\0”) for i in range(ls._len_0: obj. display(Isfil) elifich == 3): print(“\n Student Found,”) 5 = obj.search(2)
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6094)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (627)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1147)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (922)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8212)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1253)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (631)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (860)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (8365)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (947)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (877)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (482)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (2922)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (277)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (438)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (4972)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Tóibín
3.5/5 (2060)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (444)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1067)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4273)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1972)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (275)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (1993)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2619)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (1936)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (125)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4066)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (75)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (901)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2530)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (790)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
3.5/5 (109)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4/5 (105)
Related titles
Click to expand Related Titles
Carousel Previous
Carousel Next
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Principles: Life and Work
From Everand
Principles: Life and Work
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Steve Jobs
From Everand
Steve Jobs
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Yes Please
From Everand
Yes Please
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
The Outsider: A Novel
From Everand
The Outsider: A Novel
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
John Adams
From Everand
John Adams
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
Little Women
From Everand
Little Women