Download as pdf
Download as pdf
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!

You might also like