You are on page 1of 79
cD) Introduction and Basics 1-27 (CC-Sem-3 & 4) PART-1 Introduction: The P The Progrmining Gye for Python, Interacting with Python Programa PE Questions-Answers Long Answer Type and Medium Answer Type Questions CONTENTS Part-I : Introduction : T Programming C: Python, Python IDE, Interacting with Python Programs Part-2 : Elements of Python, wo. ‘Type Conversion Basics : Expressions, ... Assignment Statement Part-3 : Part-4 : Arithmetic Operators... Operator Precedence, Part-5 + Boolean Expression 1-1T (CC-Sem-3 & 4) sone LAST to 1-1 Lar to Ler | L-6T to 12 1-127 to L-13T 1-18T to 1-28 Que Ti. | Explain the programming cycle for Python. ‘Answer 1amic module reloading canbe used. id parts of running program with Stop the application t Edit program code Bait program code (b) Python's programming cycle with module reloading (a) Python's programming eyele Fig Lt: ted, thereis rapid Python's parser is emt to modify programs at runtime. [ae cad Que: What is IDE ? Discuss some Python IDE- ython Programmi Py gramming 1-8 T(CC-Sem-3 & 4) ii, IDB is a sofware 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 funetion 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 used for data science: is mostly used to create a secure and scientific environment for Python. Spyder Python uses PyQt (Python plug-in) which a developer can add as an extension. Features of Spyder: It has good syntax highlighting and auto code completion features. ii Spyder Python explores and e ii, It performs very well in multi-language editor. PyDeviItis an external plug-in for Eclipse and i very popular at Python interpreter Features of PyDev: i, PyDev has strong parameters like hinting, code analysis, and code coverage function, i PyDev supports tokens browser, PyLint integration interactive console, remote debugger, Unittest integration, ete TLE: DLE is abasic IDE mainly used by beginner level developer {TDL Python ina croas-platform IDE, hence it increases he flexibility for users. = {i Tis developed only in Python in collaboration with Tkint>> defines that we are now in an interactive Python interpreter session, also called the Python shell. 5. Now enter some code for Python to run such as print(“Hello World”) and press the Enter key. 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. GRETA wt iaPython? low Pytho the tools that help to find bugs or perform are Python decorators ? Python Programming An interpreter is a kind is akind of progra ‘When wa write Python programs | 3, The python code we write is co eee compiled into python bytecode, which 4. The bytecode compilation happened inter ee pe ere aes 5. Compilation is simply a translation step, and byte code is a lower-level, and platform-independent, representation of source code, 5 6. Bach 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 8, The Virtual Machine iterates through bytecode instructions, one by operations 9. The Virtual Machine is the runtime engine of Python present as part of the Python system, and isthe comp runs the Python scripts. 10 It is the last step of Python interpreter. Following tools are the static analysis (ool in python : 1. Pychecker : Pychecker is an ope detects the bugs from source co complexity of the bug. 1s that help to find bugs 1» source tool for static analysis that ‘de and warns about the style and 2 ee 1b it looks for fas ii to-an open eouirce topLfor atatic code analysis 2 programming errors and is used for coding standard i erat epratos with Python IDEs such as Pycharm, Spyder, Eclipse, and Jupyter. Python decorators : 1. Decorators are very powerful and tseful tool in Pyth programmers to modify the behavior of function oF class: jon aince it allows ad ome cde on the tp of Talis. donnesor fection ad ao Long Answer Type and Medium Answer Type Questions Que 15 | What do you mean by comments in Python ? eal Comments : m allows us to add comments in the ende. ‘used by the programmer to explain the piece of code to by other programmer in a simple language. Every Tanguage makes use of some character for commenting. 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 Python interpreter does not display any error message for comments For example : Commenting using hash mark (#) por 849 addition VW # Output 27 kia example, ‘addition’ is writen with a hash mark, Hesse the interpreter understands tas a comment and does not display any more ‘messages. Gere | Explain identifiers and keywords with example LA Python identifier isthe name given 19 8 ‘module or other object. variable, function, lass, ‘Reserved keywords : Python has alist of reserved words known as keywords. Python Programming a ECC ies ag ~2), or an underscore a or under rscores and Table 1.6.1. Examples of Identifiers Valid Invalid MyName My Name (Space is not allowed) "| My_Name Sdfig (cannot start with a digit) Your#Name (Only alphabet: Underscore (_) and numeric are ‘Your Name Every keyword has a specific purpose and use. Some of the reserved keywords in Python: and del from None True as elif global nonlocal try assert elseif not while break except import or with class false in pass yield continue finally is raise def for lambda return Define variable. Also discuss variable initialization. Variables: 1 a. 2 Avariable holds a value that may change. ‘The process of writing the variable name is called declaring the variable in order to reserve memory spaces as in other programming Java, ete. 4, When we initialize the variable in Python, Python Interpreter automatically the declaration process. Initializing a vari 1. The general format of assignment statement is as follows : Variable = Expression Introduction and Basies known as assignment iny value, text or arithme ime of variable, >>>year=2 ‘The two give year and nat Que TB. | What do youmean by data types ? Explain numeric and string data type with example. aaa Data types : erve two memory spaces with variable names rt, are stored in these memory spaces. i. The data stored in the memory can be of many types. Far example, a person's nameis stored as an alphabetic value and his address is stored as an alphanumeric value. i, Python has six basic data types which are as follows 1. Numeric 2. String 3 List 4, Tuple 5. Dictionary 6. Boolean jumeric data can be broadly divided into integers and (ie, fractional numbers). Integers ean be ne 2. The real numbers numbers in programmi contain a decimal and a al numbers >>> num =2_ # integer number >>>num2=2.5 # real number (float) >>onum1 2 # Output >>>num? 25 # Output >>> ee SS ee creas String: 1. Single quotes or double quotes are used to represent strings. 2. Astringin Python can be a. and special characters. For exampl Series 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. 1. Alist can contain the same type of items. 2, Alternatively, a list can also contain different types of items, 3. A list is an ordered and indexable sequence. 4. To declare a list in Python, we need to separate the items using commas and enclose them within square brackets ({]). ions such as concatenation, repetition and sub-list are done on :) operator. “two”, 3.0, “four”] #1" list >>>second = [“five”, 6] # 2! list, >>ofirst # display [1, ‘two’, 3.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 , “eight”, 9, 10.0) (7,eight’,9, 10.0) # Output ‘GEETAO] Explain 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 Basics 2, When we have the large amount of data, the dictionary dat: used. ype is 3, Keys and values can be of any type in a dictionary, 4. Items in dictionary are enclosed in the curly-braces [} and separated by the comma: 5. Acolon( bracket For exampl is used to separate key from value. A key inside the square is used for accessing the dictionary items, first line”, “second”: 2) #declare dictionary third dictionary ‘second’ : 2, 8:‘third line’) # Output 1e”#add new item 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. Interms of programmi similar to False. inguage, Yes is similar to True and No is 3, This True and False data is known as Boolean data and the data types which stores this Boolean data are known as Boolean data types. For example: >>> a= True >>> type (a) type ‘bool'> Que 1.11. | What do you mean by type conversion ? eal 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 ii Python han not have to explicitly convert the ype implicit data type conversion, so we do ta type into another data Python Programming ee COS 1-1 T(CO-Sem-3 & 4) For example: co a=5 b=55 sum=a+b print (sum) Print (type (sum)) # type() is used to display the datatype of a Inthe given example, we have and float data types and added Further, we have declared another variable named ‘sum’ ant stored the result of the addition in it, oa r When we checked the data type of the sum variable, we can see that the data type of the sum variable has been automatically converted into the float data type by the Python compiler. This is called implicit type conversion. b. Explicit type conversion: i Explicit type conversion is taken two variables of integer them, also known as type casting, ii 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 ‘str 300 Tn the given example, the variable a is of the number data type and variable b is of the string data type Introduction and Basics ‘Que 112] what is expression ? meal An expression is a combination of symbols that evaluates to a value ‘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, A sub-expression is any expression that is part ofa larger expression. Sub-expressions are denoted by the use of parentheses, For example: 4 +(3*&) An expression can also consist ofa single literal or variable. Thus, 4,3, and k are each expression, This expression has two sub-expressions, 4 and (3 * 4). Sub-expression itself has two sub-expressions, 3 and &. What do you mean by assignment statement? 1, Assignment statements are used to create new variables, assign values, ‘and change values. 2 Syntax of assignment statement : # LHS <=> RHS Variable = Expression Python Programming 1-18 T(CC-Sem-3 & 4) 3. There are three types of assignment statements i Value-based expression on RHS. ii, Current variable on RHS iii Operation on RHS Que 1.14, ] Discuss types of assignment statements with examples. this type, Python allocates a igned variable. jon on the RHS of yur statement, ype, we have an opet ining factor of th 1-147 (CC-Sem-3 & 4) Introduction and Basics Que 5. | Define the term operator. 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. Operators that take one operand are called unary operators, Operators that take two operands are called binary operators. Based on functionality operators are categories into following seven iii, Bitwise operators. iv. Comparison operators. Discuss arithmetic and comparison operator with ‘operators : These operators are used to perform arithmetic , subtraction, multiplication and division. ‘Table 1.16.1. List of arithmetic operators. Description ‘Example + [Addition operator to add two operands. 10 + 20= 30 = mn operator to subtract two operands, 10-20 =-10) x lication operator to . 0 x 20 = 200] 1 mn operator to divide left hand by 5/2=25 lright hand operator. ++ | Exponential operator to calculate power. 599 2= 25) % [Modulus operator to find remainder. 5%2=1 71 |Ploor division operator to find 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.., true or false, Python Programming 167 Table 1.16.2. List of comparison operat ‘C-Sem-3 & 4) 1-16T (CC-Sem-3 & 4) ‘Description a, Que TAB, Define bitwise operator with example. Operator to check whether two operand | 10==20,false| ARSWOF Bitwise operators : These operators perform bit level operation on operands to check whether two operand Let us take two operand and y = 12. In binary format this can be qual. written as x= 1010 and y = to check whether first operand 10 > 20, false| ieee SS onal is greater than second operand. [Operator Description Example |< Operator to check whether first operand 10<20,true| fe Bitwise [This operator performs AND operation] x & y is smaller than second operand AND operands. Operator copies bit >= | Operator to check whether first operand | 10> 20, false a as is greater than or equal to second operand. [Bitwise [This operator performs OR operation |x | y results 1110 | <= [Operator to check whether first operand | 10<=20, true ST tare eee is smaller than or equal to second operand. “= | Bitwise [This operator performs XOR operation| x 4 y results 0110 BB] exptain assignment operitor with example. XOR _ between operands. Operator copies mememece SS bit fit exists only inone operand. | Tnswer | [bitwise this operator is a unary operator used | ~x resulta O01 Assignment operators : This operator is used to store right side operands _[ inverse _|to inverse the bits of operand. | in the left side operand > 2 results 0010 = [Store right side operandin left-side operand. |a=b +e ls bits towards right, FEO) [Aight ide operand tolefidewperand and [+= | RIE a ostat ana wana : store the result in left side operand a=atb g Discuss logical and identity operator with example. == — [Subtract right side operand to left side operand |a—-=b or ‘Answer | and store the result in left side operand feeb Logical operators : These operators are used to check two or more *=bor | conditions. The resultant ofthis operator is always a Boolean value. Here r += | Multiply right side operand with let side operand | a * = per: ways and store the result in left side operand a=a*b andy are two operands that store either true of alse Boolean values 7= | Divide left side operand by right side operand |.a/=b or and store the result in left side operand a=a/b %= | Find the modulus and store the remainder a %=bor in let side operand a=a%b **= | Find the exponential and store the result peabor in eft side operand aza**b 4/= |Find the floor division and store the result a/l=bor in left side operand a=al/b Python Programming Mart ces Sem-3 & _____ Eimcegs 1-18 T(CC-Sem3 & 4) Introduction and Basics Table 1.19.1. List of logical o ee ee operator ee Perators, ‘Table 1.20.1. List of Membership operators. hind logical | This operstor perform AN Example {Operator Description. ‘Example | | AND | between ND operation itemisin ist orin | operands. Why x and y resul in [Return true ifite ~riny, results true | | are tru en both operands | ts fas ‘Return fal is not — , the resultant become true Fn lit or in sequence | lorlogical | This operator perfor ti foe ol bare rm ORoperation | x not in [Return false, rin | xnotiny,resul -en oper, andy resul | ist perands. When any operand Brae, sequence. Re item fe rue, the resultant become trne inlist or in sequence a [____Jintistorinsenuenee, sa baba thsomnnarsactooeees tara \ pa opecmndatate. aa” | PART-S. a _| Identity operators : These ope: operands are same or not. Suppose 40. Then x is y returns false and x not heck wl andy st Table 1.19.2. List of id Description is Operator Precedence, Boolean Expression. ‘Long Answer Type and Medium Answer Type Questions Return true, if the operands are same Return false, if the operands are not same. | notis urn false, if the operands are same. turn true, if the operands are not fee r exckiene eI Que 1.20, | Explain membership operator with example. Membership operators = 1. These operators are used to chee astring, alist oratuple. ‘A membership operator the list. stores 8. Suphiy then x isa partoof the listy because can item or an element that is * reduces the effort of searehi 20 and y is the list con value 20 andy ie x notisy, results tru part of ing an element in taining items 10,20, 30, value 20s inthe list: =a ee] 1. Whenan expression ‘What do you mean by operator precedence ? ‘When the given express becomes 3. 2, However, if the expression is evaluated right to left, the final answer becomes 11. This shows that changing the sequence he operators are evaluated in the given expression also solution, st specifies the importance of each Python Programming L197 (CC-Sem-3 & 4) Table 1.21.1. Operator precedence from lower precedence to higher. Operator Membership operator ee ee | Seen Identity operator Assignment operators, Equality comparison operator Comparison operators 1-20T (CC-Sem-3 & 4) Introduction and Basics 0 # Output poo attaes2 #3416 43046721 # Output >>> (94s 72 #81A2 6561 # Output Que 123, 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-20, Marks 10 precedence, and Boolean expression. Bitwise XOR and OR operator Addition and subtraction ‘Multiplication, Division, Modulus an floor division Exponential operator ‘Que 122, | Explain operator associativity. Prensa Associ L a Associativity decides the order in which the operators with same precedence are executed. ‘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. Bb. Right to left : In right to left asso the operators of same precedence are executed from the right Most of the operators in Python have left to right associ ication, floor division, ete. Left to right associative operators are mult and ** operator is right to left associative When two operators have the same precedence then operators are evaluated from left to right direction. For example: >>>3*4//6 2 # Output >>> 3*(4/16) ‘Answer | Programming cycle for Python: Refer Q Elements of Python : Refer Q. 18, Page 1 and Refer Q. 1.10, Page 1-9; Unit-1 ‘Type conversion in Python : Refer Q. 1.11, Page 1-107, Unit-1 Operator precedence : Refer Q. 1.21, Page 1-18T, Unit-1 Boolean expression : A boolean expression 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 ooo 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. AKTU 2019-20, “Answer | Memory management : 1. Memory management in Python involves a private heap containing all Python objects and data structures. 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 enough room in the private heap for storing all Pyth« ad interacting with the memory manager of the operating #¥' Page 1-27, Unit-1. fer Q. 1.9, Page 1-97, Python Programming ene 2) On top of the raw operate onthe memory al aged differently wi because inte Aaa nd speed/space tradeotte ger thus del 5, but ensure te heap heap Bers imply different Python memory mana object-specific allocato the bounds of the privat PEP8; wy A PEP is a design document ocument providing information to the Pyth community, or describing anew ie environ OF describing anew feature for Python or its processes or ‘The PEP should provide a concise technical specification ofthe feature 3. PEP is actual an acronym that stands for Py pees Enhancement 4. PEP 8 is Python's style guide. It is a set of rules for how to format the Python code to maximize its readability. 5 A PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment. Program to print even length words in a string : def printWords(s) : # split the string s=s.split("’) # iterate in words of string for word in s: # if length is even if len(word)%2==0: print(word) # Driver Code 5 =“i am muskan” printWords(s) ‘Output : am muskan following Waei2e)] what will be the output after the follo% statements ? x6 yes print(x/y) SF : 2 5 26. statements? x=8 y=2 print(x//y) ii @Queia7.| What will be the output after the following statements ? x=5 ya4 print(x%y) | 128)| What will be the output after the following pane bLok 3 i y #| 3; ry What will be the output after the following statements ? x=5 y=7 xtey priniGo Answer i owing TEGeTSO] what wilt be the output after the folle statements ? x=30 Python Programming 1-23 T(CC-Sem.; th) eT COS S RA) Introduction and Basics Se oo =eey y= False print(x) print(x and y) Answer Answer 2 False e 1e at il Ye output after the followin, ‘QueTSi-] What will be the output after the following | ated cant eek et Gee statements ? statements? x=3 x=True ya y= False Print(x == y) print(x or y) aa] =a False True ie I37] What will be the output after the followin, 182| What will be the output after the following ae x - statements ? oesoc x= True g 1.88.| What will be the output after the following output after the following ot cnts? x= True ” EB 8 ‘Que 139.| What will be the output after the following statements ? x=20 y=40 z=yif(y>x elsex print(2) output after the following BETA] what wil be the output after the following statements ? z=True output after the following Python Programming y=10 z=yif(y>x)elsex Print(z) y=53 Z=y if (x%2==0) else x print(z) Answer. 65 Que 1-42.| What will be the output after the following statements ? x= 46 y=98 z=y if (y %2==0) else x print(z) Answer: 98 Que 1.43.| What will be the output after the following statements ? GeeTAT] What will be the output after the following statements ? x=7*(4+5) print(x) 63 THETA] wnat wit be the output after the following statements ? xs (24416 1-26'T (CC-Sem-3 & 4) Introduction and Basics print ‘Answer 216 Gueide)] what will be the output after the following statements? x=15 +95 print(x) ‘Answer 50 QueiAT,| What will be the data type of x after the following statement if input entered x= input(Enter a number ‘Answer String Que 148, | What will be the data type of y after the following statement x danres Integer Que T49.]| What will be the data type of y after the following statements ? x=7 y=float(x) Float GTROT] what wit be the data type of 3 after the following statements ? x=48 y= stron) String eo cate ——____—__* statements ? X=yer=8 print(y) Answer 8 Que 152.] what will be ¢) statement ? X=y=z=300 Answer 1 All three will have the value of 300 Que 1.53, 1 What will be the value statement ? %Y,2=3,4,5 Answer * will have the value of 3, y will have the value 4 and of 5, Que 1.54. | In the order of Precedence, which of the operation will be completed last in the following statement ? 3°6+5-4/2 ‘Aaswer | Subtraction ‘Que 1.55. ] What will be the order of precedence of operations in the following statement ? 10*4-14+8/5 ‘Multiplication, Division, Addition, Subtraction ‘Que tse] ‘What will be the data type of x after the following statement if input entered is 64? x = float(input(‘Enter a number’) Float hy © value of =, y and z after the following of sy and = after the following will have the value 1-28 T (CC-Sem-3 & 4) be Bete (COS em abs (57. statements? a=27/3%2* 4°*2 Introduction and Basics i What will be the output after the following 6.0 What will be the output after the following i statements ? a=3/3+4°7-3"3 print(a) i ©0O PART-1 Conditional Statement in Python Gf-else Statement, its Working and Execution), Conditionals and Loops ae CONTENTS Part-1 ; sou ET to statement, eee its working and execution) Part-2 : Nested-if Statement and .. snwnee BAT 10 2-97 : Expression Evalu: snenes 2A9T to 2-117 and Float Represent Purpose and Working of... QUIT to 2-147 Loops, While Loop Including its Working 2-147 to 2-237 + For Loop, Nested Loop, Break and Continue Statements atement consists of a Boolean expression followed by one or 2. With an ifclause, a condition is provided; ifthe condition is true then the block of statement written in the if clause will be executed, otherwise not 3 Syntax: If (Boolean expression) ; Block of code #Set of statements to execute if the condition is true 2-17 (CC-Sem-3 & 4) 23T(CC-Sems a 4, Python Programming SE Statements of if block rest ofthe code For example: var = 100 if( var == 100): print “value of expression is 100” print “Good bye !” ‘Output : ‘value of expression is 100 Good bye! EBAY] what do you mean by if-else statement ? Explain with the help of example. ‘An if statement can be followed by an optional else statement, which executes when the Boolean expression is False. 2, Theelse condition is used when we have to judge one statement on the basis of other. 3 Syntax: If (Boolean expression): Block of code #Set of statements to execute if condition is true else : Block of code #Set of statements to execute if condition is false 4 Working and execution : ‘he condition will be evaluated to a Boolean expression (true oF a b. Ifthe condition is true then the statements present inside theif block will be executed ool & Ifthe condition is false then the statem. inside else block will be executed. OD cabal 2AT(CC-Sem-3 & 4) Conditionals and Loops 5. Flow chart : Condition ? False True 1 Statement of else block Statement of ifblock rest ofthe code ‘ber is greater than 10") print (“Number is less than 10”) z print (“This statement will always be executed”) 2 ms a: anne int neces caer ices at ob te ete only if the fist condition executes as true. iftest z sion 1 cs ‘# executes when condition 1 is true BERRA] explain cit statement in Python. Explain al the conditional statement in Python using small cade (Aser 2019-30, Marks 10] avwer] Fe ‘ional statement are ; * asec Page 2-27, Unit 2 2TTCOSem4 & 4 else: print “value of variable a is greater than 40") Output : value of variable a is greater than 40 GERD] Write a program to find whether a number is even or odd. >>> number = int (input (“Enter an integer number :")) >>> if (number % 2) == 0: print “Number is even" else: print “Number is odd” Enter an integer number : 6 Number is even GRETA] Write « program to check the largest among the given three numbers. >>> x= int (input (“Enter the first number :”)) Enter the first number :14 2229 =int (input (‘Enter the second number 7) Enter the second number : 21 22 = int input (Enter the third number") Enter the third number; 10 227 iba> 9) and (x> 12): #0utput lax ify >) and ty > 2): ley lee: let Conditionals and Loops Output SBR] write» Pytnom pros to nck hep yer leap year oF not. ee rh tins pe FERBBIT write « Python program to aiopay the bones ence ‘Enter the value for x (where x>2)7)) >>> number = int (input (“ Python Programming 29T(CC-Soms « 4 = print (x1) a 2-107 (CC-Sem-8 & 4) Conditionals and Loops else: r = print (“Fibonacci sequence is") casion by evaluating the sub-expressions and. print (xth) # update values xl=x2 x2=xth count + =1 Output : Enter the value for n (where n > 2)? 10 Que BAL] Discuss float representation in Python. Tawer | n point representations vary from machine to machine 2 type in Python represents the Noating-point number. a ‘ged to represent real numbers and is written with a decimal the integer and fractional parts 4. Forexample: 9798, 92.3 + e18,~32.54¢100all are floating point summers 5. Python Moat values are represented as 6i-bit double precision valves 6. The masimum value any oating-point number can be is approx ra a as = 1.8% 108. 1. Any number greater than this will be indicated by the string inf in What do you mean by expressic 5 Python. expression evaluation ? Floating-point numbers are represented in computer hardware as tase “Answer” 2 (binary) fractions oe a ‘ore? le, the decimal yn 0.125 has value U'10 + Y/100+: 1. In Python actions are performed in two forms: aE oe hc nary ection 0.01 bas value +04 + US Eee enna For example : # Python code to demonstrate float values. oes eat Prin 76308) . Y difference between these two forms is that i # greater than 1.8 * 10*308 returns a: is sssion evaluation . io ea ea rea es eat cahe Sma 4. Sane ser or more ruin one OF more statements, A statement ans pyone seninastatemet by evaluating expressions tovaues ne areas 21LT(COSem.3 ay Expression evaluation : Refer Q. 2.10, Page 2-97, Unit-2, Float representation : Refer Q. 2.11, Page 2-107, Unit-2. Program : import math 4 Autility function that returns true ifx is perfect square def isPerfectSquare(x): aa = int(math sqrt(x)) return s*s == x # Returns true ifn is a Fibonacci number, else false def isFibonacci(n}: return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n'n — 4) 4 Autility function to test above functions for iin range( else: Print iis a not Fibonacci Num! Ray, i Number” Lis a Fibonacci Number 2s a Fibonacei Number 3 isa Fibonacci Number 4 is anot Fibonacei Number 5 isa Fibonacci Number TR] ering = Joop, Also, discuss the purpose and working of 2-12°T (CC-Sem-3 & 4) = 1. Alvopisa programming structure that repeats a sequence ofinstructions until a specific condition is met. 2, Aloop statement allows us to execute astatement or group of statements ‘multiple times. 3, Python programming language provides following types ofloopsto handle looping requirements: Conditionals and Loops a For bh While Nested es Purpose The purpose ooops isto repeat the same or similar, code a searrete Tea This sumber of ines cul especie to a ceean aera the number af times could be dicated by a cerain condition Being met 5. Working: Consider the flow chart or aloop execution Out of Loop ‘a Inthe low chart ifthe test condition is true, then the loopis executed, ‘and ifit is false then the execution breaks out of the loop. be Ane successfully executed the execution again starts from the loop entry and again checks forthe test condition, and this ‘keeps on repeating until the condition is false RRB scans white oop in beet wer] certain 1 While loop statements in Python are used to repeatedly execute acertain statement as long as the condition provided in the while oop statement istrue. Python Programming 2-18 T(CC-Sem. tthe program control to iterate over a block of cade. gram first evaluates the while loop condition. , then the program enters the loop and executes the body ile loop. © It continues to execute the body of the while loop as long as the condi rue, 4 Wher false, the program comes out of the loop and stops repeating the body of the while loop. For example: >>peount = 0 while (count <9): print ‘The count is ’, count PART-S For Loop, Nested Loop, Break and Continue Statements. Geib] Explain for loop with the help of example. clement reached? Exiting loop Body of for loop ‘Statement after the fr loop Ce Sais Ah ga Python Programming Se sg 21ST (CCSems 4 « 2167 (CCSem3 4) Conditionals and Loops For example: ist 2 Sean. ieee | print 2 1 The break keyword terminates the loop and transfers the contralto the Output : - 2 ‘ 6 3 ’ ately flowing the loop. 4 10 “ RBI) wat is nested toop 7 Explain. 1. Loop defined within another loop is known as nested loops A 2 Nested loops are the loopa that are nested nested loope are the body of another op. mnane Wow t 4 & Syntax; 6 for condition 8 for condition? | 10 Betist t lerp TEBE expnin continue statement with example. 4. For example: finan) = for jin rangeti) L. The continue statement causes execution to immediately continue at print( i, end the start ofthe loop, it skips the execution of the remaining body part of p re 2 the loop. ‘Outp 3 2. The continue keyword terminates the ongoing it tion t the control to the top of the loop and the loop + ‘again. If the condition is true, then the neat iter: aes 3, Just as with while loops, the continue statement 55555 ‘Python for loops 7777777 For example + >>> fori in range (1, 10) : ifi% 2 = 0: BRA] west break statement in P aa ‘continue #ifeondition becomes true it skips the print part print i 217 T(CC-Sem-3 & 4) ppb og Outpat : 2 4 6 8 GECTIR sna te purpose and working ooops Discuet break and continue with example. Write a Python program to convert, time from 12 hour to 24-hour format. [AKT 2019-20, Marks 10 “Answer | Purpose and working of loops : Refer Q. 2.15, Page 2-11, Unit-2. Break statement : Refer Q. 2.17, Page 2-15T, Unit-2, Continue statement : Refer Q. 2.18, Page 2-167, Unit-2. Program : 4 Function to convert the date format def convert: 4 Checking iflas 2 ifstrl[-2:] ==*AM” and stri[:2] ==“12": return “00"+ str1|[2:~ 2] ;oelements of time #is AM and first two elements are return strl(-~ 2] # Checking if last two elements of time is PM and first two elements are 12 elifstr1(-2:] == “PM” and str1[:2] == "12": return strl(;~ 2) else: add 12 to hours and remove PM return str(int(stri[-2)) + 12) + str1{2:8] # Driver Code ‘print{convert24(“08:05:45 PM")) BEBEIGR we «program to demonstrate while loop with else >>> count =0 >>> while count <3 Print (“Inside the while loop") Print (count) counter = count + 1 chee > ae 2-187 (CC-Sem-3 & 4) Conditionals and Loops print ‘Inside the else statement”) Output : Inside the while loop 0 Inside the while loop 1 Inside the while loop 2 Inside the else GESTHET] write a python program to print the numbers fr auser provided range. . rovidec 7 ‘Pythons program to print the prime numbers for a user provided a input rangeis provided from th user So Mow sintinput Enter lower range") Sp int npetEnter upper range") 33 for in range ow vp +1) ifn for iin range (2, n) if(n %i) ==0 break else r print (n) ‘Output: Enter lower range : 100 Enter upper range : 103 107 109 13 127 131 137 139 us 151 Python Programming 2197 (6CSem54 4 7 2 sr 1 REESE] pitterentiate between for and while loop. |Properties ‘Format ation anq| -cking is done at Use [The for loop is used only when| we already knew the number| ofiterations. are not exactly 2-20 T(CC-Sem-3 & 4) yerl newer | 121212 GaeBas, | What will be the output after the following statements? x=70 ifx<=30 or x>= 100: print(‘true) elif x <= 50 and x == 50: fare written at the the top of| loop. the loop. ‘Ifthe condition is not given in| ‘while’ loop, it provides| compilation error. Condition |ifthe condition is not given in| ‘for’ loop, then loop iterates| infinite times, Initialization] tn ‘for’ loop the initialization| In while loop if initialization is jonce done is never repeated. |done cond ‘checking, then initialization done each time the loi iterate, WOM at wn ae cutye ater tho roto statements? 112358 x=1 while x <4: xte1 yel while y <3: printty, end=’) print(false’) ‘print(‘not false’) aeene TSB) newt tne output ater the flowing statements? my =2,5 oes print(xy, end="") =e “y+sd 1045, [TERE] wat witne he output ater the fllowingstatements? for inrange(t, 25,5): Python Programming 221T(COBem.¢ mem & 4) print(i, end=") 16111621 RRA] what witb the oun ater the following siatementay ees - print(‘no’) Taawer | GueFSE| What will be the output after the following statements? Answer aoe [GEER] wont wpe the output anerthetowingstatemente? TEER wnt wit the output ater the following statements? an isis Python Programming ©8O 2-297 (CO-Sema. y eed) 6 | Functions and Strings CONTENTS faa Peale Function, Keyword and Default Arguments, Scope Rules Operations in It, Indexing and Slicing of Strings Part-3 : Pythons Data Structure ©... S117 to $19 Toples, Unpacking Sequences, Lists Mutable Sequences, .... List Comprehension, Sets and Dictionaries Part-4 + Part-5 : S1T(CCSem-3& 4) 3. They help in improving the clarity of code (i.e., make the code easy to understand). 4 Apiece of code can be reused as many times as we want with the help of functions. RRR] How to define and call function in Python ? Explain different parts of a function. Function is defined by “def” keyword following by function name and Syntax of function definition : def function name (): ly identi ; imax Function anming flows the same rales of writing wentiions= Python, cok z | 4. Arguments: Arguments are the values passed tothe fsnetians parentheses. In the given example, two arguments are wend, = and » ‘These are called formal arguments. 5 Body of the function : The body processes the sxguments w de something useful. In the given example, body ofthe function isimtendied es, es Fonetions and String = Recs” Beers ee — ieee SS aaa ey en et “it x ts This is because when me call the For example : ev 3: When fanetin treated sane: ‘* Fasctions in Python ars themselves an objet, nd an object has some 6 When we run the command “print square” it ‘it returns the value of the e fc en ame any hens femme mene trr eer ote tibet te ae co For example : del eqoaretx) : returnla’x) Python Progra ae 25 TCCHems printisquare) Output : >> var? = "Welcome to Python Programming!” >>> print varl Hello Python! # Output >>> print var? Welcome to Python Programming! # Output GEST] wha is ten) tunction ? oR mie AES 1. Jen () is a built-in function in ring, len eta fae Ei, When used with string 2 Sack She pa weil ‘haracters are considered in the length of the For example: >>> var = “Hello Python!” ‘#oncatenate two lists licated or repeated or repeatedly concatenated with the (list aList repeats three times own as slice string with the use of square braces (1) il substring which consists of letters bet adm nc niger and tering ta a letter from n* index to (m — 1) index. For example: >>> var = Hello Python’ SOT (COSemS & 4) >>> print var (0:4) 4 Similarly, o letters from n* index ie, sfterletter at n, that For example: >>> alphabet = “abedefghij” >>> print alphabet (1:8: $I beh # Output element at 1" index: is 3, it will will print ie, beh. ESBS] exetin the term indexing in Python. Indexing means referring to an element of an iterable by its position ‘within the iterable. For example : Create a list using a list comprehension: ‘my_list = (_for_in ‘abedefghi') my _list (at, ee, 8," 2, 91 ‘3. Now toretrieve an element of the list, we use the index operator (()) For example: my_list{0} Be {a Python, lists are “zero indexed”, so [0] returns the zeroth (i.,, the left-most) item in thelist. Inthe given example there are 9 elements in lst ( ‘we want to access my list9] thenit throws an inde of range 6 Python also allows to index from the end of the list usi i number, ive i onght intend Fen Gr, 18 negative indices, we start counting from the right instead 7. Negative indices start from~1, gh [8}) and if list index out Python Programming Pythons Data Structure : Tuples, Unpacking Sequences, Lists. ‘Long Answer Type and Medium Answer Type Questions Que Gas. | Define tuples. How are tuples created in Python ? Answer | 1. Tuples are the sequence or series values of different t S417 (CC-Sem-3 & 4) .s separated by can also be accessed by their index values, which are integers starting from 0. For example : ‘The names of the months in a year can be defined in a tuple >>> months = (January’, February, March’'April’, ‘May’, June’, July’ s-12T(CC-Sem-3 6 4) Geese eer aac, >>>tuple = 49, 6, house” TERBIGT] How are the values in a tuple accessed ? ‘Accessing values in tuples : I ers cats an partanicieng aaa ‘Tuple as return values : ‘ ‘Tuples can also be returned by the function as return values. 2 Generally, the function returns only one value but by returning! function can return more than one value. For example : If we want to compute a di Tan kzow the quotient and the remainder, both the quotient ent renee ner cn be computed at the same te, Two vals wile returned, ie, quotient and semuinde the tuple ast velo ofthe ineton under by uring he tun >>rdefdiv_mod(a,b); # defining function Python Programming 3.13 T (CC-Sem.3 & 4) remainder # function returning two values poy =3 TERRI eptain tne basic operation of tuples with example. Basic operations of tuples are : 1. Concatenation : The concatenation in tuples in used to concatenates two tuples, Thisia done by using + operator Python. $-14T (CC-Sem-3 & 4) Function: * >>pprint (3 0.2.3.4,5,67.8) # Output Repetition : The repetition operator repeats the tuples a| of times. Beppe in? operator in Python les. It tells user that the given ii Ifthe given input exists in the tuple, it ae tut, otherwise false. For example : >>otuple = (10, 20, 30, 40)” >>>20in tuple True # Output >>>50in tuple False # Output Interation : It can be done in tuples using for loop. It helps in traversing the tuple. For example: >>>tuple =(1, 2,3, 4, 5,6) >>> for xin tuple : print x vi RI yom enn eapmcingeanenrne ‘example to explain. SS T(CCSem3 & 4) the components of the sequence into nts can be performed simultaneously. 1ents in Python where sre can have multiple LHS assigned from corresponding values at the RHS. This is an example veer of unpacking sequence. Strings and sequences are: Indexing, repetition, conetenation A list is also a series of values in Python. Ina lst, all the values are of any type ‘The values in a lst are called elements or items. lists a collection of items or elements. ‘The sequence of data in a lst is ordered and can be secessed by their positions, i, indices. sseT(co-sem$@4) __Fuetions and Sting °88 20d Sting 2 # Output iS ‘>>> list [3] 4 # Output ‘quent | Explain the copying method in list. We can make a duplicate or copy of an existing list ‘There are two ways to make copy of alist. 1 Using[:] Operator: >>> list_original =[1, 2,3, >>> list_copy =list_original [] # Using [! operator >>> print list_copy 1,2, 2 Using built-in funetion : Python has a bui can be used to make copy of an existing list. 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 3,4] How elements are deleted from a list ? 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 : a Ifwe know the index of the element that we want to delete, then we can use the pop operator. For example : >>> list = (10, 20, 30, 40,1 >>> a= list-pop (2) >>> print list 120,20,40] # Output ate op operator deletes the element on the provided del es thst clement in a variable for further use. oy (eloperator: The del operator deletes the value on the provided : not store the value for further use, in copy function which rrder to use the copy ee index and Python Programming SATTCC-Sem-3 & 4) a. We use the remove operator if we know the item that we want to remove or delete from the list. For example: >>> list = [10, 20, 30, 40,] t (20,30, 40] # Output b. Inorderto delete more than one value from a list, del operator with slicingiis used. >>>print 1, 4,5, 6, 7, 8] # Output TERRA Diaciae bate in tnt operators in detail Answer Built-in list operators are as follows = 1. Concatenation : The concatenation operator is used to concatenate tovo lists. This is done by the + operator in Python. For example : >>>listl = [10, 20, 30, 40] >>>list2 = [50, 60, 701 >>>list3 = list +list2 >ooprint list 110, 20, 30, 40, 50, 60,70] # Output 2 Repetition : The repetition operator repeats thelist fora given number of times, Repetition is performed by the * operator. For example : >polistl = [1, 2,3] >>olist 14 0, 2,3,1,2,3,1,2,3,1,2,3) # Output 3 Imoperator : a. Thein operator tells the user whether the given string exists in the list or not. Functions and LI9T (CC-Sem3 £4) Gigaas python Programming bb It gives a Boolean output ie. true or false. pyitmaProwmmming OT ofthe given input exists in the string, it given true as oyiny : eee ora: >>olist = [Hello’, ‘Python’, “Program’] >>> Hello’ in list ‘A eT Ose Sor ist fe ices BEEBE] wre varons bast in nt methods. Explain nti pia with example. ‘>>>print list Taswer | te. 2.4,2,9) tDatpat Fert een Cn i i sn Python includes many built-in methods for use with list as shown in ‘Table 321.1. ‘Table 8.21.1. List of built in list methods. Fe = lis >>>print list 1. | emp(istl, list2) | It compares the elements ofboth ists, list] 1,2,4,5,8,91 # Output and list2. - - 2 | max (list) ‘It returns the item that has the maximum ” ‘value ina list. 3. | mindist Tt returns the item that has the minimum value in a list. 4 | list seq) It converts a tuple into a lis. 5, | listappend item) | It adds the item to the end of the list 6. | listcount (tem) | Itreturns number of times the item occurs in the list. 7. | listextend (eeq) | Tvadds the elements ofthe sequence at ‘GHETAA] what are mutable sequences ? Discuss with example. end of the list. aoe 6 [lin zemove item) | It delete the givenitom from thelist “Anawer | wel - ah 1. Fython representa alts data as objects, Mutabity of objects detormined sreverse() Tt reverses the position (index number byits type. the items in the list. 2 Some of these objects like lists and dictionaries are mutable, meaning wet wwe can change their content without changing their identi, 10. | list.sort ({fune]) Ttsorts the elements inside the list and) sable, compare funetion if provided. A. Other objects like integers, floats, strings and tuples are mmutshis, ‘meaning we cannot change their contents 1 Append method : This ‘anew element or item t0 °° ae method can add a new elemen! aero inedits, cing = non Programmi |L_ Dictionaries are mutable in Python = as mee 3-21 T(CC-Sem-3 & 4) ‘2 Dictionaries in Python are mutable. b Thevaluesin a dictionary can be changed, added or dcleteq 1 key is present in the dictionary, then the associat Sse eteet ia? fs apdatad or peed bers sao ie ue pairs added. 3 For example : >>> ditt = name’ ‘Akash, ('age’: 30, ‘name’‘Akash'} # Output >>> dictl('address] =‘Alaska’ # adding akey: value 6 In the given ext concatenate it wi thot have any effect on the origins Lists are mutable: ‘a. Lists are mutable means t list ean be chang 1m the original string and alue of any element inside the ible with their index value. and ends with n — 1, if the list contains n ele The syntax for accessing the elements ofa lists the same asin the case ofa string. We use square brackets around the variable and index number For example : >>>print dt i ‘ >>> list = [10, 20, 90, 401 (fage’ 30, name’:‘Akash’,‘address’:‘Alaska’) # Output ea Inthe given example, we tried to reassign the value ‘30’ to the key Python interpreter 20 # Output updateit. Hence, the value of ‘age’is updated to 30. Howev does not find the key ‘address’; hence, the key: value ‘address :‘Alaska is added to the dictionary. Strings are immutable : a String are immutable which means that we cannot change any element of a string. b. If we want to change an element of a string, we have to create a new string. For example : >>> var = ‘hello Python’ >>> var (0) =p) Output: ‘Type error: ‘str’ object does not support item assignment Here, we try to change the 0" index of the string to a character p, but the python interpreter generates an error. Now, the solution to this problem is to tor a new string rather generator a than change the old string. For example: >>> var = ‘hello Python! >>> new_var ='p' + var{1 ; >>> print new_var PelloPython # Output In the given example, we access the index number and the interpreter Now, if we want to change a value For example : >> list [3] =50 >>> print list 50] # Output the value of the 4% element is changed to 50. given in the example ymprehension is used to create a new list from existing sequences. tool for transforming a given list into another list, ‘expression that produces the same result. f list comprehension is based on set builder notation in Set builder notation is a notation is a mathematical notation for describing feb stating tho property that ts members should sab ‘The syotax n> for in if ] das “Compute the expression for each element inthe conditional is true”. 3-22 T(CC-Sem-3 & 4) ee For example: 10, 20, 80, 40, 50) (20, 30, 40, 50, 601 Without list comprehension Using list comprehension 5, Inthe given example, the output for both without list comprehension ‘and using list comprehension is the same. 6 The use of list comprehension requires lesser code and also runs faster 7. From above example we can say that list comprehension contains a Aninput sequence b. Avariable referencing the input sequence © Anoptional expression 4 Anoutput expression or output variable GaeSBA] wnat do you mean by sets ? Explain the operations performed on sets. ewer | 1. InPython we also have one data type which is an unordered collection of data known as set. 2 Asset does not contain any duplicate values or elements: 3. Operations performed on sets are: i. Union : Union operation performed on two sets returns all the elements from both the sets. It is performed by using and oP? Intersection : Intersection operation performed on ' - returns all the element which are common or in both the °t* performed by using ‘|’ operator. i Difference : Difference operation performed on two ts8th 0) set2 returns the elements which are present on set but Set2. Itis performed by using ~’ operator. , Symmetric difference ; Symmetric difference orer performed on two sets returns the element which are PTT py either set1 or set2 but not in both. It is perfor using * operator. ii, python Programming Py 3-23 T (CC-Sem-3 & 4) # Printing set 2, 4, 5)) ) # Output =setl &set2 # intersection of set] and set2 S>> union =setl | set2 # Union of setl and set2 >>> print union >>> difference = set1—set2 # Difference of set 1 and set >>> print difference set (18, 4]) # Output >>> symm_diff = set] * set2 # symmetric difference of set] 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 All other compound data types in Python have only values as their elements or items whereas the dictionary has a key : value pair. Each 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 valoes. ‘The mapping of a key and value is called as a key-value pair and together they are called one item or element. Akkey and its value are separated by a colon: ) between them. ‘The items or elements in a 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 a 88 S252 dictionary. ‘The vahiesin a dictionary can be duplicated, bt the Bers inthe Scoanscy are unique. TER BEA] tow do we create a dictionary in Python? 9-247 (CC-Sem-3 & 4) Functions nasi sumocsmaeo Picton ani Tome | a 1. Creating a' dictionary is simple in Python. 2. The valuesin a dictionary can be of any datatype, but the ke es STI be ,‘name’: Rahul) # Output Explain the operations performed on dictionary with ‘a. Traversing in dictionary is done on the basis of keys. b. Fortraversing, for loop is used, which iterates over the keysin the dictionary and prints the corresponding values using keys. ‘This example prints the key: value pairsin the dictionary dict 2 Membership: i Using the membership operator (in and notin), we can test welt ‘key isin the dictionary or not. i Inoperator takes an input key and finds the key in the diction” python Programming Python ee ——— 3-257 (CC-Sem-3 & 4) iii Ifthe key is found, then it therwise, false. For example: Sopeubes = (1:1, 2:8,3:27,4: 64,5: 125, 6: 216) S5> Bin cubes ‘True # Output >> 17 not in cubes ‘True #Output quia ‘Write some built in dictionary methods used in Python with example. ‘There are some builtin dictionary methods which are included in Python given in Table 3.28.1 Bees eect chor atc A coe T=) areas aa | aleraes Tinie amar a Rei ip lpeatacn Sencar a as the dictionary. 4 | empldicti, dict2) | Ttcompares the items oftwo dictionaries, 5 | sorted ied) 6. | dictlear() Tereturns the sorted lst of keys. Te deletes all the items in a dictionary at Tt returns a copy of the dictionary 1._| diet. copy) & | dict get (key, default = None) 9. | dictitems() 10. [ dict keys Te returns the list ofall the keysin dictionary 11, | ict pate (dick2) | Tada the items from dict to det TE returns al he waves inthe distionny [22 [ diet values 3-26 (CC-Sem-3 & 4) Funeti saeTicCSem-$&4) _Fivetions and Sting, For example : Soocubes = (1: 1,2: 8,3: 27,4: 64, 6 : 125, 6: 216) >>>all (cubes) a # Output, >>>any (cubes) True # Output >>plen (cubes) # Output # Output Output | Higher Order Functions: Treat Functions as First-Class Objects, "Lambda Expressions, 2 In Python both functions and classes are treated as objects which are jects, allowing them to be manipulated in the same By definition, first class objects are the following which is a. Created at runtime b. Assigned as a variable or in a data structure © Passed as an argument to a function 4 Returned as the result of a function For example, let create and test a function, then read its_doc_ent check its type. >>> def factori returns n! return 1 ifn <2 else n * factorial(n ~ 1) >>> factorial (4) python Programming pease eT CC Sem3.4 4) +14950061177528798985431426032445115e0s3636400c00000 ‘>>> factorial. doc __ “returns nt" >>> typelfactorial) 4. The console session in example shi Here we create a functio that the function object itselfis an instanc qaesa0-| Explain Lambda expression, ewer | a cits cit tin morc c 2, The anonymous functions are the functions created using a lambda keyword. Python functions are objects, 5_doc_attribute, and check the function class 3, They are not defined by using def keyword. For this reason, they are called anonymous functions, “We can pass any number of arguments to a lambda form functions, bat still they return only one value in the form of expression. 5. Ananonymous fimetion cannot directly call print command as the lambda needs an expression. Tt cannot access the parameters that are not defined in its own namespace. ‘An anonymous function is a single line statement function. & Syntax: Jambda (arg! (,arg2, . son argnl] ; expression ‘The syntax of the lambda function is @ For example : # function definition here >>>mult =lambda vall, val2 :vall*val2; 4 function call here >>> print “value, mult(20,40) ‘Value:800 # Output de pete jven example, the lambda function is de eae ae ne een rll ral? des the mutans {wovalies, Now, in fanetion call we can directly al tbe mol SO ‘with two valid values as arguments and produce| the output as shown in given example. -28T (CC-Sem-3 & 4) Functions en = Sena An Sting, GEESE] Eoplain higher order function with respect to tay expression: Write a Python code to count occurrences ofan tent seme, ARTU 2019-20, Maria “Answer { Reducel), filter, mapt) are higher order functions used in Python ition does not include a “return” stat 2, Lambda definition does not a ‘contains an expression which is returned. it alway 4. We can also put a lambda definition anywhere a function is expec ‘and we do not have to assign it to a variable at all. nected 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( fanction 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 from an inputllist : 4 Python code toillustrate filter() with lambda liz (6,7, 22, 97, 54, 62, 77, 23, 73, 61) final_list = list(filter(lambdax: (x%2!=0),1i)) print(final_list) Output = (5, 7,97, 77, 23, 73, 61) Use of lambda() with reduce() : 1. The reduce() function in Python takes in a function and a list 2° argument. ‘The function is called with a lambda function and a list and a ni reduced result is returned. This performs a repetitive operation the pairs of the list. ‘This is apart of functools module. For example: 2 eh F, ofalist #Fython code to illustrate reduce() with lambda() to get sum o ‘python Programming see __ 3297 (CC-Sem.3 & 4) Here the results of previous ees and this goes on till the end vowels count element count = vowels.cour # print count print(“The count of # count element ‘p’ ‘count = vowrels.count(‘p’) print count ; print(“The count of pis’, count) Output : ‘The count of iis: 2 ‘The count of pis: 0 je 8.82, | Explain unpacking sequences, mutable sequences, and list comprehension with example. Write a program to sort list of dictionaries by values in Python ~ Using lambda function. (Aer aoe ar) Answer Unpacking sequences : Refer Q. 3.16, Page $-14T, Unit-3 Mutable sequences : Refer Q. 9,22, Page 3-19T, Unit List comprehension : Refer Q. 3.23, Page 3-21 Program : 4 Initializing list of dictionaries ‘ame” : “Nandini”, “age” ; 20), ‘name” : “Manjeet”, “age” ‘name”: “Nikhil” ,“age” : 19 ‘using sorted and lambda to pri brint “The list printed sorting by Print sorted(lis, key = print (*\r") yee ’,eount) ‘using sorted and lambda to print lst sorted by both age and name Print “The list printed neaiae Print sorted(lis, key = lambda print (*\r")_ ‘using sorted and lambda to print list sorted by ago in descending order Print “The lst printed sorting by age Print sorte key = lambda i: il descending order” reverse=True) python Programming —___ #27620 UM ety cgecndce: ae re eh, fage. 20, oame' Man andini’}} list printed sorting by age in descending order: 20, ‘name’:‘Nandini’), age’: 20, ‘name’: “Manjeet FRESE] weit a tunctionin Aad the HCF of some given num zz rs, >>odef hef (a, b) : ifa>b: small =b else small=a for iin range (1, small + 1): if(a %i ==0) and (b %i ==0)) valent” s>rbin oct hex (10) = B ining binary, octal, hex vy (Cob1010;, binary equivalent’) ‘iat oe ee ‘octal equivalent’) (xa, hoxadecimal equivalent’) 60 hef =i return hef >>> hef (20, 40) 20 #Output >>>hef (529, 456) 1 #0utput « 1d) Write a function to find the ASCII value of the character. >>>def ascii_val_of (a) print (“The ASCII value of * + a+” is", ord (a)) #Output >>>ascii_val_of( #Finding ASCII value of spac (The ASCII value of ‘’ is", 32) #Output: its TEBE] Write « function to convert a decimal number fe binary, octal and hexadecimal equivalents. Sieve of Eratosthene, and File Vo CONTENTS Part-1 Sieve of Eratosthen 4-27 to 447 Part-2 ; File VO: File Input and... 4-4T to 4-77 ‘Output Operations in | Python Programming Part-3 : Exceptions and Assertions - AAT to 4137 41ST to 4177 Part-4 : Modules : Introduction, . Importing Modules, Abstract Data Types : Abstract Data ‘Types and ADT Interface | in Python Programming Classes, Special Methods (Such as_init__, _str_, Comparison Methods, Arithmetic Methods, ‘te.), Class Example £ Tnbpritanee ferninnmnsminimmraronncnee Inheritance and OOPS A1TICOC Rem d) 427 (CC-Sem-3 & 4) 4, Following is the algorithm to find all the prime numbers less than or 5 snes’ method Que 42. | Explain Sieve of Eratosthenes with example. equal to Eazy 1. Let us take an example when n = 50, So, we need to print all print ‘oumbers smaller than or equal to 50. 2 We create a list of all numbers from 2to 50. PART-1 Sieve of Eratosthenes, gern by Be ra desntii] ey tt uf 2 fas [a [5 [ie [a ai] 22 | aa | 24 [25 | 96 | 27 ai] 2 | 33 | sa | 35 | 98 | 37 ai] 42 [43 | 44 [| a5 | a6 [ 47 ttn Programm __—_——_— = + gman aie rua the guar Fa aeemiemmcenia7 |e Tee) na | mee eas tT [P18 [as fas a | 27_| a eae Roce eos wone| S75 | 38 _ POE iG EETT , ,. T a r aeuaen zoe | 47 | a8" pext unmarked number 3 and mark all the numbers 4-AT (CC-Sem-3 & 4) Sieve of Eratosthenes and File /O rime, else true. (ns) , 1 while (p * p <=): 4# If prime(p] is not changed, then itis a prime 4, Now we move tooo Now Were multiples of 9 and are greater than or equal it sien rene asim ste |S | 8° [aoe ope - Tar | 28° # driver program ee ee (ea fede 2s eed | are | 28 29 oe sin ar ae [oor | oer | 35 | 96° | 37 | Ser aD eps [a [ae Le a print “Following are the prime numbers smaller”, print “than or equal to”, x 5. Wemoveto our next unmarked number 5 and mark all peieecoimransteaaastey ahd are greater than or equal to the square of it Soul aie eden igies Mee ee | Pee PART-2| | Gi faze a3 | a4 [ase [aoe | a7 | 19 119 2 File 1/0 File Input and Output Operations 21 [22 | 23 | 24* | 25+ | 26 | 27 28 | 29| 30 in Python Programming. ai [az | aae | 34% | 35° aa la | 43 ee | ase [aoe | ave | 48 36° | 37+ | 387 | 39*| 40° 49 | 50° We continue this process and our final table will : peal amen esos | 7 | 8 tr faze | aa | a4 [ ase | s6* | 17 | 18° fate [2a | 23 | 24* | 25% | 26+ | 27" | 28° 31 [a2 | ae | a4r | a5 | a6 | 37_| 98° ai faze | aa | a4e | 45* | age | 47 | 48 So the prime numbers are the unmarked ones :2, 3,5, 7,11, 18,1 31,37, 41, 43, 47 Write a Python program to print all prim than or equal to n using Sieve of Eratosthenes. def SieveOf Eratosthenes (n) : # Create aboolean array “prime(0. .n)" and initialize # all entries it as true. A value in primeli] will 7, 19,23 .es smaller GHETAD] Wat are fies ? How are they useful? Answer] 1, A file in a computers a location for storing some related data. 2. thas a specific name. 3, The files are used to store data permanently on toa non-volatile memory (such as hard disks). 4. Aswe know, the ‘Access Memory (RAM) is a volatile memory type because the data int is lost when we turnoff the computer: Hence, we use files for storing of useful information or data for Future reference EGFR] Describe the opening a file function in Python. python Programming a. Filename the file which we want to te Access_mode : The value of access_mode specifies the m toe re wrant to open the file, ie., read, write, append ete,” 3 Syntax: file_object = open(file_name |, access_mode]) For example : >>>f= open (*test.txt”) #Opening file current directory s>>f=open (*C/Python27/README. txt”) ‘#Specifying full path Output >of open file‘C/Python27/README.txt’, mode at 0x02BC5128> Output Gee] Explain the closing a file method in Python. 1. When the operations that are to be performed on an opened file are Puiched, we have to close the fle in order to release the reso 2. Python comes with a garbage collector responsible for cleanit tnreferenced objects from the memory, we must not rely on i afile. 3. Proper closing ofa file frees up the resources held with the fle 4. The closing of file is done with a built-in function close 0. 5. Syntax: fileObject. close () For example: # open file >>> f= open “test, txt”, “wb") # perform file operations >>> f.close() # close the file TERRA | Discuss writing to a file operation. Here we 2, Inorder a case the file already exists # open the file with w mode poe f= open ("C sPython27itest.txt”,“w") # perform write operation >of write (‘writing to the file line Un’) Spek. write (writing to the file line Yn’) >of. write (writing to the file line /n’) >paf. write (‘writing to the file Ene 4) # clos the file after writing >>> felose 0) ‘The given example creates a file named test txt ifit does not exist, and Groterites ito iit exists Ifwe open the Se, we wil nthe fl content in it. noe Output : Writing to the file line 1 Writing to the file line 2 Writing to the file line 3 Writing to the file line 4 WESRA] explain reading from file operation with example. Answer | In order to read from a file, we must open the fle in the reading mode (r mode), ‘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 ofthe fle. ‘The read() method enables us to read the strings from an opened Sle. Syntax: file object. read ((sizel) For example: open the file Sertng? # Ontrat wri ead (@) # roadnext Cyto oats ‘tothe’ # Output ERT Piecuse ste On Python. How to perform open, read, Sita lor into nile? Write a Fyihon program to reeds i tine-by-line store it into a variable. (Rien 2018-30, Marks) 4. rae cena, write and close into a file: Refer @. 4%, Dase 4-41, eer grke. Pagel4-8T, Rafer Q. 4.7, Page 4-57, and Refer Q. 46, Page 4-5T; Unit. ‘Program : L = [Quantum \n’, “for\n", “Students \n") ‘writing to file filel = open(myfile.txt’, ‘W’) ‘int(line.strip()) print(*Line():()" format(count, line.strip0)) Output : Linel: Quantum Line2: for Line3: Students (CC-Sem-3 & 4) EOTWCC Hema 4A Sieve of Rratnthenes and File LO FTI deserve sserons 5. The syntax for assert is: assert Expression |, Argumental 6, Ifthe assertion fails, Python uses ArgumentEsxpressicn as the argument for the AssertionError. For example = Consider a function that converts a temperature from degrees Kelvin degrees Fahrenheit. ieee ne epee: aor eripd function fails iit secs a negative temperature Wyuser/biprpython ‘assert (Temperature >= 0). return ((Temperature — print KelvinToFahrenbeit (-5) ‘Traceback (most recent call last) File “test. py’, line 9, incmodule> print KelvinToFahrenbeit (-5) File “test.py”, line 4, in KelvinToFahrenbeit assert (Temperature >=0),"Colder than absolute sero!” AssertionError : Colder than absolute zero! BERR wnat ao you mean by exceptions ? Aaewer | 1. While writing « program, we aften end up making some errors. There ‘are many types of error that can occur ina program. a For example, Whenever an exception occurs in Python, it stops the current P “ae Rt ee 499 py writing an improper syntax i ter caused ‘The error cau ied compile time err: or parsing error: Errors can also occur as exceptions _ Fees ore vastnuntypien of rants error ia PYEHCD ‘ghen a file we try to open does not exist, we get g For NotFoundError. When a division by 20r0 happens, we get ¢ Fel tjlonBror, When the module we are trying to import does not exist, we get an ImportError. Python creates an exception time errors. ‘The user mi Ifitis not capable of to that error along wi For example: ‘Compile time error (syntax error) these are also call at runtime and these runtime errors are knoyn object for every occurrence of these run ust write a piece of code that can handle the error. yhandling the error, the program prints a trace back th the details of why the error has occurred ppp aad spp if(a <4) # semicolon is not included ‘SyntaxError invalid syntax # Output ZeroDivisionError + >>25/0 Output : ‘Traceback (most recent call last) File “cpyshell#71>”, line 1, in 50 ZoroDivisionError : Integer division or modulo by zero Explain exceptions handling with syntax. rocess ‘and passes it to the calling process until it is handled. Ifthere is no piece of code in our program that can handle the exceptio™® then the program will crash. For example, assume that a function X calls the function Y, uaee turn calls the finction Z, and an exception occurs in Zt tis exeoR isnot handled in itself, then the exception is passed to ¥ and thenton Ifthis exception is not handled, then an error message will display" and our program will suddenly halt, 307 CCSem-3& 4) eee i. Try..except: fa. Python providesa try statement forhandli b, An operation in the program that can caus placed in the try clause wl the exception is placed ¢. The block of code for handling the exception is wi tuner and itis for him ta decide which operation he waste to perform after the exception has been identified. Syntax: wy the operation which can cause exception here, he exception is le that handles, except Exception! 1 if there is exception1, execute this. except Exception? ifthere is exception2, execute this else : ifno exception occurs, execute this. ii, try finally: ‘a. The try statement in Python has optional finally clause that can be associated with it. b. ‘Thestatements written in finally clause will alwaysbe executed by the interpreter, whether the try statement raises an exception or not. ¢ With the try clause, we can use ether except or finally, but not doth. ‘We cannot use the else clause along with a finally clause a Wee >>otry: file = open(“C:/Python27/test.txt”,“W") file write(“hello python”) exceptIOError : print "Error: cannot find file or read data else: > print “content written successfully” a python Programming AU T(CC-Sem3 a, Sn al cC-Sem-3 & 4) iene nearer eur as tatesn mode, and want to write ‘to that file. We have added ee except blocks. 2. Ifthe required file is not found orwe donot have the permission to wri, tithe file, an exception is raised in is handled by the except block and the following statement 3, Theexcel 4. On the other hand, Output : ‘Content written successfully GET Give example of try.--finally. poo try ‘i file = open(“testfile”,“w") try file.write(*Write this to the file") a é file.close() “ exceptlOError: pprint “Error Occurred” 1. Inthegiven example, when an exception raised by 2 After all the statements inside the onError is raised when an EERIE] Discuss exceptions and assertions in Python. How to sendle exceptions with try-finally ? Explain five builtin exceptions aa (aso Mo Tower] Exception : Refer Q. 4.11, Page 4-8T, Unit-4. ‘Assertions : Refer Q. 4.10, Page 4-8T, Unit-4. 5. Handle exceptions : Refer Q. 4.12, Page 4-97, Unit-4- ce oF assignment Five built-in exceptions : {exception LookupError : Tis is the base class fr how exceptions falls suchas when «non af Sr ereare rior inne n emeninge = for example : invalid or not found. The exceptions raised are : class Attributes(object): a KeyError pass object = Attributes() b IndexError Print object.attribute 413 T (CCS, Python Programming : CC-tema ey Output : 4) ‘Traceback (most recent call aop4295abe62dal14ae7a7.py”, line 5, in ute rattributes object has noattribute attribute’ ' : PPART-4 ke Modutea: Introduction, Importing Modules, Abstract Date Type wectvat Data Types and ADI Interface in Python Programming, QueAAG.| Define the term modules. 1. AmoduleisfilecontainingPython definitions and statements module an define functions, classes and variables. 2, Itallows.us to logically organize our Python code 3. The file name is the module name with the suffix py appended. “ Amodule can also include runnable code. Grouping related code into module makes the code easier to understand and use 5, Definitions from a module ean be imported into other modules or into ‘the main module. For example : Here is an example ofa simple module named as support PY defprint funcl par): print “Hello :”, par urn 17, | Explain the import statement with the help of example Dre caters e i ot rasa way oftovacn Oe machinery, 2, Animport statement is made up of the import keyword along with the ‘name of the module 3. Theimport statement combines two operations; it searches module, then it binds the results of that search to a name scope. aT (CC-Sem-3 & 4) ue For example: ‘to import standard module math import math printThe valve of Bis”, math pi Fyisscime ran the program, the output wil be ‘The value of iis 9.141592653559709 SIE cpinin abstea GaeAAB| Explain abstract data types with its types. eon) 1. Abstract Data type (ADT) isa type for Dyavet ofvalue and a set of operations one bavows deed ‘There are three types of ADTs is +The data b, Stack ADT: iii The head node and the dat d the data nodes are encapsulated in the . The calling function can only see the pointer to the stack. in stack, it, The program al 1s the memory for storing the data. REEGAGT] explain ADT interface in Python programming. a ADT only defines as w ions are to be performed but not bow ., ssopeations willbe ted fi specify how data will be organized in memory and'what : Sentaas will be used for implement the operations Its called “abstract” because it gives an implementation-independent

You might also like