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

Python Programming

Python quantum

Uploaded by

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

Python Programming

Python quantum

Uploaded by

Aditya Tiwari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 97
Se Cpe eta Ta irks ETT in Question-Answer form. + Short Questions (2 Marks) UNIF1 : INTRODUCTION TO PYTHON (1-1 V to 1-23 V) Python variables, Python basic O,erators, Understanding python blocks. Python Data Types, Declaring and using Numeric data types: int, float ete. UNIT-2 : PYTHON PROGRAM FLOW CONTROL CONDITIONAL BLOCKS (2-1 V to 2-25 V) Python Program Flow Control Conditional blocks? if, else and else if, Simple for loops in Python, For loop using ranges, string, ist and dictionaries. Use of while loops in Python, Loop manipulation using pass, continue, break and else. Programming using Python conditional and loop blocks. UNIT3 : PYTHON COMPLEX DATA TYPES (3-1 V to 3-39 V) ‘Using string data type and string operations, Defining list and list slicing, Use of Tuple data type. String, List and Dictionary, Manipulations Building blocks of Python programs, string manipulation methods, List manipulation. Dictionary manipulation, Programming using string, list and dictionary in-built functions. Python Functions, Organizing Python codes using functions. UNIT-4 : PYTHON FILE OPERATIONS (4-1V to 4-20) Reading files, Writing files in python, Understanding read functions, read(), readline(), readiines(). Understanding write functions, write() and writelines() Manipulating file pointer using seek Programming, using file operations. CE scanned with OKEN Scanner ———_ UNITS : PYTHON PACKAGES AV 5-3 5 0 Simple programs using the bulltin functions of packages aplotib, numpy, pandas ee. GUI Programming: Titer introduction, Tkinter and Python Progremming Tk Widgets Tainter examples. Python programming with IDE ‘SHORT QUESTIONS. (50-1 V0 SQ-a1y) SOLVED PAPERS (2019-20 TO 2022-23) (SP-1V to SP-20V) Introduction to Python _ 1-8V to1-4¥ Partl + Python Variables Part-2 : Python Basie Operators LAV to 1A2V Understanding Python Blocks ABV to L13v 1-14V to 1-180 Parts: Hython Data Types Parte : Declaring and Using Numerie noo T1BV to 1-280 Dota Type" int, Float ote. AV(CC-Som-3.& 4) a aa scanned with OKEN Scanner _ 1-2V (CC-Sem-3.& 4) 1 Se Python Variables, 1. Avariable holds a value that may eh change. ‘The process of writing the variablename iscalled declaring the vara lec variable, 3 In Python, varia tn Pron, vals do not ed oe dred eye reserves in other progeariing langues ke C, 4. When we initialize the i lize the variable in Python, Python Tate automatieally does the desaraion preeas Ten TPE Initializing a variable: 1. The general format of assignment statement is a fellows: Variable = Expression 2. The equal sign (=) is known as assignment operator. 8, Am expression is any value, text or arithmetic expression where as ‘Variable isthe name of variable, 4, Thewalue of the expression will be stored in the variable. Example of initializing a variable 016 35> name=Albort” ‘The toe given slateinents reserve wo momar spaces with variable nae ‘or6 and Albert, are stored in these memory speee What do you understand by local and global vari bles Local Variable: ‘A local variable is declared it by the funetion in which ii Example: 2 deff 2 #local variable 3g. S=*Tlove Python” ide a specif uneion andeanonybe oe declared. sav (CO-Sem-5.& 4) ee : Sepeivreade a tne ewe ora Eeavanaie Chobe Vavinles ad arial noe tat Agile, be acon Beam ae): its etn" stb sone Sevtiove Ptan” " Ff enteoutie neo’ 8) Fane shove came, Sinlbal arable ple, we have delared S inside the fanction Hence it is saecared” outside ofthe funetion in Progra ‘by any of the functions os co aera aaa age pane a parca ep ws erecta aes a Reet aera Seen ea om eS oe the code. the function. ny ee ae Fg |e mg Petr PS lace [geaemocnisfneres Eat yw 7 Was Joma aerate ‘e other functions of the aa scanned with OKEN Scanner 1-4 (CO-Sem-3& 4) Introduetion to Python triton to Prt ‘Que1s. | Write python program to swap two numbers without ‘wsing Intermediate/Temporary variables. Prompt the user for input. ARTU 2081-22, Sem-4j Marks 10 ‘Answer | 4 Prompt the user for input ‘num = intfinput(“Enter the rst number: *)) ‘num2 = intiinput(“Enter the second number: )) ‘Swap the numbers without using a temporary variable uml = num + num2 ‘num? = num - ume ‘sumt = num = num2 (Print the swapped values prini{"After swapping, th frst number is fnumi}*) Drint(FAfter swapping, the second number: (nam) ee PART-2 Python Basie Operators, Si eee ata QueTA ] Define the term operator, ae) 1 bp operator asa ht ropresents an operation that ‘ered ae mor opran TN at mn pear aren medi the vans operands. Orato tha ks one operand raed yoo Orne tha tak tv opr ald ay operas, eed on Sto orate aces ellie eaeN Arithmetic operators Assignment operators. ‘Bitwise operators, Comparison operators. ‘entity operators, Logical operators, ‘Membership operators. fae eR ee ich is"T ‘GaI Discuss various categories of operators in python. Find Paap cass ase Various categories of operators: afer @. 1.6 to @. 1.10, Unit ‘According to operators precedence we wil evaluate the expression as ov, the expression becomes a & b > 9>5.25"e%2 Step sb >25 hichis 1-SV(CC-Sem-38'4) and explain stepwise solution of following expressions if a=8,b= 5, bosatea oobee2%erS a&b< 252 +e" follows Step 2: 225 which ie 0.08, now the expression becomes a & b-<0.08 + Nos, the expression hocomes 1 < 0,08 + e*b 05 + 100000 whieh is 100000.08 According to operators precedence we will evaluate the expression as So, the expression becomes b>> 9 >>b™*24e™"3 Stop 3:e°"3 is 10°3 which i 1000 1 Now, the expression bocomes 1°1000 eto. (AisrO 20B2 5, Sem Mas 10] i=l Given values :a=3,6=5, Step 1:5°2895 a Step4e%i 10° which s 100000 nally 1 10000.08 which true flows Step2str2ie Sa whichis the expression becomes b>» >> 2551000 a the expression becomes >> 2661000 Step 821100 whichis 1000 scanned with OKEN Scanner V (CO-Sem-3 & 4) Introduction to Python ‘QeETET] Discuss arithmetic and comparison operator with example. asiners Arithmetic operators : These operators aro usd to perform arithmetic operation suchas adation, subtraction, maitipcation and ison ‘Table 1.6.1. List of arithmetic operators. Gus. | Explain assignment operator with exampl Taawer ‘Assignment operators: This operators used t stare right side operands inthe lef side operand. ‘Table 1.7.1. Lis of assignment operator Description x __ | Multiplication operator te multiply two operands |10 x 20 = 200) 1 Division operator to divide left hand by Tight hand operator. s+ | Beponential operator tocaleulate power Description Example jparator + [Adaitin operator to ad two operands 10+ 20-99 = | Storerightside operand in left side operond, = _ [Subtraction operator to subtract two operands, [10-20 =10] T= [hd right aide operand to Tet wide operand and store the rosult in lot side operand Subtract right side operand to left side operand and store the result i loft side operand =| Multiply night ede opera with left side operand | nnd store the result in lft side oparand %___|Modulus operator to find remainder, 5a2-1 512-9) 11 | oor division operator to find the quotient and remove the fractional part Comparison operators:These operators are used to compare values. Is also called relational operators. The result ofthese operator i alway’ Boolean value ie. rue o flee ‘Table 1.6.2 List of omparieon operators, Iperator| ‘Description Tape == | Operator to check whether two operand | 10==20, foe are equal Teor [Operator to check whether two operand | 101=20, true are not equal > | Operator to check whether Grst operand | — 10>20, fle {greater than seeand operand, | Operator to check whether rst operand is Smaller than socond operand, >= | Operator to chosk whether frst operand {greater than or equal to second operand, ‘Operator to check whethor First operand Ta [Divide loft side operandby right side operand and store the result i lef side operand Find the modulus and sive the remainder in left side operand Find the exponential and stare the result inlet side operand "Pid the Noor division and store the result in eft side operand Quoi, | Detine nie newer Bitwise operators ‘These operators perform bit level operation on operands. Let us take two operand x= 10 and y = 12. Iu binary format this ean be ‘written asx = 1010 and y ~ 1100, a//=bor i= enalld operator ith exampl scanned with OKEN Scanner ov (CC-Sem-3& 4) 18V(COSem-3.& 4) Introduction to Pythoy Python Programming am ‘Table 1.92. Listof identity operators Table 1.81, List ofbitwise operators are Faample (aameer aa Beam i ne ie | Return tro, ifthe operands are same. | sy, results else feBitwise |This operator performs AND operation| x &y results Return fle, ifthe operands are not AND between operands, Operator copies bit same Prvvassee etheoweands ae ttle | Return fle, ifthe operands are same. | xnotiny, results trad TBitwise This operator porforme OR operation |= | y reals 1110 Return true, ifthe operands are not OR between operands. Operator copies Iitifitexistsineither operand membership operator with example. |" Bitwise [This operator performs XOR operation|x *y results 0110 | XOR between operands. Operator copies [bit iit exists only in one operand. |-titwise [This operator en unary operator used | 2 vonlla 0101 inverse _ftoinverse the bits of operand > results 0010, bits towards right | ‘QUETR! ] Diseuss logical and identity operator with example eae Logical operators : These operators are used to check two or more ‘conditions. The resultant of this operator is always a Boolean value. Here icine Desoeetien ae This operator performAND operation | x and y results fal [between operands, When both operands are true, the resultant besome true. lor logical | This operator perform OR operation OR | between operands. When any operand Istrue, the resultant become true. ‘ory results true ‘ot «result fale hot logical | This operator is used to reverse the NOT | oporandstate. Identity operators : These operator are used to check whether both operands are same or not. Suppose x stores a value 20 and y ores a value 40. Then x isy returns false and x nati return true. 1. Those oporators are used to check an item or dn oloment that is part of string alist ora tuple 2 A momborship operator reduces the effort of searching an element in the lit. A. Suppose.r stores. a value 20 and yi the list containing itoms 10, 20, 30, and 40, Then xis apart ofthe listy because the valve 2 ‘Table 1.10.1 List of Membership operators, Description Eom ing, results true [operator] i __| Return rao, item isin lst orin sequence, Return false, if tem is not inlistor in sequence, ‘otin |Returmialse, itemisinlistorin. | noting, resulte roa uence. Return true, ifitem is ot, inlist or in sequence, ‘Que 11] What is short circuit evaluation ? What is printed by the following Python program 7 ‘a=0 bee e=3 print 2) ‘ARTU 3030295) Sema Marke 10] scanned with OKEN Scanner -10V(CC-Sem-38 4) “Anew: |L_When the evaluation of a logical expression stops because the overall value isalready known, itis called short-circuit evaluation 2 When Python detect that there is nothing to be gained by evaluating ‘ho rest of logical expression, it stope its evaluation and does not do the ‘compotations in the ret ofthe logieal expression, For Example: ‘When Python is processing a logical expression such asx >= 2 and (xy) 2) evaluates the expression from lft toright, Because ofthe definition of ond fx isles than 2, the expression x>=2's ales and c the whale Introduction to Python ‘exprestion is False regardless of whether (iy) > evaluates to True or Fale. print) Output 3 ‘QueiA2. | What do you mean by operator precedence ? ea When an expression has two or more operator, we need to identify the correct soquonce to evaluate theso operators. Thies because result of the expression changes depending on the precedence For example: Consider a mathematical expression 1045/6 ‘When the given expression is evaliated left to right, the final answer becomes 3. 2. However, if the expression is evaluated right to loft, the final answer Decomes 11, This shows that changing the sequence in which the ‘operators are evaluated in the given expression also changes the solution. 8 Procodenee is the condition that specifies the importance of each operator relative to the other. i peti v (CC-Sem-3& 40) Python Programming ‘er precedence to hither. ‘Table 1.12.1. Operator procedence from lower Pre Operator Description NOT, OR AND Logical operators _| in not in [ Membership operator isnot ~[ enti operator ‘Acsimnment operators. quality comparison operator ‘Comparison operators Biuwise XOW and OR operator Bitwise AND oporator ‘Bitwise loft shift and right shift ‘Addition and subtraction ‘Multiplication, Division, Modulus an face division a | Exponential operator ‘GueLil | Explain operator associativity, =a Associativity 1. Assosatvity decides the order in which the operators with same precedence are executed 22 There are two types associativity: Left torright: Ia oft to right aeosiativity, the operators of same precedence are executed from the left side frst. 1b. Rightto left :tnright to lef associativity, the operators of same precedence are executed from the right side fest 8 Mostoftho operators in Python have Jet toright associativity. 4. Left toright associative operators are multiplication, Noor division, ete, ‘and * oporatorisright to left associative. 5. When to operators have the same precedence then operators are evaluat fom lft to right direct ee For example: >os4i/6 2 v ovtpat scanned with OKEN Scanner [_ 1-12V (CC-Sem-$& 4) Introduction top poo 394/16) 0 F Output 1-1sVv(CC-Sem-3 & 4) poo geearee #9816 Tnewer ‘046721 # Output TiaglesEine TMaliine perryrt #8" = eae (Eee 6051 # Output contains a single| t consists of multiple 1] Seton] emt “an is |statment ani indnted WERTH] what do you mean by operator precedence ay sateen tien on{by indentation, extending aaa lover several lines. associativity ? Explain, ARTO 2021-22, Semis Masia Sesame ine ae ie ue ap tino Operator procedence :Refer Q.1.12, Page 1-10V, Units 2 Suitable for short and Trereetepjoperations to Operator associativity : Refer Q. 1.13, Page 1~11V, Unit-1, nea | enhance readability. consistent PARTS es is required. indentation for — all Undervanding Prion Blocks Hatements within he lock Easier to meintain and ‘Minimal indentation] Require ‘Que 115; ] Explain Python blocks, How do you define a block of code in Python ? ine 1 Alockin Python isa group of ne or more statements tha pefrma specific task. oS 2 locks are defined by their indentation, which provides structure to fhe program. y ‘Indentation in Python is important as it defines the scope ofa Hack ‘nd helps to keop the code organized, " 4. Forexample, consider the fllowing code itxso Prints positive”) sxe1 5, Inthis ode, the block is define i {ute he locks dened by tho indentation of the two sates She block starts with the ie print is positive”) and ends withthe 7. Thestatements within th block w he enditen ‘pected intheifclausetemen, NY beoxesuted ithe Que 1.16. | Differentiate between singlo-tine block and multiline block. & | Maintainabiity Gan be harder to| modify and debug| when multipl Statements are needed, modify due to clearer structure, 8. | Clarity Clear when the ‘operation is concise and doesn't span ‘multiple lines Offers a clearer! visual separation of code blocks and steps. ©.» 6. | Brrorhandling| Might be more challenging to identify and» ix] structured layout. Hisicto identify and correct errors due to the crrors within.a single line. Example | ifeon: ifeondition= x=5 ye10 In this example; bath x = 5 and y = 10 are part of the sameblock because they are indented under the if| statement. scanned with OKEN Scanner Python haw six basic dats types which aren fllows L Numerie 2 String 3 tie 4 Tuple 5. Dictionary 6 Boolean Numeric: 1. Nomerie data can he broadly divided into integers and yal sustees (pi ftactional mamibers) Integers caste pate ercepatve f 2. The real numbers or fractional mumbert are called, Nosting joint i in programming languages Such Mating point autora | a decimal and a fractional part, Poe olga (. Seo numl «2 inter ssl >oonum2 = 2.5 @ real number (leat! sooremt 2 output _ 2s Output strings 1. Blogl qusts co dub ques are wet represen rng 2 Astring in Python can be a series or a sequence of alphabets, numerals atopci characters 16V(CCSem3 & Fyn Preemie oo For exampie' s sos sample string = "Hhelie® Watere etring waboe ssosample string # display string vale ‘ete? Output Gar LIE] Discwes thet and tuple date types im detail, ‘Anewer List: £Alitenn conta the aame type of terms 2. Akernatively.a fit eam alan contain diterwes goat iia. 2. Aliatie an orders and indousble aequence | Tosdectace a latin Python, we na to septate Data ning Pomme Aandercloge them within aguare brackets (FD. + such as concatenation, sepetition sod eb ht are done on plore) anteruik(*}andiahicing O epeentor: For example eofiat [19,20 ae” 1 tat sooaccond « [five", at at gn seotiet duping Bt two! 8.0, foal) # Outpat ‘Tuple 1 Atuple in algo med to store sequence of item 2 Likealist, atuple consuts of tems separated by conten, 3 Tuples are enchaed within patentheten father than within square brackets For example + >oothind = (7, eight". 9, 10.09 Soathind , (Teight,9, 100) Output ‘QUeTAB:] Hepa dictionary and ootean data type. eevee] Dictionary : 1A Python dictionary isan unordered ealleetion oMkeywealoe pare 2 we Whee wv ave the lange amount of data the dictionary datatype ix a Keys and values canbe of any type ina dict scanned with OKEN Scanner idniadefn aici savicosemsee tsi ith ope icaeeeealinioee este cee es ei Sets tread te eae Sid omnia amssuscals wi I Hadas acca gl WE dn Space nemo a ed he mo ie papa ig gM ure fgmeenee i). ESE Be nan, Tatras tent antna | For example: oe i | >>> type (ad 1 | ctype ‘bool > \ ‘TaeTaRT] wi dose moan ty pe cnvstion Anower |) “The process of\Converting one'dataltype into another data type is Kaowivas type conversion, 2 ‘There aré mainly two typos of pe conversion methods in Python Implicit type conversion : i. Whon the datatype convettion takes place during compilation or during the run time, then i called an implicit datatype fi Python handles the implicit data type conversion, so we do not have to explicitly convert the data type into anather data ‘ope. For example: ass b=55 um = 0.4 b i | | print sum) LTV (CC-Sem3& 0) Python Programming prin (type (um) # type is sed to display the data type of Variable Output: 105 ae fi, Inthe given example, we have taken two wariables of int and float datatypes and added them. lv. Further, we have declared another variable named ‘sum’ and stored the result ofthe addition init " ‘v. When we checked the data typeof the sufi variable, we ean see that the data type of the sum variable has been ‘tomatieally converted into the float datatype bythe Python Compiler. Thi ie called implicit type conversion. Explicit type conversion: " i Bxpliit type conversion is aldo known as type casting. ‘ype conversion takes place when the programmer cleacly and explicitly defines the variables inthe program. For example: 4 adding string and integer data types using exiittit type b="200" 4 result =a result2=a+b print renul2) Output ‘Traceback (most recent all last): File“, tine 1, in ‘Type8rror: unsupported operand type (=) for #: ‘int! and'sts? 300 5 In th vn example, te variable a ofthe number data ‘Speand verb sath srg date ore '% When toad the fe intagers and ware the val a ‘variable named result, eins Perio his operation 2 Type ror occurs. So, in order 10 ‘have to use expliit type casting. ariable into integer type and then stored in the variable scanned with OKEN Scanner LBV (CC-Sem-3.& 4) Introduction to Python ‘Gael | What do you mean by Boolean exprossion ? “Anwor Boolean expression : A boolean exproscion may have only one of tp values True or False. For example In the given example comparison operator (e=) is uscd which compares two operands and prints true if they are equal otherwise print false veo Ban ina sis (ccSem-3 & 4) Python Programming For example: b=50 peint(“\Type ob", tpetb)) ‘Output: ‘Typo of: Complex numbers complex class. fComplox number is represented by a compl oe «A caperifiod (eal part + (imaginary part) For example 2435 For example: cn2+d) print(\atype ofe:",typeteD) Output: ‘Type of : PARTS FETE] What will be the output after the following IDiarhgchd Ungar Di Type nt Pot te, ee ste Que 1.22. | How do you declare numeric data type in python ? yes tf Z Primes ame] ae 1 Then dligypinPtonreprvetsthdtathathasationere | 20 aes laoe can ho an intago, a Moaing number or even a QuOTRL] What will be the output after the following complex number. statements ? a tages: a 1 “Thgyatuts rereentd bya Primos) 1 conan pantie or noatve whole ner (without faction ex esa) Si. In Python, thers no ita how Tongan integer val san be. weemmcis: What will be the output after the following 2 printtype of" type) Outpt ‘ypoctas be Float : i This value is represented by the float class. x * i" Iisaealaomber with flatng print repeentation Stein apcited ny adecinal point scanned with OKEN Scanner -— | Python Programming (| 1-20 (CO-Sem-3& 4) Introduction to Pytig | Learv(co-Sem-3& 9) " lowing Qioias] what will be the output after the following pce attas ota wing | Queiai.] What will be the outpr statements? | =a] ae E— ve x= True | ime y= False | — ‘print(not x) I Answer : False othe output after the following a | Qaeiaa] What will be ‘QueIR7] What will be the output after the following 023%! Wh statements? statements? oie False zag printinot eint(x te y) penn?) $ newer What will be the output after the following ‘Que T29.] What will be the output after the following | QueTS4&] What will be the output after the following statements? ‘statements? x= True x6 ge y= False y=53 rint(x and y) 2nyil%2==0)clsex aaa printia) False } | ‘QueTS0.] What will be the output after the following | | statements be the output after the following x=True y= Falee print(x or y) Iniwer Troe scanned with OKEN Scanner _"—s—‘i ;PU;] lt ] savqusess0 __isstiimang 1-25 (CC-Sem: | Python Progenmming == eet | ‘aaa a have the value ‘GEETEET] What wil be tho output ater the falling aa eas oswahne tae ant wire statements? a al int) | Gas TAE] i th order of precedence which ofthe operat — | ye completed last In the following statement 7 "annwer Sieveeara ae ‘Tawwer | QEeTAT] What will be the datatype of + after th fllowing. Stirctin ‘statement if input entered is 18? | Qectas.| x= input(‘Enter a number) | pe se sntcancat ? ‘Answer | rosa-1 48/5: fen | “Rawr ‘QaeTAL] What wil be the datatype of y after the follwing Mslintin Dison, Aiton, Subrtion ; statements if Expat enberes{te BO 7 Gueida:] What will be the data type of = after the following pa statement if input entered is 647 Sfimrtiapulebaier «number | ——_ | Trower | oat What will be the data pe of y afer the following GueTas.] What will be the outputafter tho following ao” | statements? a | NIST7Stea eae vane | print) Aaeree ‘Anawer ad 160 GseTAG.] What will be the output after the following) QueiaG] What will be the output after the following statements ? | statements? zeyet=8 asa/aa7-33 print print) ‘Answer ‘Anower 8 ano Gow TAT] What wilt be the value of and = after the following statement ? 200 | . — G scanned with OKEN Scanner ——_—— — lltt—~— Python Program Flow, Control Conditional Blocks | CONTENTS Sf else and elseif. 2:2 to 21V, ‘Simple for Leops in Python, PHY to 2-15 For Loop Using Ranges String, List and Dictionaries. 25V to 217 ‘Use of While Loops in Python, cw. STV to 2-22 Loop Manipulation Using Pass, Continue, Break and else 2.22 to 2-25V ‘Programming Using Python eons Conditional and Loop Blocks 21V(CCSom3&4) onal Blocks 22 (CC-Sem-3& 4) Python Program Flow Control Conditional BOSS PART-1 ‘ifielse and elec if ‘GasBi, | What are conditional statements in Python ? sedis! ‘statements help in making a decision based on certain cae ns are specified by a set of condition sfeménts havit Erotica a oon niece Sanaa igentenansre ren reasons 2 = a Ifstatement e. Nested:ifstatement Quoz2, | Explain ifstatement with the help of an examples 1. An ifstatoment consists of a Boolean expression followed by one or ‘more statements, 2 Withanifetause, a conditions provided: ifthe conditions true then the block ofstatement writen inthe if elauge will be executed, otherwise 3 Syntax: (Boolean expression): Block of ode #8 of statements to exoeute if the condition is true 4 Flow chart : ‘Statements of if block ren ofthe code scanned with OKEN Scanner o_o For example: var=100 if (car ==100): print value ofexpresions 100° print "Good bye Output : ‘value of expressions 100 Good byt GaeTS. | What do you mean by: the help of example. newer 1. Anifstatement ean be followed by an optional cls statement, which texceutes when the Boolean exprossion is False, 2. ‘The else condition is used when we have to judge one statement onthe basis other. 3 Syntax: ‘se statement ? Explain with ements to cxocuteil istrve ‘hse: Block of ode Wet of statements to execute if eondition false 4, Working and execution: 7 ‘The condition wil be evaluated to a Boole expression (tre fale). ‘yo 1rthe Gndition is true then tho statements oF program prese! Inido the ifblock will be executed 11'the condition is false then the statements or program pres {nid else block wil be executed. Flow chart: Falee Tree Statement of a Blatement oboe exvicosnst_ Brien neon cn nn A Torereni aaa torn (Number is greater than 10°) clse: print (‘Number i lese than 10") print This tatemont will always be executed”) Output ‘Numbor is Tess than 10, GuedA, | Discuss the Nested ifstatement with thehelp of example. newer a 1, Nostedsif statements are nested inside other ifstatesionts, That i ‘ated statement isthe body of another ifstatement. 2, Wousenestedifstatoments when we needto cheek secondary conditions ly i the it condition executesas true: 8 Syntax: After expression 1 ‘executes when condition 1s true body off statement iftestexpression 2: ‘executes when eon Body of nested else body of nested it: #Firstifetatement iffa<25): Print (ais smaller than 25°) lee sta, MBER grentr than 257 print a ienot equal Output: San ‘is amaller than 25 a scanned with OKEN Scanner Python Programming £468:00 Sema, ? 8) yccosema&) Python Prgram ow Control Conon] ESS 4. Flow chart : a Sate Perepanta in Ht woah ea canta ibaa Boaretat t Byers eae re Body of nested else Bor eft] ¥ ‘ hos Sa | AN [Tae] plan ott eed in Python ayes on Explain all the conditional’statement in Python using suiall code a V8 example TATU Bb, So arcane] fe ‘Answer .! teat atonal vatrment on L Ifstatement : Refer Q. 2.2, Page 2~2V, Unit-2. ecmeeenane eer 2 encanto aor 23: Po— 2, U2 1 Nested:ifsiatement: Refer Q. 24, Papo 2-4V, Unt-2 Fore & Hlfoatoment: ; im re pant hte fin Psn ~ erate . afr ing eee alin caada stan ae on Working and execution : Pie Crane ofvarahe ats 7) Pe ether ieondtin true, tbe ie ie aatement Othervze, en ow ae print a i oninchbaneatrehecks rere Qutnae; Hreatement vale of variable : cote he is grater than 40 sa rth condo str the prnram wllexeut | Ain cn tocol andt | QE. | Weite program ond whether & nambe body ofthe lf ate ae nk amd RE | gag, sets aren ce ERotoay ete ea boc oven program will exocute the ‘eof variable ais greater than 40") scanned with OKEN Scanner —a_—_"" i. 2 ~~} Python Programming BTV COSema ay “Answer >>> number = int (input “Enter an integer number) >>> iF(aumber % 2) == 0: print “Numbers even” else print “Number s old” Enter an integer number : 6 Numbers even, ‘output Quek. | Write a program to check the largest among the given three numbers. >>> x= int (input “Enter the frst number Enter the first number: 14 >> y= int (input (Enter the second number") Enter the second number: 21 ‘So> 4= int (input ‘Enter the third mumber ")) Enter the third number :10 oo if y)and (x> 2) lex ‘elifty > and > 2) tey lee: ies >>> print “The largest among the threo 8", 1 ‘The largest among the three is 21 aos] Write » Python program to check ifthe input ver ist (ar ST] #utput teap year or not. Tower | Conditional Blocks eV (CC-Sem-3&4) Python Program Flow Control else: : priot (year, isnot leap year) lee! print (year, isleap year) le print year, ‘sleapyear) ‘Output : ‘Bator a year : 2016 2o16is leap year Output: Boter a year: 1985 1986 i not Ieap year Gueds. ] Write a Python program to display the Fibonacci sequence for n terms. oR Write a program to produce Fibonacei series in Python. “AKTU 2021-22, Sem-&j Marke 10 Answer 5 25> number = int Gnput “Enter the value for x Gwhere 2 >) 7) first the terms pord-1 >>> count = 2 ‘check f the numberof terms i vali >>> if numbers <=0: Print (Please enter postive integec") prin (Fibonacci sequence is) >> year = int Gnpot *Entar year") bores dor if year % 4) == 05 rene ‘if year % 100) fem ome: if year % 400) == 0: = print (year ‘sleapyee) riot (ath) — scanned with OKEN Scanner Python Programming 2OVCCSemsa, ‘update values Output: Enter the value for a (where n> 2)710 Fibonace sequence : 0,3, 1,2,8,5, 8,18, 21,94 Que210: | What will be the output after the following statements? x=70 fx <= 30 or x >= 100: print(true’) lif x<= 50 and x == 50: print(not true’) elif x >= 150 oF x <= 75: print(false) elses ‘print(not false’) Poa false tional Blocks ps0v (CO-Sem-5&4) Python Program Faw Controt ond nave — ogram Flow Conteh Oe print(t) ‘GueBia | what will be the output after the following statements? x=50 > : itx> 10 mndx 15: print(true) elifs> 15 and x <25¢, rintCnot trac?) ‘TonTAT] wnat wine th outputaitorthfllowingstaemests?’ ett asandxe doe aearrima! rea : Hey se 100 ‘Drintnat fae?) xey>e 3 printtrae?) a curry en et false Drintcnot true) Seta (Qse 2] What willbe the outputafter the following statements ? Drinetfalse? = o . ifx>t0andx<15: printcnot false? oan les Band 5 25 ne print‘not true’) = 4 Hifx> 25andx print) Rew] elite == 18: a G scanned with OKEN Scanner Python Programming 211V (COSem-I 84) ‘Que 26. | What will be the output after the following statements? x15 ifx> 10 and x 1Gand x <2 print(not truo’) lif x> 25 and x <35: print(‘false’) elses peint(not false”) al true PART-2 ‘Simple for Loops in Python, For Loop Using Ranges. Que2A7, | Define loop. Also, discuss the purpose and working of loops. “Answer 1. Albopisa programming structure that repeats. sequonce ofinstructons ‘until a specificcondition is met. 2 Albop statement allows usto execute a statement or group ofstatements ‘multiple times. 18, Python programming language provides following typesofloopsto handle ‘ooping requirements: a Pr White Nested 4. Purpose: The purpose ofloops iso repeat the same, or similar, ode 8 ‘number of times, ‘This numberof times could be specified to acartain ‘Humber, er the numberof ims could be dictated by acertain condition, being met. Working : Consider the flow chart fora loop execution a. Inthe flowchart ithe test contin struc, hen th lop isexecuted, ‘and if is false then the execution breaks out of the lop. 1b After tne loop is successfully exceuted the exerution again starts {rom the loopentey and ngnin checks forthe tost condition, and thi keeps on repeating until the condition i fale. 4A. Flow chart : e12v(ccsems&4) out ef Loop QueBI&] Explain for loop with the help of example. ‘newer ee tia Tor bop in psthoa is used to oxeeute block of statements or code Sooner antl tho gives condition becomes fale. 4. Were fr lop when we low the numberof times to tera Syntax 3 for variable in sequence: Ba Body of for lop Entering for loop foreach items in sequence 2 Body of for loop scanned with OKEN Scanner = tt Python Programming 2ISV(CO-Sem3.a.4, For example: int for in range, 8) print 21 Output: 2 4 6 8 10 2 “ (Que 218: | What is nested loop ? Explain. ae 1. Loop defined within anather Toop is known as nested loops: 2 Nested lope are the lopa that sre nested inside an existing Loop thai, nested loops are the body of another loop. 8 Syntax: for eénditionl: for condition? Body of for loop 4. Forexaniple: for iin range(9.2) for in rangelt): priot(i, end print) Output: 1 393 55565 a977777 _Pybon Program Flow Control Conditional Blot 214 (CC-Sem-3 8 0) Foeaan] wet pat Python program to construct the following torn, using a nested for loop. [aeRO aa ow RTO] Program : pos fori in rangetn): forjia ramget prat™"end=) print for in range(a): forj in ranged): sit print(*end="") od print) ‘Que2HT | Write and explain an algorithm through python code to ‘ARETO B0R2- 25, Semi Marka TO ‘generate prime numbers. meee y A prine aunber S's natural musket whic gator than 1 and has no Dostve divisor oer than andl sah as 3, 87,1, 13, and soot Algorithm Step 1:10 through all the elomenta athe gi ‘Step 2 Check fo each number iit has any factor between 1 and ite 8 : If yes, then the number is not prime il x Sten Ie then the numbers ot prime, and it wll move tthe nest Step 4 fo, iti the pri number, an lpi Step 4 fo tah pre number. an th program willprntitand ches Step 8 Theluoy wl break when i reac Code: 4. Ae, we willtake the ing 2 lowor_value = int(input (Please, Ent Elona Enter the Lowest Rango Vatu wed tothe upper value. ins Pe Ener per Rea ae scanned with OKEN Scanner Python Programming 248V(COSem-3.&4) 4. print The Prime Numbors inthe range are:*) 5. for number in range (lower_value, upper value +1) : 6 ifnumber>1: 7. foriinrange (2, number): 8 ‘if (aumber i) = 0: 9, ‘break 10. else aL ‘Print (number) GaeBBE] Reptain range (function, How do you use for loop with range 0 funetion in Python ? Answer 1. The Python ranged function retirns's sequence of numbers in a given ‘range. The most common use of it to iterate sequences on a sequence ‘of numbers using Python loops. 2 Syntax ranestar, top sep) Parameter i Slat: {optional start yal tbe soqence Stop: next vals arth end valu of th sence Stop: {optical inter vale, donating the ifrencebween ay eR altos Rati turin het that rpreeot gesqene of sunbars ». Renney altel of ode fo lof the values in range. for xin range(6) printix) 5, The range() function defaults to 0 as a starting value, however it is possible to specify the starting value hy adding a parameter: ranget2, 8 ‘which moans values from 2 to 6 (but net including 6) amide aes 2 “String, List and Dictionaries, ated See ean eae Didoodrie a ‘What do you mean by the term strings ? (CC-Sem-38&4) Python Program Flow Control Conditional Blocks td within quotes. Python seer nising vacate d seers bren Ege utes a dowle eo 4. Stomper ofr er lar'pe The thas interpetr teats he matador 4. Sulagn inten canes ata ig data eo lori serSSecemed inputs, Thismeke stings really wef and eases poo varl = "Holle Python!” >>> var2 ="Weleome to Python Programming!” >>> print varl HelloPython! # Output o> print var? ‘Welcome to Python Programming! # Output ‘Que Bx | Write short note on list: lists also seties of values in Python. Ina lis, all the valles ara of any type. ‘Tho values in alist are called elements or items. Alistis a collection ofitems cr elements, The sequence wf datain a el erred aid can be acted hy thei ‘positions, te, indices. pe For example: >>> list 1,2, 3,4] >>> list [1 2 # Ovtput >>> lst 4 Output Que235,] what =a] nat vn i ecco npal ec art ier ‘value is associated with a key, ae a Aictionary in Python ? ction of items or slements, scanned with OKEN Scanner Program Mow Control Candia Blok Python Programming PATV(COSem344) eisvicc-sem-se4) Python A Indletonary, we bave keys and they can be of any type, awake sion 4 Distionsryinsidtobeamapringbetween somo rtofkeysandvag,| a. The program rtevatuaes the whileloopcODdO% 5 ‘Thomapping ofa key and vali calle asakey-valse pair na 1 ifititroe then the program ater the loop they ae called oe item or element Pete mae Reel sigue 6. Akay and its valu are separated by colon: between them, e Teeontinues to execute the body ofthe 1% The temsor elements ina dictionary are separated by commas an cede frie cout of the loop and stor odeabantensteyrane emg amon tof ely 8 A pairof curly braces with no values in between is known as en ene, | repeating the body o dictionary. aI For example: | pescount 0 lctionary ‘The valuesin a dictionary ean be duplicted, but the kéys athe, are unique. 5 PART-4 Loop in Python, Loop Manipulation Using Pass, — Continue, Break and Bee, | Eee ‘Que 226. ] Discuss while loop in brief. aes ‘While lop stateroent in Python are used to repeatedly execute acta Use of While hile (eount <9) print ‘The count is, count Explain the following loops with a flow diagram, syntax, and suitable examples i For I it wisie “ARTU 2099-25, Sem; Marks 10 Answer For loop : Refer Q. 2.18, Page 2-12V, Unit L statement aslong atthe condition provided imho whleloopstatonen’ i, While oop fer @. 2.26, Page 2-17V, Unt 2. istroo 2. While loops let the program control to iterate over a block of code. SORES: | Want Mt beenk statement tn y 3 Syntax: Kamer while test_exprestion: | 1. Thebreak keyword terminates the loopani transfers the control to the ‘nd oF while sido he loop. 4 Flow chart 2 Wile lop, far oop can alo be promatorely terminated using the break statement 8 The break statement exits fom the loop and transfers the execution from the loop the statement tht is immediately fillowing the loop, For example: >>> while True Print ount ‘ifcount > = 12: = hroak # breaks te loop ———————_ scanned with OKEN Scanner —_—_—_—_—""——s—( ee Python Programming 219V(CCSem3a.g Output: 2 4 6 8 10 ‘Que228, | Explain continue statement with example. Answer 1. The continue statement causes execution to immediately continue a the start ofthe lop, f skips the execution ofthe remaining bay parte the oop, 2 ‘Thecontinve keyword terminates the ongoing iteration and transfer tho control to the top ofthe loop and the loop condition is evaluated ‘again. Ifthe condition is true, then the next iteration takes pace. 3, ast as with while loops, the continue statement can also be used ix Python for ops For example: >>> for iin range (1,10): ifinzino ‘ontinge #fcondition hemes tre, ips the pent part print Output : 2 4 6 8 ‘ue 230, | Explain the purpose and working of oops. Discuss break and continue with example. Write a Python program to convert time from 12 hour to 24-hour format. ([BieTT 2010-20, Sem: 3; Marke 10] “Answer Purpose and working of loops : Refer Q. 2.17, Page 2-11V, Unit-2. Break statement : Refer Q.?.28, Page 2-18V, Unit 2. Refer Q. 2.29, Page 2-19, Unit-2 tional Blocks -20V(0CSem-3& 4) _ Python Program Flow Control Cond Program Function toconvert the date format defconvert24letr1): ‘¢Checking if ast two clements of time # is AM and first tw 2 ar AM and ste itstrsl-2: return *00"+ str1(2:~21 fr remove the AN lfstell 2 return strtl:-2) ‘+ Checking fast two elements of times PM and first two elements are 12 lifstel[- 21 ==°PM" and str1[-2] == "12": return stril--2) sii le: (add 12 to hours and remove PM return stint strIL-2) + 12) + 3tr11281 Driver Code print(convest241°06:05:45 PM) ‘Que 2.1. | Write a program to demonstrate while loop with else. >>> while count <3 print (“Inside the while loop") print (count) counter = count +1 lee Drint Taside the clue statement”) ‘Que 232, | Dicierentiate hetwoen for and while loop, scanned with OKEN Scanner _ intinite times. nidalization| In Tor loop the iitialization| Jonce done is never repeated. compilation eror. In while loopfinitialzation i done during condition ‘checking then initialization i one each time the loop iterate. QueZSs, | Explain the continue, break, and pass statements with [RRSTU BORE, Sem-3; Marks 10] oR Explain the use of break and continue with a suitable example. iam Continue : Refer Q. 2.29, Page 2-19V, Unit-2. Break : Refer Q. 2.28, Pare 2-18V, Unit2 Pase: 1, The pass statement is used as a placsholder for fature 2. When the pass statement is executed, nothing happens, getting an error whon empty code isnot allowed. 14. Empty code is not allowed in loops, fonction definitions, lass definitions orinifstatements. For exampl a suitable example. code, but you avid sonal Blocks PRIV(CCSemI&H — 5 say (cC.Sem-B&4) _PythnProgram Flow Control ond ifn> 10 z 5 pase ire ae 8 print(Hello) ation, condition| Only initialization an i tio iL Caanent| ag] What willbe the output after the following statements? are writen atthe top of the| top ofthe loop. er Kies fission |e mt ee er lope ues only when |The ‘hil’ oop is used onl ends we already knew the number| when the numberof trating Baar ofiterations. are not exactly known. RECERT Geatitin [Wine aodiientnngventalirdmesiibnistersrent|] GEESE] Hor loop, then loop terates|‘whilo’ loop, it provides| | 112368 é Que Z3E | What will be the output after the following statements 7 xel whilex <4: aed yer while y <3: printty, end=") yee ‘Answer 121212 ‘Que 236: ] What willbe the output ater the following statements ? xya35 while y= printy, ends) xed yeed “Answer 1045, eee [PARTS | 2 Programming Using Pythan Conditional él Loop Blocks. scanned with OKEN Scanner ‘Que 2.87. Write a program to check an input number is prime op not, ARTUR, Sea Maa] | “Answer . AdotPrime Checker: # Chocking that given number is more than 1 ifa>t: #Tterating over the given number ith for loop for j in range(2, intla/2) + 1): ‘Ifthe given number is divisible or not tapp=o. print(a, “isnot a prime number") break, (se itis « prime number se: print, “isa prime number") # Ifthe given number is 1 bse: rinta, “isnot apriie number") ¢# Taking an input number from the user ‘= intGinput(“Enter an input number:") # Printing result! PrimeChecker(a) ‘Output : Enter an input number:17 Tis prime number Develop a program tocaleulatethe reverse of any entered ARTO 202225, Sem-9; Marka 10) number. 7 4 Ack for enter the number from the use 2-24 (CC-Sem-9& 4) _ Python Program Flow Control Conditional Blocks BUVCC EE) Hine ‘pumnber = int{input("Enter the intoger number: ‘Initiate value to mull revs_number = 0 ‘reverse the integer number using the while loop ‘while number > 0) remainder = number % 10 revs number = (revs number * 10) + remainder number =mumber 10 Display the result print(“The reverse number is)" format(revs.nyimiber) Output: Enter the integer mumber: 12545 ‘The reverse numbor is 54921 ‘Que20. | Explain expression evaluation and float representation. ‘with example, Write a Python program for how to check if a given number is Fibonacci number. [AKTU201930, Som; Marks 10 “Answer e ¢ Expression evaluation : Out of syllabus from session (2028524) Float representatiot : Out ofsplabus from séaion (2028-24), Program : import math Z 4 Autilty function chat returns true fi pele square def isPerfectSquare(x): Ss int(math.sgrt(x)) . return sts ‘Returns true ifn is a Fibonacei number, else false AefisFibonaceiin return isPerfectSquare(S*n’n + 4) or isPerfectSquare(6* ‘* Autility function to test above functions {or in ranget1,6) if GsFibonacsii)== True) "nn 4) scanned with OKEN Scanner Python Programming print isa Fibonaeei Number” le: print is a not Pibonacei Number” Output ‘Lisa Fibonacei Number Bis aFibonacei Number ‘is Fibonacei Number 41s anot Fibonacei Number ie Fibonacei Number eee 2-25V(CC-Semd & 4) Data Types Parts Parts String Operations Part-2 1 Defining List and List Stcing Use of Tuple Data Type, vse String, List and Dictionary. Manipulations Building Blocks of ... S-18V to 8-28V; Python Programs, String Manipulation Methods, Lict Manipulation, Dictionary Manipul Part-6 + Programming Using String, List and Dictionary in-built Funetions Part-6 + Python Functions, Organizing... Python Codes Using Functions S.8V to EUV. Su11V to S-18V ” 8-28V to S-26V. 3-26V to s-s0v 3-1 (CO-Sem-2.& 4) scanned with OKEN Scanner

You might also like