Libkviit.files.wordpress.com



COMPUTER SCIENCE APRIL MONTH HOME LEARNING MATERIALSPLITUP SYLLABUS FOR APRIL MONTHUNIT-1 Programming and Computational Thinking ? CHAPTER-1 : Revision of the Basics of Python?CHAPTER-2 : Functions : ( Basics)CHAPTER 1 : REVISION OF BASICS OF PYTHONPython was created by Guido Van Rossum when he was working at CWI (CentrumWiskunde & Informatica) which is a National Research Institute for Mathematics andComputer Science in Netherlands. The language was released in I991 Python0.9v ( v stands for version). Python got its name from a BBC comedy series from seventies- “Monty Python?s Flying Circus”.It is free to use.Python is influenced by ABC& Modula 3Features of PythonSome of the features which make Python so popular are as follows:It is a general purpose programming language which can be used for bothscientific( ex:-NASA) and non scientific programming.It is a platform independent programming language.It is a very simple high level language with vast library of add-on modules.It is excellent for beginners as the language is interpreted, hence gives immediateresults.The programs written in Python are easily readable and understandable.It is free and open source.It is easy to learn and use.Variables(Objects) and TypesWhen we create a program, we often like to store values so that it can be used later. Weuse objects to capture data, which then can be manipulated by computer to provideinformation.Variables are memory locations used to store data.Every object has:A. An Identity, - can be known using id (object)B. A type – can be checked using type (object) andC. A valueA. Identity of the object: It is the object's address in memory and does not changeonce it has been created.(We would be referring to objects as variable for now)B. Type (i.e data type): It is a set of values, and the allowable operations on thosevalues. It can be one of the following:Python Data TypesThere are different types of python data types. Some built-in python data types are:Python Data Type – NumericPython numeric data type is used to hold numeric values like;int – holds signed integers of non-limited length.float- holds floating precision numbers and it’s accurate upto 15 decimal plex- holds complex numbers which are made up of real and imaginary numbers. They take the form ‘x+yJ’or ‘x+yj’ (note x and y are float values)All numeric types (except complex) support the following operations, sorted by ascending priority (all numeric operations have a higher priority than comparison operations):OperationResultx + ysum of x and yx - ydifference of x and yx * yproduct of x and yx / yquotient of x and yx // yfloored quotient of x and yx % yremainder of x / y-xx negated+xx unchangedabs(x)absolute value or magnitude of xint(x)x converted to integerfloat(x)x converted to floating pointcomplex(re, im)a complex number with real part re, imaginary part im. im defaults to zero.c.conjugate()conjugate of the complex number cdivmod(x, y)the pair (x // y, x % y)pow(x, y)x to the power yx ** yx to the power yIn Python we need not declare datatype while declaring a variable like C or C++. We can simply just assign values in a variable. But if we want to see what type of numerical value is it holding right now, we can use?type(), like this:a=100print("The type of variable having value", a, " is ", type(a))b=10.2345print("The type of variable having value", b, " is ", type(b))c=100+3jprint("The type of variable having value", c, " is ", type(c))print(c.real,c.imag)print(c)Boolean(bool):Boolean data type represents one of 2 possible values True or Falsex= 10>2print(x)y=8<2print(y)Output:TrueFalseString(str):A string is a sequence of characters that can be a combination of letters , numbers and special symbols enclosed within single quotes ' ' or double quotes " " or triplequotes "' '"str=”hello world”print(str)None:This is a special datatype with single value.None keyword ?is a special constant in Python. It is a null value. None is not the same as?False. None is not?0. None is?not an empty string.x = Noneprint(x)C) Value of variableTo bind a value to a variable we use assignment operator (=)x=100 X ---- Name of variable100 ---- Value of variable2004 ---- address(id) of variable100We should not write 100 = x #this is an errorThere should be only one value to the left hand side of the assignment operator . This value is called L-value.There can be a valid expression on the right hand side of the assignment operator . This expression is called R-Value.The Statement: L-Value = R- Value is called assignment statementMultiple Assignments :We can define multiple variables in single statement. It is used to enhance readability of the program.Multiple assignments can be done in two ways:Assigning multiple values to multiple variables:var1,var2,var3,…. , varn=value1,value2,value3,…..,vlauenEx:- x,y,z=21, 43,56 is equivalent to x=21 y=43 z=56Assigning same value to multiple variables:var1=var2=var3=…. = varn=value1ex:- total=count=0 # it will assign total and count to zeroComments: (Single line & Multiline), Continuation statements,Single LineComments are lines that exist in computer programs that are ignored by compilers and interpreters. Including comments in programs makes code more readable for humans as it provides some information or explanation about what each part of a program is ments in Python begin with a hash mark (#) and whitespace character and continue to the end of the line.# This is a commentBecause comments do not execute, when you run a program you will not see any indication of the comment there. Comments are in the source code for humans to read, not for computers to execute.Multiline Python CommentPython allows comments to span across multiple lines. Such comments are known as multiline or block comments.# To Learn any language you must follow the below rules.# 1. Know the basic syntax, data types, control structures and conditional statements.# 2. Learn error handling and file I/O.# 3. Read about advanced data structures.# 4. Write functions and follow OOPs concepts.Explicit Line Continuationuse the line continuation character (\) to split a statement into multiple linesx= 1+2+3 \ +4+5print(x)Implicit Line ContinuationImplicit line continuation is when you split a statement using either of?parentheses ( ), brackets [ ] and braces { }. result = (10 + 100 * 5 - 5 / 100 + 10 )print(result)Python Character SetCharacter Set is a set of valid characters that a language can recognise. A character can represent any letter , digit or any other symbols.Ex: Letters : A-Z , a-z Digits:0-9 Special Symbols like . , " ' : () [] {} + - * / = white spacesToken A python token is smallest individual unit in a program/script that is meaningful to interpreter.The following categories of tokens exist in python:Keywords,Identifiers, Literals, Delimiters, Operators.Keywords:Keywords are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only except .Keywords in python:FalseclassfinallyisreturnNonecontinueforlambdatryTruedeffromnonlocalwhileanddelglobalnotwithaselififoryieldassertelseimportpass?breakexceptinraiseIdentifiers: The name of any variable ,constant,function or module is called an identifier.Rules for naming identifiers:Rules for writing identifiersIdentifiers can be a combination of letters in lowercase?(a to z)?or uppercase?(A to Z)?or digits?(0 to 9)?or an underscore?_.?Names like?myClass,?var_1?and?print_this_to_screen, all are valid example.An identifier cannot start with a digit.?1variable?is invalid, but?variable1?is perfectly fine.Keywords cannot be used as identifiers.Identifier cannot use special symbols/characters( LIKE . , whitespaces)except underscore(_) Identifier can be of any length.UPPER CASE and lower case letters are different as python is case sensitiveIdentifiers can start with underscore( _ ) or a letter.DelimitersDelimiters are symbols which are used to separate values or enclose values.Ex: - ( ) { } [ ] : ,OperatorsA symbol or word that performs some kind of operation on given values and returns the result.Ex: + - * ** / / % =LiteralsA fixed numeric or non numeric value is called a literal. Ex:- 10, 20.3, “abc”, ‘xyx’, TrueLiterals -Escape sequence An?escape sequence?is a?sequence?of characters that does not represent itself when used inside a string literal, but is translated into another character or a?sequence?of characters that may be difficult or impossible to represent directly.Escape Sequence Description \\ Backslash (\) \' Single quote (') \" Double quote (") \a ASCII Bell (BEL) \b ASCII Backspace (BS) \f ASCII Formfeed (FF) \n ASCII Linefeed (LF) \r ASCII Carriage Return (CR) \t ASCII Horizontal Tab (TAB) 0\v ASCII Vertical Tab (VT) \ooo Character with octal value ooo \xhh Character with hex value hhExpressions and OperatorsExpressionsAn expression is combination of operators and values(operands). An expression is evaluated to a single value.Ex:- 5+2 *4 =13Converting mathematical expressions to python expressions4b 4*by= 3 (x2) y= 3 * x/2a=x+2b-1 a=(x+2)/(b-1)Operators Operators can be defined as symbols that are used to perform operations on operands. Types of Operators 1. Arithmetic Operators. 2. Relational Operators. 3. Assignment Operators. 4. Logical Operators. 5. Bitwise Operators 6. Membership Operators 7. Identity Operators 1. Arithmetic Operators :Arithmetic Operators are used to perform arithmetic operations like addition, multiplication, division etc.Operators Description Example + perform addition of two number a+b , 15+ 25- perform subtraction of two number a-b , 35-10/ perform division of two number a/b , 21/4* perform multiplication of two number a*b 2*3% Modulus = returns remainder a%b 17%3// Floor Division = remove digits after the decimal point a//b 17//3** Exponent = perform raise to power a**b 3**2-Unary minus-3Types of operators based on no. of operands:Unary operator: takes only one operandBinary operator: takes two operandsNote + is also used for string concatenationRelational(comparison) Operators :Relational Operators are used to compare the values.Operators Description Example == Equal to, return true if a equals to b a == b != Not equal, return true if a is not equals to b a != b >Greater than, return true if a is greater than b a > b >= Greater than or equal to , return true if a is greater than b or a is equals to b a >= b <Less than, return true if a is less than b a < b <= Less than or equal to , return true if a is less than b or a is equals to b a <= bWe can use relational operators in following way also:a<b and b<c can be represented as a<b<c3. Logical Operators Logical Operators are used to perform logical operations on the given two variables or values. In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:?False,?None, numeric zero of all types, and empty strings(‘’) and empty containers like tuples(,), lists[], dictionaries{}). All other values are interpreted as true.Operators Description Example and The expression?x?and?y?first evaluates?x; if?x?is false, its value is returned; otherwise,?y?is evaluated and the resulting value is returned.Syntax :- x and y >>> 3>2 and 7>5True>>> 5 and 88>>> 0 and 80or The expression?x?or?y?first evaluates?x; if?x?is true, its value is returned; otherwise,?y?is evaluated and the resulting value is returned.Syntax :- x or y >>> 3>2 or 7>5True>>> 5 or 85>>>>>>>>>>>> 0 or 88not The operator?not? returns ?True?if its argument is false,?False?otherwise.Syntax: not expression4. Assignment Operators & Short Hand(Augmented ) assignment operators: Used to assign values to the variables.Operators Description Example = Assigns values from right side operands to left side operand a=b += Add 2 numbers and assigns the result to left operand. a+=b /= Divides 2 numbers and assigns the result to left operand. a/=b *= Multiply 2 numbers and assigns the result to left operand. A*=b -= Subtracts 2 numbers and assigns the result to left operand. A-=b %= modulus 2 numbers and assigns the result to left operand. a%=b //= Perform floor division on 2 numbers and assigns the result to left operand. a//=b **= calculate power on operators and assigns the result to left operand. a**=b5.Bitwise operators :Decimal to binary conversionBinary to decimal conversionAND: true only when both are trueOR: false only if both are falseNOT: TRUE IF FALSE , FLASE IF TRUE (REVERSE)XOR: True if both are oppositea ba & b (AND)a | b(OR)a ^ b(XOR)~a(NOT)000001010111100110111100OperatorDescriptionExample& Binary ANDOperator copies a bit to the result if it exists in both operandsa & b| Binary ORIt copies a bit if it exists in either operand.a | b^ Binary XORIt copies the bit if it is set in one operand but not both.a ^ b~ Binary Ones ComplementIt is unary and has the effect of 'flipping' bits.~a << Binary Left ShiftThe left operands value is moved left by the number of bits specified by the right operand.a << 2 >> Binary Right ShiftThe left operands value is moved right by the number of bits specified by the right operand.a >> 2a = 60 # 60 = 0011 1100 b = 13 # 13 = 0000 1101 c = 0c = a & b # 12 = 0000 1100print("Line 1 - Value of c is ", c)c = a | b # 61 = 0011 1101 print("Line 2 - Value of c is ", c)c = a ^ b # 49 = 0011 0001print("Line 3 - Value of c is ", c)c = ~a # -61 = 1100 0011print("Line 4 - Value of c is ", c)c = a << 2 # 240 = 1111 0000print("Line 5 - Value of c is ", c)c = a >> 2 # 15 = 0000 1111print("Line 6 - Value of c is ", c)Precedence Operator precedence determines which operator is performed first in an expression with more than one operators with different precedence.?For example 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30.(A**2+b**2)**(1/2)Associativity is used when two operators of same precedence appear in an expression. Associativity can be either?Left?to?Right or?Right?to?Left. For example ‘*’ and ‘/’ have same precedence and their associativity is?Left?to?Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.OperatorsMeaning()Parentheses**Exponent+x, -x, ~xUnary plus, Unary minus, Bitwise NOT*, /, //, %Multiplication, Division, Floor division, Modulus+, -Addition, Subtraction<<, >>Bitwise shift operators&Bitwise AND^Bitwise XOR|Bitwise OR==, !=, >, >=, <, <=, is, is not, in, not inComparisions, Identity, Membership operatorsnotLogical NOTandLogical ANDorLogical ORRight to Left associativityprint(4 ** 2 ** 3) Exponentiation ** has Right to Left associativity in python4 ** 2 ** 34**8What Are Nonassociative?Operators In Python?Python does have some operators such as assignment operators and comparison operators which don’t support associativity. Instead, there are special rules for the ordering of this type of operator which can’t be managed via associativity.1. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same. State whether true or false.a)Trueb)FalseAnswer:aExplanation: Although the presence of parenthesis does affect the order of precedence, in the case shown above, it is not making a difference. The result of both of these expressions is 1.333333333. Hence the statement is true.2. The value of the expression:4 + 3 % 5a)4b)7c)2d)0Answer:bExplanation: The order of precedence is: %, +. Hence the expression above, on simplification results in 4 + 3 = 7. Hence the result is 7.3. Evaluate the expression given below if A= 16 and B = 15.A % B // Aa)0.0b)0c)1.0d)1Answer:bExplanation: The above expression is evaluated as: 16%15//16, which is equal to 1//16, which results in 0.4. Which of the following operators has its associativity from right to left?a)+b)//c)%d)**Answer:dExplanation: All of the operators shown above have associativity from left to right, except exponentiation operator (**) which has its associativity from right to left.5. What is the value of x if:x =int(43.55+2/2)a)43b)44c)22d)23Answer:bExplanation: The expression shown above is an example of explicit conversion. It is evaluated as int(43.55+1) = int(44.55) = 44. Hence the result of this expression is 44.6. What is the value of the following expression?2+4.00,2**4.0a)(6.0,16.0)b)(6.00,16.00)c)(6,16)d)(6.00, 16.0)Answer:aExplanation: The result of the expression shown above is (6.0, 16.0). This is because the result is automatically rounded off to one decimal place.7. Which of the following is the truncation division operator?a)/b)%c)//d)|Answer:cExplanation: // is the operator for truncation division. It is called so because it returns only the integer part of the quotient, truncating the decimal part. For example: 20//3 = 6.8. What are the values of the following expressions:2**(3**2)(2**3)**22**3**2a)64,512,64b)64,64,64c)512,512,512d)512,64,512Answer:dExplanation: Expression 1 is evaluated as: 2**9, which is equal to 512.Expression 2 is evaluated as 8**2, which is equal to 64. The last expression is evaluated as 2**(3**2). This is because the associativity of ** operator is from right to left. Hence the result of the third expression is 512.9. What is the output of the following expression:print(4.00/(2.0+2.0))a)Errorb)1.0c)1.00d)1Answer:bExplanation: The result of the expression shown above is 1.0 because print rounds off digits.10. Consider the expression given below. The value of X is:X =2+9*((3*12)-8)/10a)30.0b)30.8c)28.4d)27.2Answer: d11. Which of the following expressions involves coercion when evaluated in Python?a)4.7–1.5b)7.9*6.3c)1.7%2d)3.4+4.6Answer:cExplanation: Coercion is the implicit (automatic) conversion of operands to a common type. Coercion is automatically performed on mixed-type expressions. The expression 1.7 % 2 is evaluated as 1.7 % 2.0 (that is, automatic conversion of int to float).12. What is the value of the following expression:24//6%3,24//4//2a)(1,3)b)(0,3)c)(1,0)d)(3,1)Answer: aExplanation: The expressions are evaluated as: 4%3 and 6//2 respectively. This results in the answer (1,3). This is because the associativity of both of the expressions shown above is left to right.13. Which among the following list of operators has the highest precedence? +, -, **, %, /,<<,>>, |a)<<,>>b)**c)|d)%Answer:bExplanation: The highest precedence is that of the exponentiation operator, that is of **.Conditional statementsif StatementSyntaxif test_expression: statement(s)Here, the program evaluates the?test expression?and will execute statement(s) only if the text expression is?True.If the text expression is?False, the statement(s) is not executed.In Python, the body of the?if?statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end.Python interprets non-zero values as?True.?None?and?0?are interpreted as?False.Flowchart# If the number is positive, we print an appropriate messagenum = 3if num > 0: print(num, "is a positive number.")print("This is always printed.")num = -1if num > 0: print(num, "is a positive number.")print("This is also always printed.")if-elseSyntax of if...elseif test expression: Body of ifelse: Body of elseThe?if..else?statement evaluates?test expression?and will execute body of?if?only when test condition is?True.If the condition is?False, body of?else?is executed. Indentation is used to separate the blocks.Flowchart# Program checks if the number is positive or negative# And displays an appropriate messagenum = int(input(" Enter a number:"))if num >= 0: print("Positive or Zero")else: print("Negative number")if-elif-elseSyntax of if...elif...elseif test expression: Body of ifelif test expression: Body of elifelse: Body of elseThe?elif?is short for else if. It allows us to check for multiple expressions.If the condition for?if?is?False, it checks the condition of the next?elif?block and so on.If all the conditions are?False, body of else is executed.Only one block among the several?if...elif...else?blocks is executed according to the condition.The?if?block can have only one?else?block. But it can have multiple?elif?blocks.num = int(input(" Enter a number:"))if num > 0: print("Positive number")elif num == 0: print("Zero ")else: print("Negative number")--------------------------------------------------------------num = int(input(" Enter a digit:"))if num == 0: print("Zero")elif num == 1: print("One ")elif num == 2: print("Two ")elif num == 3: print("Three ")elif num == 4: print("Four ")elif num == 5: print("Five ")elif num == 6: print("Six ")elif num == 7: print("Seven ")elif num == 8: print("Eight ")elif num == 9: print("Nine ")else: print("Not a digit")SIMPLE PROGRAMSABSOLUTE VALUEnum = int(input(" Enter a number:"))if(num <0): abs=-numelse: abs=numprint("absolute of",num,"is",abs)SORT 3 NUMBERSF M LF L MM F LM L FL F ML M F 10 20 3010 30 2020 10 3020 30 1030 10 2030 20 10x = int(input("Input first number: "))y = int(input("Input second number: "))z = int(input("Input third number: "))if x>y: x,y=y,xif y>z: y,z=z,y if x>y: x,y=y,xprint(x,y,z) Divisibilitynumber = int(input(" Please Enter any Positive Integer : "))if((number % 5 == 0) and (number % 11 == 0)): print("Given Number ", number," is Divisible by 5 and 11")else: print("Given Number ", number," is Not Divisible by 5 and 11")Notion of iterative computation and control flowLoops/REPETITIVE STATEMENTS/ITERATIVE STATEMENTS are used in programming to repeat a specific block of code.while loopThe while loop in Python is used to iterate over a block of code as long as the test Expression (condition) is true.We generally use this loop when we don't know beforehand, the number of times to iterate.Flowchart of while Loop# Program to add natural numbers upto sum = 1+2+3+...+n# To take input from the user,n = int(input("Enter n: "))# initialize sum and countersum = 0i = 1while i <= n: sum = sum + i i = i+1 # update counter# print the sumprint("The sum is", sum)While loop iterates till the condition is true.It is an entry controlled loop i = 1while i < 6: print(i) i += 1 Note: Remember to update the value of i ,otherwise it will continue forever.while loop with elsewe can have an optional?else?block with while loop.The?else?part is executed if the condition in the while loop evaluates to?False.The while loop can be terminated with a?break statement. In such case, the?else?part is ignored. Hence, a while loop's?else?part runs if no break occurs and the condition is false.counter = 0while counter < 3: print("Inside loop") counter = counter + 1else: print("Inside else")break and continueWhat is the use of break and continue in Python?In Python, break and continue statements can alter the flow of a normal loop.Loops iterate over a block of code until test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.The?break and continue statements are used in these cases.The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.Syntax of breakBreakFlowchart of breakPython continue statementThe continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.Syntax of ContinuecontinueFlowchart of continue?For loopThe for loop in Python is used to iterate over a sequence (list,?tuple,?string) or other iterable objects. Iterating over a sequence is called traversal.Syntax of for Loopfor val in sequence:Body of forHere,?val?is the variable that takes the value of the item inside the sequence on each iteration.Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.Flowchart of for Loop# Program to find the sum of all numbers stored in a list# List of numbersnumbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]# variable to store the sumsum = 0# iterate over the listfor val in numbers:sum = sum+val# Output: The sum is 48print("The sum is", sum)The range() functionWe can generate a sequence of numbers using?range()?function.?range(10)?will generate numbers from 0 to 9 (10 numbers).We can also define the start, stop and step size as?range(start,stop,step size). step size defaults to 1 if not provided.Ex1:-for x in range(10): print(x)Ex2:-for x in range(1, 10): print(x)Ex3:-for x in range(1, 30,3): print(x)for loop with elseA for loop can have an optional else block as well. The?else?part is executed if the. items in the sequence used in for loop exhausts.break statement can be used to stop a for loop. In such case, the else part is ignored.Hence, a for loop's else part runs if no break occurs.EXAMPLE PROGRAMS:1.Python Program to Calculate the Average of Numbers in a Given List2.Python Program to Reverse a Given Number3.Python Program to Take in the Marks of 5 Subjects and Display the Grade4.Python Program to Read Two Numbers and Print Their Quotient and Remainder5.Python Program to Accept Three Digits and Print all Possible Combinations from the Digits7.Python Program to Print Odd Numbers Within a Given Range 8.Python Program to Find the Sum of Digits in a Number9.Python Program to Find the Smallest Divisor of an Integer 10.Python Program to Count the Number of Digits in a Number 11.Python Program to Check if a Number is a Palindrome 12.Python Program to Read a Number n And Print the Series "1+2+…..+n= "13.Python Program to Read a Number n and Print the Natural Numbers Summation PatternIDEAS OF DEBUGGINGBug means an error. DEBUGGING means removing the errors.Errors And ExceptionsExceptions are python way of notifying errors.Exception Name When it is raised or thrownSyntaxErrorRaised by interpreter when syntax error is encountered.IndentationErrorRaised when there is incorrect indentation.ValueErrorRaised when a function gets argument of correct type but improper value.ZeroDivisionErrorRaised when second operand of division or modulo operation is zero.NameErrorRaised when a variable is not found.TypeErrorRaised when a function or operation is applied to an object of incorrect type.ImportErrorRaised when the imported module is not found.IndexErrorRaised when index of a sequence is out of range.KeyErrorRaised when a key is not found in a dictionary.Syntax Errors:When you forget a colon at the end of a line, or forget a parenthesis, you will encounter a syntax error. This means that Python couldn‘t figure out how to read your program. This is similar to forgetting punctuation in English.while Trueprint(’Hello world’)IndentationErroroccurs when there is incorrect indentation.if True:print(’Hello world’)ValueError :Raised when a function gets argument of correct type but improper value.s= input("enter a no:")n=int(s)print(n)ZeroDivisionError:Raised when second operand of division or modulo operation is zero.no1= int( input("enter number 1") )no2= int( input("enter number 2") )div=no1//no2print("Quotient is " , div)NameError:Raised when a variable is not found .TypeErrorIt ?is thrown when an operation or function is applied to an object of an inappropriate type.Example:'2'+2Traceback (most recent call last):File "<pyshell#23>", line 1, in <module>'2'+2TypeError: must be str, not intDifference between type and value errorsConvert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return integer. For floating point numbers, this truncates towards zero.It can convert the string "21" to the integer 21, but it can't convert "dog" to a number. Thus, it's getting the right?type, but it's still not a?value?that it can convert. This is when we get the?ValueError. It's of the right type, but the?value?is such that it still can't be done.That being said, if we tried to send in something that was?neither?a string?nor?a number, it would have generated a?TypeError?as it is of the wrong?type.int(3+2j)Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> int(3+2j)TypeError: can't convert complex to intelse and finallyIn Python, keywords?else?and?finally?can also be used along with the try and except clauses. While the except block is executed if the exception occurs inside the try block, the else block gets processed if the try block is found to be exception free.Syntax:try: #statements in try blockexcept: #executed when error in try blockelse: #executed if try block is error-freefinally: #executed irrespective of exception occured or notThe finally block consists of statements which should be processed regardless of an exception occurring in the try block or not. As a consequence, the error-free try block skips the except clause and enters the finally block before going on to execute the rest of the code. If, however, there's an exception in the try block, the appropriate except block will be processed, and the statements in the finally block will be processed before proceeding to the rest of the code.try: print("try block") x=int(input('Enter a number: ')) y=int(input('Enter another number: ')) z=x/yexcept ZeroDivisionError: print("except ZeroDivisionError block") print("Division by 0 not accepted")else: print("else block") print("Division = ", z)finally: print("finally block") x=0 y=0print ("Out of try, except, else and finally blocks." )Raise an ExceptionPython also provides the?raise?keyword to be used in the context of exception handling. It causes an exception to be generated explicitly. Built-in errors are raised implicitly. However, a built-in or custom exception can be forced during execution.The following code accepts a number from the user. The try block raises a ValueError exception if the number is outside the allowed range.Example: Raise an Exceptiontry: x=int(input('Enter a number upto 100: '))if x > 100: raise ValueError(x)except ValueError: print(x, "is out of allowed range")else: print(x, "is within the allowed range")Debugging:Pdb, Break Points.Bug means an error. DEBUGGING means removing the errors. A Debugging tool or debugger is a specialized computer program/software that can be used to test and debug programs A debugger tool allows to inspect the state(current values) of variables.Python also provides a separate debugger program called pdb.pdb is python module for debugging which is available in standard library. It is built in. We have to import it as followsimport pdbBreak point: a?breakpoint?is an intentional stopping or pausing place in a?program and it is used to debug program.set_trace() method is used to set a break pointPython debugger commands:l(list) – shows current position in scriptc(continue)- executes codep -- print variabless- to execute next lineq(quit) – exit debugger?(help) – shows all commandsExample:-import pdba = 0b = 1print(a)print(b)for I in range(5): pdb.set_trace( ) c = a+b print(c, end = " ") b = c a = bLists, tuples and dictionary:LISTSThe data type list is an ordered sequence which is mutable and made up of one or more elements.A list can have elements of different data types, such as integer, float, string, tuple or even another list.Elements of a list are enclosed in square brackets and are separated by comma.Syntax:List_Name=[value1,value2,……...,valueN]Index: 0 1 N-1#list1 is the list of six even numbers>>> list1 = [2,4,6,8,10,12]>>> print(list1)[2, 4, 6, 8, 10, 12]#list2 is the list of vowels>>> list2 = ['a','e','i','o','u']>>> print(list2)['a', 'e', 'i', 'o', 'u']#list3 is the list of mixed data types>>> list3 = [100,23.5,'Hello']>>> print(list3)[100, 23.5, 'Hello']#list4 is the list of lists called nested#list>>> list4 =[['Physics',101],['Chemistry',202],['Maths',303]]>>> print(list4)[['Physics', 101], ['Chemistry', 202],['Maths', 303]]Accessing Elements in a ListPositive Index01234L1025341214Negative Index-5-4-3-2-1#initializes a list list1>>> list1 = [2,4,6,8,10,12]>>> list1[0] #return first element of list12>>> list1[3] #return fourth element of list18#return error as index is out of range>>> list1[15]IndexError: list index out of range#an expression resulting in an integer index>>> list1[1+4]12>>> list1[-1] #return first element from right12#length of the list list1 is assigned to n>>> n = len(list1)>>> print(n)6#return the last element of the list1>>> list1[n-1]12#return the first element of list1>>> list1[-n]2Lists are MutableIn Python, lists are mutable. It means that the contentsof the list can be changed after it has been created.#List list1 of colors>>> list1 = ['Red','Green','Blue','Orange']#change/override the fourth element of list1>>> list1[3] = 'Black'>>> list1 #print the modified list list1['Red', 'Green', 'Blue', 'Black']List OperationsThe data type list allows manipulation of its contentsthrough various operations as shown below. ConcatenationPython allows us to join two or more lists usingconcatenation operator depicted by the symbol +.#list1 is list of first five odd integers>>> list1 = [1,3,5,7,9]#list2 is list of first five even integers>>> list2 = [2,4,6,8,10]#elements of list1 followed by list2>>> list1 + list2[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]>>> list3 = ['Red','Green','Blue']>>> list4 = ['Cyan', 'Magenta', 'Yellow','Black']>>> list3 + list4['Red','Green','Blue','Cyan','Magenta','Yellow','Black']Note that, there is no change in ongoing lists, i.e.,list1, list2, list3, list4 remain the sameafter concatenation operation. If we want to merge twolists, then we should use an assignment statement toassign the merged list to another list. The concatenationoperator '+’ requires that the operands should be of listtype only. If we try to concatenate a list with elements ofsome other data type, TypeError occurs.>>> list1 = [1,2,3]>>> str1 = "abc">>> list1 + str1TypeError: can only concatenate list (not"str") to listRepetitionPython allows us to replicate a list using repetitionoperator depicted by symbol *.>>> list1 = ['Hello']#elements of list1 repeated 4 times>>> list1 * 4['Hello', 'Hello', 'Hello', 'Hello'] MembershipLike strings, the membership operators in checks ifthe element is present in the list and returns True, elsereturns False.>>> list1 = ['Red','Green','Blue']>>> 'Green' in list1True>>> 'Cyan' in list1FalseThe not in operator returns True if the element is notpresent in the list, else it returns False.>>> list1 = ['Red','Green','Blue']>>> 'Cyan' not in list1True>>> 'Green' not in list1FalseSlicingLike strings, the slicing operation can also be appliedto lists.>>> list1 =['Red','Green','Blue','Cyan','Magenta','Yellow','Black']>>> list1[2:6]['Blue', 'Cyan', 'Magenta', 'Yellow']#list1 is truncated to the end of the list>>> list1[2:20] #second index is out of range['Blue', 'Cyan', 'Magenta', 'Yellow','Black']>>> list1[7:2] #first index > second index[] #results in an empty list#return sublist from index 0 to 4>>> list1[:5] #first index missing['Red','Green','Blue','Cyan','Magenta']#slicing with a given step size>>> list1[0:6:2]['Red','Blue','Magenta']#negative indexes#elements at index -6,-5,-4,-3 are sliced>>> list1[-6:-2]['Green','Blue','Cyan','Magenta']#both first and last index missing>>> list1[::2] #step size 2 on entire list['Red','Blue','Magenta','Black']#negative step size#whole list in the reverse order>>> list1[::-1]['Black','Yellow','Magenta','Cyan','Blue','Green','Red']Traversing a ListWe can access each element of the list or traverse a listusing a for loop or a while loop.(A) List Traversal Using for Loop:>>> list1 = ['Red','Green','Blue','Yellow','Black']>>> for item in list1:print(item)Output:RedGreenBlueYellowBlackAnother way of accessing the elements of the list isusing range() and len() functions:>>> for i in range(len(list1)):print(list1[i])Output:RedGreenBlueYellowBlack(B) List Traversal Using while Loop:>>> list1 = ['Red','Green','Blue','Yellow','Black']>>> i = 0>>> while i < len(list1):print(list1[i])i += 1Output:RedGreenBlueYellowBlackList Methods and Built-in Functions1.len() Returns the length of the list passed asthe argument>>> list1 = [10,20,30,40,50]>>>>>> list1 = [10,20,30,40,50]>>> len(list1)52. list():Creates an empty list if no argument ispassed>>> list1 = list()>>> list1[ ]Creates a list if a sequence is passed asan argument>>> str1 = 'aeiou'>>> list1 = list(str1)>>> list1['a', 'e', 'i', 'o', 'u']3.append() Appends a single element passed as an argument at the end of the listThe single element can also be a list>>> list1 = [10,20,30,40]>>> list1.append(50)>>> list1[10, 20, 30, 40, 50]>>> list1 = [10,20,30,40]>>> list1.append([50,60])>>> list1[10, 20, 30, 40, [50, 60]]4.extend() Appends each element of the list passed as argument to the end of the given list>>> list1 = [10,20,30]>>> list2 = [40,50]>>> list1.extend(list2)>>> list1[10, 20, 30, 40, 50]5.insert() Inserts an element at a particular index in the list>>> list1 = [10,20,30,40,50]>>> list1.insert(2,25)>>> list1[10, 20, 25, 30, 40, 50]>>> list1.insert(0,5)>>> list1[5, 10, 20, 25, 30, 40, 50]6.count() Returns the number of times a given element appears in the list>>> list1 = [10,20,30,10,40,10]>>> list1.count(10)3>>> list1.count(90)07.index() Returns index of the first occurrence of the element in the list. If the element isnot present, ValueError is generated>>> list1 = [10,20,30,20,40,10]>>> list1.index(20)1>>> list1.index(90)ValueError: 90 is not in list8.remove() Removes the given element from the list. If the element is present multipletimes, only the first occurrence is removed. If the element is not present, then ValueError is generated>>> list1 = [10,20,30,40,50,30]>>> list1.remove(30)>>> list1[10, 20, 40, 50, 30]>>> list1.remove(90)ValueError:list.remove(x):x not in list9.pop() Returns the element whose index is passed as parameter to this functionand also removes it from the list. If no parameter is given, then it returns andremoves the last element of the list >>> list1 = [10,20,30,40,50,60]>>> list1.pop(3)40>>> list1[10, 20, 30, 50, 60]>>> list1 = [10,20,30,40,50,60]>>> list1.pop()60>>> list1[10, 20, 30, 40, 50] 10.reverse() Reverses the order of elements in the given list>>> list1 = [34,66,12,89,28,99]>>> list1.reverse()>>> list1[ 99, 28, 89, 12, 66, 34]>>> list1 = [ 'Tiger' ,'Zebra' ,'Lion' , 'Cat' ,'Elephant' ,'Dog']>>> list1.reverse()>>> list1['Dog', 'Elephant', 'Cat','Lion', 'Zebra', 'Tiger']11.sort() Sorts the elements of the given list in-place>>>list1 = ['Tiger','Zebra','Lion','Cat', 'Elephant' ,'Dog']>>> list1.sort()>>> list1['Cat', 'Dog', 'Elephant', 'Lion','Tiger', 'Zebra']>>> list1 = [34,66,12,89,28,99]>>> list1.sort(reverse = True)>>> list1[99,89,66,34,28,12]12.sorted() It takes a list as parameter and creates a new list consisting of the same elementsarranged in sorted order>>> list1 = [23,45,11,67,85,56]>>> list2 = sorted(list1)>>> list1[23, 45, 11, 67, 85, 56]>>> list2[11, 23, 45, 56, 67, 85]13.min()Returns minimum or smallest elementof the list14.max()Returns maximum or largest element ofthe listsum()Returns sum of the elements of the list>>> list1 = [34,12,63,39,92,44]>>> min(list1)12>>> max(list1)92>>> sum(list1)284STRINGS:TUPLES & DICTIONARIES:RANDOM MODULE:random.random()Return the next random floating point number in the range [0.0, 1.0).random.randint(a,?b)Return a random integer?N?such that?a?<=?N?<=?b. random.randrange(stop)random.randrange(start,?stop[,?step])Return a randomly selected element from?range(start,?stop,?step).What possible outputs(s) are expected to be displayed on screen at the time ofexecution of the program from the following code? Also specify the maximumvalues that can be assigned to each of the variables FROM and TO.import randomAR=[20,30,40,50,60,70];FROM=random.randint(1,3)TO=random.randint(2,4)for K in range(FROM,TO+1):print (AR[K],end=”# “)****************END OF CHAPTER -1******************************CHAPTER-2 : FunctionsWhat is a function?Function is a group of related statements that perform a specific taskSyntax: function definitiondeffunction_name(parameters):"""docstring"""statement(s)return<value> #optionalA function definition consists of following components.Keyword?def?marks the start of function header.A function name to uniquely identify it. Function naming follows the same?rules of writing identifiers in Python.Parameters (arguments) through which we pass values to a function. They are optional.A colon (:) to mark the end of function header.Optional documentation string (docstring) to describe what the function does.One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).An optional?return?statement to return a value from the function.Function Examples:def greet(name):"""This function greets tothe person passed in asparameter"""print("Hello, " + name + ". Good morning!")def add(a,b):returna+bdefcalc(a,b):add=a+bsub=a-bmul= a*breturnadd,sub,mulresult= calc(10,20)print( "the result obtained are")fori in result:print(i)Function Call or invoking a function:A function call is just the function’s name followed by parentheses, possibly with some number of arguments in between the parentheses. When the program execution reaches these calls, it will jump to the top line in the function and begin executing the code there. When it reaches the end of the function, the execution returns to the line that called the function and continues moving through the code as before.Syntax:- Function_name(actual parameters)Write functions for add,sub,mul,div,average,minimum,maximum, of 2 numbers, area of rectangle,triangle, square.Return Values:return?statement is used to return a value from the function.We can return multiple values through single return statement as explained in above example program in function calc(a,b)Parameters and Arguments in Functions:Parameters are values provided in the parantheses,(), when we write function header. Also called formal parameters or formal arguments.Arguments are values that are passed to a function when it is called.Also called actual parameters or actual arguments.Functions can be called using following types of formal arguments ? Positional arguments Keyword arguments Default arguments Variable-length arguments 1.Positional argumentsThese are arguments passed to a function in correct positional order.def subtract(a,b) print(a-b)subtract(100,200)subtract(200,100)2. Keyword arguments - the caller identifies the arguments by the parameter name def fun( name, age,gender ): print ("Name: ", name) print ("Age ", age) print ("Gender ", gender)fun( age=15, gender="F" ,name="abcd") We can use positional and keyword arguments together first we have to provide positional argument then key word argument.fun('xyz', gender='M',age=16)3.Default arguments that assumes a default value if a value is not provided to argumentsdef sum(x=3,y=4): z=x+y return zr=sum()print(r)r=sum(x=4)print(r)r=sum(y=45)print(r)r=sum(9)print(r)4.Variable-length arguments We can pass variable number number of arguments to a function using *(asterisk) symbol in python.def sum(*vartup): total=0 for x in vartup: total = total + x print(" The sum is:", total)sum()sum(20)sum(20,30)sum(20,30,40,50)PRACTICE QUESTIONSERROR FINDING QUESTIONSQ1.Find error in the following code(if any) and correct code by rewriting code and underline the correction;-x= int(“Enter value of x:”)for in range [0,10]:if x=y print( x+y)else: Print( x-y)Q2. Rewrite the following program after finding and correcting syntactical errors and underlining it.a,b = 0 if (a = b) a +b = c print( z)Q3.Rewrite the following code in python after removing all syntaxerror(s). Underline each correction done in the code. 250 = NumberWHILE Number<=1000:if Number=>750print(Number)Number=Number+100elseprint( Number*2)Number=Number+50 Q4.Rewrite the following code in python after removing all syntax error(s). Underlineeach correction done in the code.Val = int(input("Value:"))Adder = 0for C in range(1,Val,3)Adder+=Cif C%2=0:Print (C*10)Else:print(C*)print(Adder)Q5.Rewrite the following code in python after removing all syntax error(s).Underline each correction done in the code.25=Valfor I in the range(0,Val)if I%2==0:print( I+1)Else:print(I-1Q6.Rewrite the following code in python after removing all syntax error(s). Underlineeach correction done in the code.STRING=""WELCOMENOTE""for S in range[0,8]:print(STRING(S)) Q7.Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.a=int{input("ENTER FIRST NUMBER")}b=int(input("ENTER SECOND NUMBER"))c=int(input("ENTER THIRD NUMBER"))if a>b and a>cprint("A IS GREATER")if b>a and b>c:Print(" B IS GREATER")if c>a and c>b:print(C IS GREATER)Q8.Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.i==1a=int(input("ENTER FIRST NUMBER"))FOR i in range[1,11];print(a,"*=",i,"=",a*i)Q.9 Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.a=”1”while a>=10:print("Value of a=",a) a=+1Q10.Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.Num=int(rawinput("Number:"))sum=0for i in range(10,Num,3) Sum+=1if i%2=0:print(i*2) Else:print(i*3)print(Sum)Q 11.Rewrite the following code in python after removing all syntax error(s). Underlineeach correction done in the code.weather='raining'if weather='sunny':print("wear sunblock")elif weather='snow':print("going skiing")else:print(weather)Q 12.Write the modules that will be required to be imported to execute the following code in Python. def main( ):for i in range (len(string)) ):if string [i] = = ‘’ “printelse:c=string[i].upper()print( “string is:”,c)print(“String length=”,len(math.floor()))Q.13. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with each correction underlined. DEF execmain():x = input("Enter a number:")if (abs(x)=x):print("You entered a positive number")else:x=*-1print "Number made positive:"xexecmain()Q 14.- Rewrite the following code in python after removing all syntax error(s).Underline each correction done in the codex=integer(input('Enter 1 or 10'))if x==1:for x in range(1,11) Print(x)Else:for x in range(10,0,-1):print(x)15.Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code.30=Tofor K in range(0,To) :IF k%4==0:print (K*4) Else:print (K+3)OUTPUT FINDING QUESTIONSQ1 Find output generated by the following code:p=10q=20p*=q//3q+=p+q**2print(p,q)Q2 Find output generated by the following code:Str=”Computer”Str[-4:]Str*2Q3 Find out the output of the Following – x=20 x=x+5 x=x-10print (x)x,y=x-1,50print (x,y)Q4 Find out the output of the Following – for a in range(3,10,3):for b in range(1,a,2):print(b, end=’ ‘)print ()Q5 FIND OUTPUT OF FOLLOWINGx=10y=5for i in range(x-y*2):print("%",i)Q6. Find outputx="one"y="two"c=0while c<len(x):print(x[c],y[c]) c=c+1Q 7:Find output -1,1,3,5for i in range(-1,7,2): 0,1,2for j in range(3):print(i,j)Q.8Find outputstring=”aabbcc”count=3while True:if string[0]=='a':string=string[2:]elif string[-1]=='b':string=string[:2]else:count+=1breakprint(string)print(count)Q9:Find outputx="hello world"print(x[:2],x[:-2],x[-2:])print(x[6],x[2:4])print(x[2:-3],x[-4:-2])Q10. Find and write the output of the following python code :Msg1="WeLcOME"Msg2="GUeSTs"Msg3=""for I in range(0,len(Msg2)+1):if Msg1[I]>="A" and Msg1[I]<="M":Msg3=Msg3+Msg1[I]elif Msg1[I]>="N" and Msg1[I]<="Z":Msg3=Msg3+Msg2[I]else:Msg3=Msg3+"*"print(Msg3)G*L*TMEQ11. Find and write the output of the following python code :def Changer(P,Q=10): P=P/Q Q=P%Qprint P,"#",Qreturn PA=200B=20A=Changer(A,B)print A,"$",BB=Changer(B)print A,"$",BA=Changer(A)print A,"$",BQ12. Find and write the output of the following python code: Data = ["P",20,"R",10,"S",30]Times = 0Alpha = ""Add = 0for C in range(1,6,2): Times= Times + C Alpha= Alpha + Data[C-1]+"$" Add = Add + Data[C]print Times,Add,AlphaQ13 Find and write the output of the following python code:Text1="AISSCE 2018"Text2=""I=0while I<len(Text1):if Text1[I]>="0" and Text1[I]<="9": Val = int(Text1[I]) Val = Val + 1 Text2=Text2 + str(Val)elif Text1[I]>="A" and Text1[I] <="Z": Text2=Text2 + (Text1[I+1])else: Text2=Text2 + "*" I=I+1print Text2Q14 Find and write the output of the following python code:TXT = ["20","50","30","40"]CNT = 3TOTAL = 0for C in [7,5,4,6]: T = TXT[CNT] TOTAL = float (T) + Cprint TOTAL CNT-=1Q15Find and write the output of the following python code:line = "I'll come by then."eline = "" for i in line: ????eline += chr(ord(i)+3) print(eline)Q 16Find and write the output of the following python code:line =? "What will have so will"L = line.split('a') for i in L: ????print(i, end=' ') Q 17 Find output p=5/2 q=p*4 r=p+q p+=p+q+r q-=p+q*r print(p,q,r) Q 18 find outputa=(2+3)**3-6/2 b=(2+3)*5//4+(4+6)/2 c=12+(3*4-6)/3 d=12%5*3+(2*6)//4 print(a,b,c,d) Q19. Find the output of the following: def main ( ) : Moves=[11, 22, 33, 44] Queen=MovesMoves[2]+=22 L=Len(Moves)for i in range (L)print( “Now@”, Queen[L-i-1], “#”, Moves [i])Q20. Find the output of the followingL1 = [100,900,300,400,500]START = 1SUM = 0for C in range(START,4): SUM = SUM + L1[C]print(C, ":", SUM) SUM = SUM + L1[0]*10print(SUM) Q. 21.Find and write the output of the following python code: def fun(s):k=len(s)m=" "for i in range(0,k): if(s[i].isupper()):m=m+s[i].lower()elif s[i].isalpha():m=m+s[i].upper()else:m=m+'bb' print(m)fun('school2@com')Q. 22. Find the output of the given program :def Change(P ,Q=30): P=P+QQ=P-Qprint( P,"#",Q) return (P)R=150 S=100R=Change(R,S) print(R,"#",S) S=Change(S)23. x = "abcdef" i = "a"while i in x:print(i, end = " ")Questions Based on TupleQ:Find the output of following codest1=("sun","mon","tue","wed")print(t1[-1])t2=("sun","mon","tue","wed","thru","fri")for i in range (-6,2):print(t2[i])t3=("sun","mon","tue","wed","thru","fri")if "sun" in t3:for i in range (0,3):print(t3[i])else:for i in range (3,6):print(t3[i])t4=("sun","mon","tue","wed","thru","fri")if "sun" not in t4:for i in range (0,3):print(t4[i])else:for i in range (3,6):print(t4[i])t5=("sun",2,"tue",4,"thru",5)if "sun" not in t4:for i in range (0,3):print(t5[i])else:for i in range (3,6):print(t5[i])t6=('a','b')t7=('p','q')t8=t6+t7print(t8*2)t9=('a','b')t10=('p','q')t11=t9+t10print(len(t11*2))t12=('a','e','i','o','u')p,q,r,s,t=t12print("p= ",p)print("s= ",s)print("s + p", s + p)t13=(10,20,30,40,50,60,70,80)t14=(90,100,110,120)t15=t13+t14print(t15[0:12:3])Q. Find the errorst1=(10,20,30,40,50,60,70,80)t2=(90,100,110,120)t3=t1*t2Print(t5[0:12:3])t1=(10,20,30,40,50,60,70,80)i=t1.len()Print(T1,i)t1=(10,20,30,40,50,60,70,80)t1[5]=55t1.append(90)print(t1,i)t1=(10,20,30,40,50,60,70,80)t2=t1*2t3=t2+4print t2,t3t1=(10,20,30,40,50,60,70,80)str=””str=index(t1(40))print(“index of tuple is ”, str)str=t1.max()print(“max item is “, str)List Based QuestionQ.1. Give the output of the following code:-list=['p','r','o','b','l','e','m']list[1:3]=[]print(list)list[2:5]=[]print(list)Q2.Give the output of the following code:-l1=[13,18,11,16,13,18,13]print(l1.index(18))print(l1.count(18))l1.append(l1.count(13))print(l1)Q 3 Find the error in following code. State the reason of the error.aLst = { ‘a’:1 ,’ b’:2, ‘c’:3 }print (aLst[‘a’,’b’])Q 4.list1 =[1998, 2002, 1997, 2000] list2 =[2014, 2016, 1996, 2009] ??print("list1 + list 2 = : ", list1 +list2)?? #statement 1 ??print("list1 * 2 = : ", list1 *2)? #statement 2 Q5. list1 = [1, 2, 3, 4, 5] list2 =list1 ??list2[0] =0; ??print("list1= : ", list1) Q6. What is the output of the following:data =[2, 3, 9] temp =[[x forx in[data]] forx inrange(3)] print(temp) a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]]b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]]c) [[[2, 3, 9]], [[2, 3, 9]]]d) None of theseQ7. What is the output of the following:temp =['Geeks', 'for', 'Geeks'] arr =[i[0].upper() fori intemp] print(arr) a) [‘G’, ‘F’, ‘G’]b) [‘GEEKS’]c) [‘GEEKS’, ‘FOR’, ‘GEEKS’]d) Compilation errorQ8.What will be the output?d1 ={"john":40, "peter":45}d2 ={"john":466, "peter":45}d1 > d2a) TRUEb) FALSEc) ERRORd) NONEQ9. What will be the error of the following code Snippet?Lst =[1,2,3,4,5,6,7,8,9]Lst[::2]=10,20,30,40,50,60Print[Lst]Q10. Find the error in following code. State the reason of the erroraLst={‘a’:1,’b’:2,’c’:3}print(aLst[‘a’,’b’])Q11. What Will Be The Output Of The Following Code Snippet?a =[1,2,3,4,5]print(a[3:0:-1])A.?Syntax errorB.?[4, 3, 2]C.?[4, 3]D.?[4, 3, 2, 1]Q 12.What Will Be The Output Of The Following Code Snippet?fruit_list1 = ['Apple', 'Berry', 'Cherry', 'Papaya']fruit_list2 = fruit_list1fruit_list3 = fruit_list1[:]fruit_list2[0] = 'Guava'fruit_list3[1] = 'Kiwi'sum = 0for ls in (fruit_list1, fruit_list2, fruit_list3):if ls[0] == 'Guava':sum += 1if ls[1] == 'Kiwi':sum += 20print (sum)A.?22B.?21C.?0D.?43Q13. What Will Be The Output Of The Following Code Snippet?a = {(1,2):1,(2,3):2}print(a[1,2])A. Key ErrorB. 1C. {(2,3):2}D. {(1,2):1}Q14. What Will Be The Output Of The Following Code Snippet?my_dict = {}my_dict[1] = 1my_dict['1'] = 2my_dict[1.0] = 4sum = 0for k in my_dict:sum += my_dict[k]print (sum)A.?7B.?Syntax errorC.?3D.?6Q15.What Will Be The Output Of The Following Code Snippet?my_dict = {}my_dict[(1,2,4)] = 8my_dict[(4,2,1)] = 10my_dict[(1,2)] = 12sum = 0for k in my_dict:sum += my_dict[k]print (sum)print(my_dict)A.?Syntax errorB.?30?????? {(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}C.?47??? {(1, 2): 12, (4, 2, 1): 10, (1, 2, 4): 8}D.?30??? {[1, 2]: 12, [4, 2, 1]: 10, [1, 2, 4]: 8} ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download