Introduction to Python Programming
2.1 Introduction
Noquestions.
2.2 Variables and Assignment Statements
2.2Q1:Whichofthefollowingstatementsis false?
a.Variablesstorevaluesforlateruseinyourcode.
b.Thefollowingstatementcreates x andusestheassignmentsymbol(=)togive x avalue.
x = 7
c.Everystatementstopsattheendofthelineinwhichitbegins.
d.Once x and y arecreatedandassignedvalues,youcanusethevaluesinexpressionslike:
x + y
Answer: c. Every statement stops at the end of the line in which it begins. Actually, it’s possible for statements to span more than one line.
2.2Q2:Whichofthefollowingstatementsis false?
a.Thefollowingassignmentstatementaddsthevaluesofvariables x and y and assignstheresulttothevariable total:
total = x + y
b.Theprecedingsnippetisread,“total isassignedthevalueof x+y.”
c.The = symbolistheassignmentoperator.
d.Therightsideofthe = symbolalwaysexecutesfirst,thentheresultisassigned tothevariableonthesymbol’sleftside.
Answer: c. The = symbol is the assignment operator. Actually, the = symbol is not an operator in Python.
2.2Q3:Whichofstatementsa),b)orc)is false?
a.Avariablename,suchas x,isanidentifier.
b.Eachidentifiermayconsistofletters,digitsandunderscores(_)butmaynot beginwithadigit.
c.Pythoniscaseinsensitive,so number and Number arethesameidentifierdespitethefactthatonebeginswithalowercaseletterandtheotherbeginswithan uppercaseletter.
d.Alloftheabovestatementsaretrue.
Answer: c. Python is case insensitive, so number and Number are the same identifier despite the fact that one begins with a lowercase letter and the other begins with an uppercase letter. Actually, Python is case sensitive, so number and Number are different identifiers because one begins with a lowercase letter and the other begins with an uppercase letter.
2.2Q4:Thevalue10.5isa(n) (thatis,anumberwithadecimalpoint).
a.integer
b.string
c.floating-pointnumber
d.Noneoftheabove
Answer: c. floating-point number.
2.2Q5:Whichofthefollowingstatementsa),b)andc)is false.
a.Python’s type built-infunctiondeterminesavalue’stype.
b.Afunctionperformsitstaskwhenyoucallitbywritingitsname,followedby squarebrackets, []
c.Theparenthesesafterafunctionnameinafunctioncallcontainthefunction’s argument thedatathatthe type functionneedstoperformitstask.
d.Alloftheabovestatementsare true.
Answer: b. A function performs its task when you call it by writing its name, followed by square brackets, []. Actually, a function performs its task when you call it by writing its name, followed by parentheses, ().
2.3 Arithmetic
2.3Q1:Whichofthefollowingstatementsa),b)orc)is false?
a.Pythonusestheasterisk(*)asthemultiplicationoperator(e.g., 7*4).
b.Theexponentiation(**)operatorraisesonevaluetothepowerofanother(e.g., 2**10).
c.Tosquareanumber,youcanusetheexponent 1/2 (thatis, 0.5),asin: 9 ** (1 / 2)
d.Alloftheabovestatementsare true. Answer: c. To square a number, you can use the exponent 1/2 (that is, 0.5). Actually, to square a number, use the exponent 2. The exponent 1/2 takes the square root of the number.
2.3Q2:Whichofthefollowingstatementsis false?
a.Truedivision(/)dividesanumeratorbyadenominatorandyieldsafloatingpointnumberwithadecimalpoint.
b.Floordivision(//)dividesanumeratorbyadenominator,yieldingthehighest integer that’s not greater than the result. Python truncates (discards) the fractionalpart.
c.Theexpression -13 / 4 evaluatesto -3.25.
d.Theexpression -13 // 4 evaluatesto -3.
Answer: d. The expression -13 // 4 evaluates to -3. Actually, the expresion -13 // 4 evaluates to -4.
2.3Q3:Whichofthefollowingstatementsis false?
a.Dividingbyzerowith / or // isnotallowedandresultsinanexception asign thataproblemoccurred:
b.Pythonreportsanexceptionwithatraceback.
c.Mostexceptionnamesendwith Exception.
d.InIPythoninteractivemode,thelinethatbeginswith ----> showsthecode thatcausedtheexception.
Answer: c. Most exception names end with Exception. Actually, most exception names end with Error.
2.3Q4:Whichofthefollowingstatementsis false?
a.Thevalueofthefollowingexpressionis 3: 17 % 5
b.Thevalueofthefollowingexpressionis 0.5: 7.5 % 3.5
c. You can use the remainder operator for applications such as determining whetheronenumberisamultipleofanother.
d.Youcanusetheremainderoperatortodeterminewhetheranumberisoddor even.
Answer: a. The value of the following expression is 3: 17 % 5
Actually, the value of the expression is 2.
2.3Q5:Whichofthefollowingstatementsis false?
a.Algebraicexpressionsmustbetypedinstraight-lineformusingPython’soperators.
b.Thefollowingcodemultiplies 10 timesthequantity 5 + 3,yieldingtheresult 80: 10 * (5 + 3)
c.Parenthesesinanexpressionaresaidtoberedundant(unnecessary)ifremovingthemyieldsthe same result.
d.Theparenthesesinpartb)aboveareredundant.
Answer: d. The parentheses in part b) above are redundant. Actually, without the parentheses, the value of the expression is different it’s now 53, so the parentheses are not redundant.
2.3Q6:Whichofthefollowingstatementsis false?
a.Pythonappliestheoperatorsinarithmeticexpressionsaccordingtotherules ofoperatorprecedence,whicharegenerallythesameasthoseinalgebra.
b.Parentheseshavethehighestlevelofprecedence,soexpressionsinparenthesesevaluatefirst thus,parenthesesmayforcetheorderofevaluationtooccur inanysequenceyoudesire.
c.Inexpressionswith nested parentheses,suchas (a/(b-c)),theexpression inthe innermost parentheses(thatis, b-c)evaluatesfirst.
d. If an expression contains several exponentiation operations, Python applies themfromlefttoright.
Answer: d. If an expression contains several exponentiation operations, Python applies them from left to right. Actually, if an expression contains several exponentiation operations, Python applies them from right to left.
2.3Q7:Whichofthefollowingstatementsis false?
a.WhenwesaythatPythonappliescertainoperatorsfrom lefttoright,weare referringtotheoperators’grouping.
b.Inthefollowingexpression,theadditionoperators(+)groupasifweparenthesizedtheexpressionas a+ (b+c):
a + b + c
c.AllPythonoperatorsofthesameprecedencegroupleft-to-rightexceptforthe exponentiationoperator(**),whichgroupsright-to-left.
d.Youcanuseredundantparenthesestogroupsubexpressionstomakeexpressionsclearer.Forexample,thesecond-degreepolynomial
y = a * x ** 2 + b * x + c canbeparenthesized,forclarity,as y = (a * (x ** 2)) + (b * x) + c
Answer: b. In the following expression, the addition operators (+) group as if we parenthesized the expression as a+ (b+c):
a + b + c
Actually, the addition operators (+) group from left to right as if we parenthesized the expression as (a+b)+c.
2.3Q8:Whichofthefollowingstatementsaboutarithmeticoperatorsis false?
a. Each arithmetic operatormaybe used with integers and floating-point numbers.
b.Ifbothoperandsareintegers,theresultisaninteger exceptforthetrue-division(/)operator,whichalwaysyieldsafloating-pointnumber.
c.Ifbothoperandsarefloating-pointnumbers,theresultisafloating-pointnumber.
d.Expressionscontaininganintegerandafloating-pointnumberaremixed-type expressions thesealwaysproduceaninteger.
Answer: d. Expressions containing an integer and a floating-point number are mixed-type expressions these always produce an integer.
Actually, these mixed-type expressions always produce a floating-point number.
2.4 Function print and an Intro to Single- and DoubleQuoted Strings
2.4Q1:Whichofthefollowingstatementsis false?
a. When you evaluate expressions in interactive mode, the text that print displaysisprecededby Out[] withasnippetnumberinthesquarebrackets.
b. print does not display a string’s quotes, though there is a way to display quotesinstrings.
c.Youalsomayencloseastringindoublequotes("),asin: print("Welcome to Python!")
butPythonprogrammersgenerallyprefersinglequotes.
d.Whenprintcompletesitstask,itpositionsthescreencursoratthebeginning ofthenextline.
Answer: a. When you evaluate expressions in interactive mode, the text that print displays is preceded by Out[] with a snippet number in the square brackets.
Actually, unlike when you evaluate expressions in interactive mode, the text that print displays is not preceded by Out[] with a snippet number in the square brackets.
2.4Q2:Whichofthefollowingstatementsa),b)andc)is false?
a.Whenabackslash(\)appearsinastring,it’sknownastheescapecharacter.
b.Thebackslashandthecharacterimmediatelyfollowingitformanescapesequence. For example, \n represents the newline character escape sequence, whichtells print tomovetheoutputcursortothenextline.
c.Placingtwo backslashes back-to-backtells print todisplayablankline.
d.Alloftheabovestatementsare true.
Answer: c. Placing two backslashes back-to-back tells print to display a blank line.
Actually, placing two backslashes back-to-back tells print to display a backslash.
2.5 Triple-Quoted Strings
2.5Q1:Triple-quotedstringsareusedtocreate:
a.multilinestrings,
b.stringscontainingsingleordoublequotes
c.docstrings,whicharetherecommendedwaytodocumentthepurposesofcertainprogramcomponents.
d.Alloftheabove
Answer: d. All of the above.
2.5Q2:Whichofthefollowingstatementsis false?
a.Astringdelimitedbysinglequotesmayincludedouble-quotecharacters: print('Display "hi" in quotes')
b.Astringdelimitedbydoublequotesmayincludesinglequotecharacters: print("Display the name O'Brien")
c.Astringdelimitedbydoublequotesmaynotincludedoublequotes.
d.Toavoidusing \' and \" insidestrings,youcanenclosesuchstringsintriple quotes:
Answer: c. A string delimited by double quotes may not include double quotes. Actually, a string delimited by double quotes may not include double quotes, unless you use the \" escape sequence: print("Display \"hi\" in quotes")
2.6 Getting Input from the User
2.6Q1:WhenPython“adds”the string values '7' and '3',itproduces:
a.theinteger 10
b.thestring '10'
c.thestring '73'
d.theinteger 73.
Answer: c. the string '73'
2.6Q2:Whatdoesthe int functionattempttodointhefollowingcode? value = input('Enter an integer: ') value = int(value)
a.Convertanintegertoastring.
b.Convertastringtoaninteger.
c.Convertanon-objecttoanobject.
d.Noneoftheabove.
Answer: b. Convert a string to an integer.
2.7 Decision Making: The if Statement and Comparison Operators
2.7Q1:Whichofthefollowingstatementsa),b)andc)is false?
a.AconditionisaBooleanexpressionwiththevalue True or False.
b. True and False arekeywords wordsthatPythonreservesforitslanguage features.
c.Usingakeywordasanidentifiercausesa ValueError.
d.Noneoftheabovestatementsisfalse.
Answer: c. Using a keyword as an identifier causes a ValueError. Actually, using a keyword as an identifier causes a SyntaxError.
2.7Q2Whichofthefollowingstatementsis true?
a.The if statementusesaconditiontodecidewhethertoexecuteastatement(or agroupofstatements).
bIPythoninteractivemodeishelpfulforexecutingbriefcodesnippetsandseeing immediateresults.
c.Whenyouhavemanystatementstoexecuteasagroup,youtypicallywritethem asascriptstoredinafilewiththe .py (shortforPython)extension.
d.Alloftheabovestatementsare true.
Answer: d. All of the above statements are true.
2.7Q3:Whichofthefollowingstatementsis false?
a.Alinethatbeginswiththehashcharacter(#)isacomment.
b.Acommentmustbeginthelinewithahashcharacter(#).
c.Commentsdonotcausethecomputertoperformanyactionwhenthecodeexecutes.
d.The Style Guide for Python Code statesthateachscriptshouldstartwithadocstringthatexplainsthescript’spurpose,
Answer: b. A comment must begin the line with a hash character (#). Actually, a comment also can begin to the right of the code on a given line and continue until the end of that line. Such a comment documents the code to its left.
2.7Q4:Whichofthefollowingstatementsis false?
a.Youuseblanklinesandspacecharacterstomakecodeeasiertoread.
b.Together,blanklines,spacecharactersandtabcharactersareknownaswhite space.
c.Pythonignoresallwhitespace.
d.Pythonallowsyoutosplitlongcodelinesinparentheseswithoutusingcontinuationcharacters.
Answer: c. Python ignores all white space. Actually, Python ignores most white space some indentation (which is created with whitespace characters) is required. [Also, white space in strings is significant.]
2.7Q5:Youmayspreadalengthystatementoverseverallineswiththe continuationcharacter.
a. @
b. \
c. %
d. ^
Answer: b. \
2.7Q6:Whichofthefollowingstatementsis false?
a. The following if statement uses the == comparison operator to determine whetherthevaluesofvariables number1 and number2 areequal: if number1 == number2: print(number1, 'is equal to', number2)
b.Each if statementconsistsofthekeyword if,theconditiontotest,andacolon (:)followedbyanindentedbodycalledasuite.
c.Eachsuitecontainszeroormorestatements.
d.Forgettingthecolon(:)aftertheconditionisacommonsyntaxerror.
Answer: c. Each suite contains zero or more statements. Actually, each suite must contain one or more statements.
2.7Q7:Whichofthefollowingstatementsis false?
a.Pythonrequiresyoutoindentthestatementsinsuites.
b.Incorrectindentationofthestatementsinasuitecancauseerrors.
c.Usingtheassignmentsymbol(=)insteadoftheequalityoperator(==)inan if statement’sconditionisacommonlogicerror.
d.Using == inplaceof = inanassignmentstatementcanleadtosubtleproblems. Answer: c. Using the assignment symbol (=) instead of the equality operator (==) in an if statement’s condition is a common logic error. Actually, Using the assignment symbol (=) instead of the equality operator (==) in an if statement’s condition is a common syntax error.
2.7Q8:Thechainedcomparison 3 < y <= 11 is false forwhichofthefollowing valuesof y:
a.11
b.10
c.4
d.3
Answer: d. 3
2.8 Objects and Dynamic Typing
2.8Q1:Assume x is 3, y is 7.1 and z is ’11.5’.Whichofthefollowingstatements is incorrect?
a. type(x) is int
b.thevalueof z is 11.5
c.thevalueof y is 7.1
d. type(z) is str
Answer: b. the value of z is 11.5. Actually, the value of z is ’11.5’.
2.8Q2:Whichofthefollowingstatementsis false?
a.Assigninganobjecttoavariablebinds(associates)thatvariable’snametothe object.Youcanthenusethevariableinyourcodetoaccesstheobject’svalue.
b. After the following snippet’s assignment, the variable x refers to the integer objectcontaining 7.
x = 7
c.Thefollowingstatementchanges x’svalue:
x + 10
d.Thefollowingstatementchanges x’svalue:
x = x + 10
Answer: c. The following statement changes x’s value:
x + 10
Actually, this statement does not change x’s value you can change x’s value via assignment as shown in Part (d).
2.8Q3:WhichofthefollowingPythonconceptsaredemonstrateddirectlyorindirectlybythefollowingcode:
In [1]: type(x) Out[1]: int
In [2]: x = 4.1
In [3]: type(x) Out[3]: float
In [4]: x = 'dog'
In [5]: type(x) Out[5]: str
a. Python uses dynamic typing it determines the type of the object a variable referstowhileexecutingyourcode.
b.Overitslifetimeavariablecanbeboundtodifferentvariables,evenvariables ofdifferenttypes.
c.Pythoncreatesobjectsinmemoryandremovesthemfrommemoryasnecessary. This removal process called garbage collection helps ensure that memoryisavailablefornewobjectsyoucreate.
d.Alloftheabove.
Answer: d. All of the above.
2.9 Intro to Data Science: Basic Descriptive Statistics
2.9Q1:Whichofthefollowingstatementsaboutdescriptivestatisticsis false?
a.Theminimumisthesmallestvalueinacollectionofvalues.
b.Therangeisthevaluesstartingwiththeminimumandendingwiththemaximum.
c.Thecountisthenumberofvaluesinacollection.
d.Measuresofdispersion(alsocalledmeasuresofvariability),suchascount,help determinehowspreadoutvaluesare.
Answer: d. Measures of dispersion (also called measures of variability), such as count, help determine how spread out values are. Actually, measures of dispersion (also called measures of variability), such as range, help determine how spread out values are.
2.9Q2:Whichofthefollowingstatementsis incorrect:
a. min(17, 19, 23, 29, 31, 37, 43) isavalidcalltobuilt-infunction min,
b.The range ofvaluesissimplytheminimumthroughthemaximumvalue.
c.Muchofdatascienceisdevotedtogettingtoknowyourdata.
d.Alloftheabovearecorrect.
Answer: d. All of the above are correct.
2.9Q3:Whichofthefollowingstatementsaboutfunctional-styleprogrammingis false?
a.Withfunctional-styleprogrammingcapabilitiesyoucanwritecodethatismore concise,clearerandeasiertodebug thatis,findandcorrecterrors.
b. The min and max functions are examples of a functional-style programming conceptcalledreduction.Theyreduceacollectionofvaluestoasinglevalue.
c.Otherreductionsyou’llseeincludethesum,average,varianceandstandarddeviationofacollectionofvalues.
d.AllreductionsarebuiltintoPython youcannotdefinecustomreductions.
Answer: d. All reductions are built into Python—you cannot define custom reductions.
Actually, you can define custom reductions.