0% found this document useful (0 votes)
253 views37 pages

Python Fundamental PDF

Uploaded by

Jayesh Chouhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
253 views37 pages

Python Fundamental PDF

Uploaded by

Jayesh Chouhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 37
24 Tn Tis Cherter 2.4 Introduction 24 Barebones of a Python Program 22 Python Character Set 2.5. Vatables and Assignments, 23 Tokens: 26 Simple Input and Ourput INTRODUCTION ‘You must have heard the term IPO ~ Input, rocess,Cutput. Most (infact, nearly all) daily life and computer actions are governed by IPO cycle. Thats, there is certain Input, certain kind ef Processing and an Output, Do you know that programs make IPO cycle happen ? Anywhere and everywhere, where you want to tansferm some kind of input to certain output, You have some kind of input to certain output, you have to havea progran.. A program isa seat instructions that govern the processing. In other words, a program forms the base for processing, In this chapter, we shall be talking about all basic elements that a Python program can contain. Towil be leaming about Python's basics ike character et, tokens, expression, statements simple input and output etc. So, are we all eady to take our first sincere sep towards Pylon programming ? And, here we go =) a 22. PYTHON CHARACTER SET set of valid characters that a language can recognize. A character repr any letter, digit or any other symbol. Python supports Unicode encoding standard, Th, Python has the following character set © Letes ates © Digs a © Special symbols space o-9/°°\() (1 C1 // stone ea? ae Bree senderscore) Whitespace lan space, tabs) carriage return), aie, fon (6 Other characters Python can proces AST and Unicode characters pr Creser teers. 23° ToKens Ina pastage of text individual words nd punctuation mark are calle olen o ea lexi elements The smallest individual unt ia program is known a Tole oe ee eee Ce (O Keywords (i Kdentiiers Names) (i) Liters Theat waren (iv) Operators (r) Punctuators (Progra 16 ANC as» Tae Let us talk about these one by one. 23.1 Keywords Keywords are the words that convey a special meaning to the language compiler/interpreter. These are reserved for special purpose and must not be used as normal identifier names. A heyword 8 wrt Yat ‘gecal maanrg "e propane wee Python programming. language contains the following = keywords Fae amet del for in or while None break elf fom is puss with Tre class else global lambda raise yield and continue except nonlocal rear as def finally import, not try 2.3.2 Identifiers (Names) Identifiers are fundamental building, blocks of a program and are used as th 6! terminology for the names given to different pats ofthe program rz, variables. by“ functions, lists, dictionaries etc. [dentfier forming rules of Python are being specified below ‘© An identifier is an arbitrarily long sequence of letters and digits ‘© The first character must be a letter; the underscore (_ ) counts asa ett Chapter 2 PTHON FUNOAMENTALS z ‘© Upper and lower-case letters are diferent. All characters are significant. {© The digits 0 through 9 can be part of the identifier except forthe ist character. ‘© Identifiers are unlimited in length, Cas i significant iz, Python is case sensitive as it ‘eats upper and lower-case characters differenty {© An identifier must not be a keyword of Python, ‘© An identifier cannot contain any special character except for underscore () ‘The following are some valid identifiers : wyflle —onres_7.77 227079 WE 05 85K ok FILen3 ‘The following are some innaid identifies DATA-REC contains special character - (hyphen) (other than AZ, a2 and (underscore) ) aecicr Starting with a digit break reserved keyword, ny. file contains special character dot (.) 2.3.3 Literals / Values Literals (often referred to as constant-Values) are data items that have a fixed value. Python allows several kinds of literals (String literals (i) Numeric literals (i) Boolean literals (ie) Special Literal None (0) Literal Collections 2.3.34 Sting Literals ‘The text enclosed in quotes forms a string literal in Python, FPoreampl ‘beak areal stig eral in Python Ve" Unlike many other languages, both single character : enclosed in quotes such a8" oor mulpe characters a mu mur lll wand ll erelowed in qutes such a8 “ah” or “x2 are tented wo chew wate in. Sting eral 2 Wat ae keywords? Can errs bes you can notice, one can form sting ital by endosing ed as eters? text in both forms of quotes ~ single quotes or double at isan Menier 2 What ae the 2% Mou a Mii 7 Yat a quotes. Following aresome valid sting ital in Python 4. Python case tensive 7 What is) “Asthat “rizvan® met by the tem ase Sense! ? Welloworld —“Aay’s" |. Which of the follwing ave valid - In Pilon, oe eniens and w/w not Data. data, 1 data, data, mye late, ambi, ak? ne naesea forms of qutes se quotes or double ste, “uzrs0201" (COMPUTER SCIENCE WITH PYTHON — 9 values. Nongraphic characters Python allows you to have certain nongniphic-charactersin Sting e ate those character that cannot be typed dircly from keyboard e. backspace, tabs carriage Tetum etc. (No character is typed when these keys are Pressed, only some action takes place). These nongrophic ‘A string Iara sequence Characters can be represented by using escape sequences. An 50 Neel Ss sons escape sequence is represented by a backslash (\) followed bY aio double ortple cate) ‘one or more characters.» ac Following table (Table 21) gives listing of escape sequences. Tote 24. escape sequences in thon What ie does Escape What it does fhe Rishon tects) scence {non grapheehorecer) Ww Backslash (\), \r Carriage Return (CR) 2 eS Seeman \ Dbl gue) Yet hash 0 te Meee | oseeen | eaeeeatss cree Soon aes 6 | Asc Backspace (85 \w ASCH Vertical Tab (VT) \ ‘ASCH Formised (£7) } oe (Character with octal value 000 inl Nw te mer ee eon es \Niname} | Character named name in the Unicode database (Unicode only) Inthe above table, you see sequences representing \,," Though these characters can be fom te eyburd ut wheused wintery sagen tees ne na pare Pecll Purpose, however, ithese are tobe typed ast, then expe sequence sould be used. (In Python, you can also direclly type a double quote Inside a single-quoted string and vice-versa, eg, “anu is a valid string in Python) String Types in Python Python allows you to have foo string ty (0 Singletine Stings on (i Maltitine Strings (0 Single-tine Sti inet Sete ese sng. se ings that you create by enclosing txt in single nat (Ic ate normally single-line strings, i, they must terminate i . eas this ty typing the following in IDLE ween and see yourselves fexti= “hello. Cooter 2: PYTHON FUNDAMENTALS 29 Python will show yo y Mt an error the moment nt you press Enter _ key after hello sce below) = ee oe be be om bw ee ee ae —s Secor mB se ome ~ tal \7 Jenna | | a are—————— orelsl te 1 (21 Toth = * hate Sytactror: EOL she taming string Literal | te 0 ‘The reason for the above error is quite clear - Python by default creates singleline strings with both single or double quotes. So, if at the end ofa line, there is no closing quotation mark for an opened quotation mark, Python shows an error. (i) Muttitine Strings. Sometimes you need to store some text spread across multiple lies 2s cone single string, For that Python offers multiline strings. Multiline strings can be created in fwo ways pce rings ol By aking keh a he df rr singlegute | iin sine aaa Jd a achlash nthe end before presning Ener fo contin ping xt on enc ne orl, - Text =ell\ ona ine ve cnt ae sag mat bmg TO peng irspe irae ras ky Stat) 25th wey Jing figure shows this Tat cracer of sofa sto Following figure show’ be closed with casig quotes ‘an Boigh wen wo th 0). tats Sr ipa oe9 | an (8: Heth» Trg sah Var corres orgie et nei Donotrto cna ent antl Tete ae ‘ing brbevng ang Safa]: Nellore a brates wore corsa tower ‘henay beng vrata yurat COMPUTER SCIENCE WIH PIHON (6) By typing the text im tiple quotation marks. (No backslash needed at the end of in). Python allows to type multiline text string by enclosing them in triple quotation marks (both triple apostrophe or triple quotation marks will wea er ee Foreumpte, . oa Jeg tn ca mercies i vers, ips one Tere Cone 11 Cheers. ‘es a Seet) eoenen str2="*Hello oe eae verte, epee sett Rs ir msn ino) Oo : ined) i ‘This is another wultéline string. mu Se Size of Strings Python determines the size ofa string as the count of characters inthe string, For exmple sizeof string “ab” is 3 and of ellos 5. But if your string literal has an escape sequence contained within it, then make sure to count the escape sequence as one character: Consider sm ‘examples given below ay sizes 1 (\\is an escape sequence to represent backslash) ah sizeis3 mat" sizes? (\aisan escape sequence, thus one characte) "Seana\’spen’ seis 11 Fortyping apostrophe (sig, ecape sequence hasbeen "says" sizeis4 Python allows single quote (without escape sequence) 8 ouble-quoted sting and vice-versa a wopter 2 PYTHON FUNDAMENTALS 31 For multiline strings created wit trings created with triple quotes, while calculating size, the EOL (end-ofline) character at the end of the line is also counte Fe string Str3 as : yunted in the size. For example if you have created a Pathan | str “hele i ecsettte me eau then size of the string Str3 is 5 (three characters a,b, ¢ and two EOL characters that fol characters a and b respectively). traces tet low For multiine strings created with single/double quotes and backslash character a end ofthe line, while calculating size, the backslashes are not counted in the sizeof the string; also you cannot put EOLs using return key in single/double quoted multiline strings eg, : “The size of sting Sts 3 (nly characters robackslash counted) [Re ‘To check the size of a string, you may also typelen(«stringname>) Use lenobst command on the Python prompt in console window shell as teste or lent shown in the following figure : a mer 28 ce a n (3): sted = Senuthor: sunita “se aud mine see tis cout EOL careers the oe of he ting ‘Sgleloubie quoted stings ‘typed ull ine with at thoond teach termed re dont count nthe az of esting. tn [2]: sted = 0) an BAA sen( sta) Sabor 5 ro (a): ents | ee Tile quoted mine ses | wish | ou Ot caactersin he te | Ft sting bat do no ot snes tacktes (\) at ee of — 0 emai 2.3.38 Numeric Literals Fee teats inPybion can blengtoany ofthe follwing diferent ume Ps signed integer) sften called just integers or ins, are postive or negative whole es“ ote ain dsl pa vt represent real numbers and are writen with a decimal ptt font ating pineal aie) he ge ai racionl ps. : sof te form a+ J, where a are oats and J (nj) were complex Complex number) a He Gay mb) ae par fe Yeas the imaginary pat 32 COMPUTER SCIENCE WITH PYTHON ‘Let.us talk about these literal types one by one. Integer Literals Integer literals are whole num! bers without any rational method of writing inte constants has been specified any fractional part. The method of writing integer in the following rule An integer constant must have at least one digit and must not contain point. Tt may contain either (+) or (-) sign. A number with no sign is assumed positive. Commas cannot appear in an integer constant Python allows three types of integer literals (9) Decimal Integer Literals. An integer literal consisting of a sequence of digits taken toby decimal integer literal unless it begins with 0 (digit zer0). For instance, 1234, 41, +97, ~17 are decimal integer literals, (ii) Octal Integer Literals. A sequence of digits starting with Oo (digit zero followed by letter 0) is taken to be an octal integer. For instance, decimal integer 8 will be written as 0o10 as octal integer. (Bip =10,) and decimal integer 12 will be written as Ool4 as octal integer (12) = 14) An octal value can contain only digits 0-7 ; 8 and 9 ar invalid digits in an octal number i, 0028, 0019, 00987 etc, are examples of invalid octal numbers as they contain digits § and 9 in them. (iit) Hexadecimal Integer Literals. A sequence of digits preceded by 0x ot OX is taken 1 be ‘an hexadecimal integer. For instance, decimal 12 will be written as OXC as hexadecimal integer. Many programing ranges ‘Thus, number 12 will be written either as 12 (as decimal), sh as © Co, and exon Python ol (as octal) and OXC (as hexadecimal), 2xtoohave two pes forages A hexadecimal value can contain digits 0-9 and letters (or stil tga) a ‘AFF only ie, OXBKS, oxPQR, Ox19AZ etc, are examples of SE eel 8 invalid hexadecimal numbers as they contain invalid {ype sss msthar aoe letters, ie, letters other than ACF. lone tegersandcan suppor a soalland integers Floating Point Literals Floating literals are also called real literals Real literals are numbers having fractional parts These may be written in one of the to forms called Fractional Form or the Exponent For. 1. Fractional form. A real literal in Fractional Form consists of signed or unsigned digits inckuding a decimal point between digit. ‘The rule for writing a real literal in fractional form is, ‘Areal constant in fractional form must have at least one digit with the decimal point, either before or after, It may alzo have either + or ~sign preceding it. A "ea constant with no sign is assumed to be positive. ‘The following are valid real literals in fractional form, 20, 173, ~130, ~ 0.00625, .3 (will represent 0.3), 7. (wil represent 7.0) CChopter 2 PYTHON FUNDAMENTALS ‘The following are invalid real literals 7 (No decimal point) +1712 (illegal symbol) 17250262 (Tuo decimal points) 17,250,262 (comma not allowed) 2, Exponent form. A real literal in Exponent form consists of fo parts : mantissa and exponent. For instance, 5.8 can be written as 0.58% 10" = 058EOL, where mantissa part is 0.58 (the part appearing before E) and exponent parti 1 (he part appearing after E). EDI represents 10° ‘The rule for writing a real literal in exponent form is . A real constant in exponent form has two ports : a mantissa and an exponent. The mantissa must be either an integer or a proper real constant. The mantissa is followed by a letter E or e and the exponent. The exponent must be an integer. ‘The following are the valid real literals in exponent form : 152E05, 1.52607, 0.152E08, 152.0608, 152E+8, 152004, -0.172E-3, 172.63, 25E-4, 3.63 (equivalent to 3083) (Even if there is no preceding or following digit of a decimal point, Python 3.x will consider it right) ‘The following are invalid real literals in exponent form LE (No digit specified for exponent) 0.723 (Exponent cannot have fractional part) 17,2502 (No comma allowed) [Do ead following discussion ater it] rather Python treats them as Numeric values with commas are not considered int or float value, tuple A tuples i a special typein Python that stores sequence of aes (You wil tuples in coming chapters ~ for now just understand a tuple asa sequence of eaucs only.) ‘The last invalid example value given above (17,225e02) asks for a special a asa mention here. learn about ‘Any numeric value with a comma in /2" (2): b= 37,225662 seminar Pome temeagea (lth wee tig tt an [5]: 2 oueis]: (1, 234) > (a7, 2250.0) COMPUTER SCIENCE WITH PYTHON ~ x 2.3.3C Boolean Literals A Boolean literal in Python is used to represent one ofthe two Boolean values i, True (Boolean true) of False (Boolean false). ‘A Boolean literal can either have value as True or as False. 2.3.3D Special Literal None Python has one special literal, which is None. The None literal is used to indicate absence of value. Its also used to indicate the end of lists in Python. 1m 1) Dasa The None valuein Python means “Thee aes} | Scannghon & pe ulin” or Tees ) canoe nothing hee” Python does play ; ra anything when asked to. diplay the lon car) pint (ato) value ofa variable containing value as ta. ‘Tr and Flare he ocean itera values in "None iter! represents ofa vaue - fin tak weet 8 | ‘None. Printing with prin statement, on the other hand, shows thatthe variable contains None (see figure here). Boolean ras Tue, Fale Special Iteral None ave fultin consansfterae of thon. Python supports literal collections also such as tuples and lists etc. But covering these here would make the discussion too ‘complex forthe beginning. So, we'll take them ata later time. Basics ABOUT TOKENS (P—__ rograss In Python 2-1 Sit Spyier IDE shnoigh Anaconda Navigator or any other IDE of your choice, 1. In fom of he Python the same order (0) Waite the expected result and then write the actu (©) Do write the reason(s) behind the result ret Solved Sample Prompt In in IPythonConsole, type the following statements one by on, al result that Python retumed, umed by Python, ‘Statement to | Expected | ‘Actual oi ea aq _betyped | rest resut Een ue to abe123 but shows nating Value of abc123 is displayed on seeen Please check the practical componen-book ~ Progress in Computer (cocaine ree 3) under Chapter 2 after Practically doing it on the computer, potece (Chopter2 = PYTHON FUNDAMENTALS Ve 1 p a 10, um at es? How many ipso Ura te salen ae How may tpt of tge ita ae Atowed ta Fthon ? How a ty writen hy ae ect and ype tng expe sence? ‘Which escape sequences represent the newt acter and” tps Grater“? An ape tegen ‘epsents how many cree at sr eshte in ton ? How muy aps can ou ee Sng tte in Python ? he the any Airc in hem ? Wat is meat by 2 Rtg pe leat in yon? ow many ee cn ‘stig tel be ered te? Mite the nig ventas te ene fw 23:17, 7216, 00005, 0338 ete the faving sl constants ito fetal om Oust, eAi7EOt, Es, rebate at ae the te Bon els Prien? ne me bun eof Prten ut ofthe owing es, detenine thar pew dein / weal 7 exe nt er 6 oating pan ar feel expen fom sng Ue ether? Tes, O26, OB", “ADC tase, 03801, aH, None, rue, False What kind of program elements are the folowing ? “4, 630005, “0°, “main”? What will yak and vard store vith statements: varl = 212182 and ar2 = 02,1282? What ae the types ff valves sored in vark and var? ? 2.3.4 Operators _ Operators are tokens that rigger some com applied to variables and other obs in or epee Variables and objects to which the computation applied, are called operands. So, an operator requires ‘some operands to work upon. “ues The following tst gives a QZETTT brief“ descrption of the operators and theirfuncions a, sam tt] / operator, in details, willbe schon won spin covered in mext chapter = and ote oyees ee, Data Honing. eresion Unary Operators ‘nary operator ar thse operators tht mi one oper to operate up, Following are some uray operat * Unay pus Unary ins Bit complement tot logical negation Binary Operators Binary operators are those operators that require two ‘operands to operate upon. Following are some binary operators Arithmetic operators + Addition = Subtraction + Multiplication J Division % Remainder) Modulus = exponent (aise to power) a Bitwise operators & —Bitwise AND > Bitwise exclusive OR (XOR) 1 Bitwise OR Shift operators << shift let >> shift right Identity operators s fs the identity same? isnot isthe identity sot same? 46 IMPUTER SCIENCE WITH PYTHON Assignment operators Assignment Relational operators os thaw Greater than (Assign quotient {een than ot etal + Assign sum Greater than or quali + Assign product Hiqual te Assign remainder Assign difference 1 Not equal we "+ Asaign Exponent Ji Aesig Bloor division Momborship operators Logical oporators ond Lagical AND in whether variable in sequence or Logical OR ol in whether variable not in sequence Jw course, Giving descriptions and examples Punctuators are symbols tat More about thee operators you will leat ith mc powible right here at the moment is not feanil 2.3.5. Punctuators Punctuators are symbols that are used in programming languages to orgie nrtenes sutures, and india thes wand" pepo shythm and emphasis of expressions, statements, and esto orga propamming sentence | Program structure Structures, and indate te Most common punctators of Uython programming language cyt and emai ‘expressions, satemen, prowom stucture | "HVOTIOB = The usage of these punctuators will be discussed when the need arises along with normal top discussions, LeT us REVISE a Athen sth sales Individual unt n program. en pres flowing thes kowa, Keraiers(ane), Values (era), punctutors operator and commer % Abepword isa reserved word carrying ipecal meening and purpose 2 Identifiers are the wser-defined names for ferent parts ofthe program % In Byton, a Ideniior may conan eters (a2, 2), gh (09) anda symbot C. Howere, Identifier must begin witha leer or underscore: ll letersi a denier are icant © Literals are the Ped wales © gon alls following Merle: svi Mera, numeri (integer, Rowing poi eras, otean ters, 50 eral None and thera elections) : © Operators ote tokens Ih tegyer some computation / action when applied to variables and other objet 2 emresion mcr re yb ed rine progr seen Srictres nd indice the rn ond ena ceressions, saserents and program-srucare soles 2 PYTHON FUNDAMENTALS 24 BAREBONES OF A PYTHON PROGRAM {Let us take our discussion further. Now we are going to tlk about the basic structure of Python program ~ what allt can contain. Before we proceed, have a bok at following sample code. Look t the code and then proceed othe discussion that follows Don worry ithe ings 2 not lear to you right now, They become clear when the discussion proceds. This progr shows a progran's components Definition of function Seevout) Follows commana Bt Se8H0i() re amt ON print Tine to sy "Main progran-code Follows now 15 be = psoas print. cS a oe af vost 4 colon means 1075 _-» print ("Value of 'a'was more than 45 ir (ended al Indies comments else: te mi) “oa. print ("Value of '#'was 15 or less initially.") Seevou() # calling above defined Function Seevou() ‘As you can see that the above sample program contains various components like © expressions © statements ‘© comments © function ‘© blocks and indentation Let us now discuss various components shown in above sample code. (i) Expressions ‘An expression is any legal combination of symbols that represents a value. An expression represents something, which Python evaluates and which then produces a value. Some examples of expressions are = svunatay ol Cn Fr} gin tha oe ar ony m eg Combination of symbols that ars compe renin ht produce represents a value, +5)/4 J seen alate ‘Now from the above sample code, can you pick out all expressions ? These are: 15, a+10, @43, b>5 - tv oa pvygrann tenia MT Astin th that doy a nv taba pla DEINE CHET) AIH statement cats eta tame Ho White aun oape nat mecensary tha Anditis Astana excites oo may ‘ray nat yl a vie (i) Commons Lconmints Comments ate th whichis amen the aon 1 source cade. omments in Python Baga wah sol Wand gery en wth nd ot the phat ine axonal ada i uly the program 1m Python, comm characte) wi ignore by Python inerp ne nts bein ath symbol (Pow oe fo with een ot p the abv coe, you ean see four games The physical tines begining ith # a comments i the abuve prog © the fall Line comments, ‘here an Hr ful fine (Ths program shows a progran’s component's Definition of function See¥out ) FoLtexs ‘Main program code fol ows now Pha ne the one ett yout {The fourth comment is a inne comment as it stats in Sm tine | the middle of 9 physical line, aftr Python conte (ce Oeone en ba below) one ful tatement 15 :W colon means it requires a block Multi-line Comments What if you want to enter a multi-tine comment oF a block comment >, You can enter a ‘multi-line comment in Python code in fw ways ()) Add a # symbol inthe beginning of every physical line part ofthe multi f MULti-Line comments are useful for detal Led adit cnal information, ‘Related to the program in question. 1 Ithelps clarify certain important things 2 THON FUNDAMENTALS 39 (9, Type comment as a triple-quoted multiline string e., tutti Tine coments are useful for detailed additional information related to the program in quest ion Tthelps clarify certain important things ‘This type of multi-line comment is also known as dacstring. You can either use triple-apostrophe ("") or triple quotes (°"") t0 write docstrings. The docstrings are very useful in documen- tation ~ and you'll learn about their usage later. ) Functions ‘A function is a code that has a name and it can be reused (executed again) by specifying its name in the program, where needed. In the above sample program, there is one function namely SeeYout ). The statements indented below its def statement | fnaton is» code that has 2 are part of the function. [Al statements indented at the same level below def SeeYou ) are part of SeeYout).| This function is erected asin) by specying executed in main code through following statement (Refer to 1 tame inthe room, where sample program code given above) need Seevou() # function-call statesent Calling of a function becomes a statement og, print isa function but when you call print() to print something, then that function call becomes a statement. For now, only this much introduction of fanctionsis sufficient. You will larn about functions in details in Class 12. (¥) Blocks and Indentation Sometimes a group of statements is part of another statement or function. Such a group of one ‘or more statements is called block or code-block or suite, For example, ar paces iter mark «AEDS? This ia Hak with al Tree net oe! f print (value of 1s ess than 5. ii ck tha print (“Thank you.") a level. Many languages such as C, CH, Java et, use symbols ike curly brackets to show blocs but Python does not use any symbol fri rather it uses indentation. Consider the following example cE ry = ‘group of statements which are part of ad nother satement oF function tmp =a Tiina Hook par ff steno Caled block or code lok o suit 9 see 4 Nore al aoe ame Bak ae have same inden ot = b=tmp ‘is aero i nc pat of print ("hank you") Rg et ia fe ‘A group of individual statements which make a single kis also cal Python. Consider some more examples show n ef check() Th dif pease T inicio be AF €< 50 ‘(Less than sa") 2 — “anasie Print ("250") mae? b=b+10 Statement Termination P, Maximum Line Length Lines and Indentation Blocks of cae are denoted Blank Lines Use two ‘Avoid multiple statements on one line Doxstring Convention Cor ple double quotes (—) Werscore to separate wondsin + CamelCase by capitals sAmount or loanAmoumt Utena 9. loan_amount ‘copes 2: PYTHON FUNDAMENTALS 41 COMPONENTS OF A Pi eee Progress In Python 2.2 ‘This is another program with different components dof Firstswultipies( ): main code Fill the appropriate components of program from the above code. Please check the practical component-book ~ Progress in Computer Science with Python and fil i thre in PrP 2.2 under Chapter 2 after procticaly doing it on the computer. seotece 2.5. VARIABLES AND ASSIGNMENTS ‘A variable in Pytlwn represents named location that refers to a value and whose values can be used and processed during program run. For instance, t store name ofa student and marke of 4 student during a program run, we require some labels to reer to these mark so that these ean be distinguished easily, Vara, called a syndic saris, (eran serve the purpose. The variables recalled symbolic variables {OS because these re named label. For instance, the following, wae scan statement creates a variable namely marks of Numeric type Frame aca Yr marks = 78 = 2.5.1 Creating a Variable Recall the statement we used just now to create the variable marks marks = 70 0 Henin sae and J you can se, that we jut signed the valu of numer pet an ent ‘ion cen in variable of the fp snd f the typ of ale ang In sho fe be Tove vatment we any ht mark mer vorble So coating variable was jot hat sinpl nl? Yes you ae right In Python, to creat variable js assign same the value of appropriate type. Fer example to cents vag namely Student to hold staden'sname and variable ag ld student’s age, you just need to write some is shown below Student ="acob age =16 Python will internally create labels referring to these values as shown below sen =} — a] “Gl Isr it simple?? © Okay, let's now create some more variables. ‘TrainNo = "Te1234 variable created of string type variable created of muneric( floating point) type balance » 23456.75 FollNo = 205 ‘variable create of Numeric(integer) type Same way, you can create as many variables as you need for your program. IMPORTANT ~ Variables are Not Storage Containers in Python Ifyou have an earlier exposure to programming, you must be having an idea of variables. BUT PYTHON VARIABLES ARE NOT CREATED IN THE FORM MOST OTHER PROGRAMMING LANGUAGES DO. Most programming languages create variables as storage containers ¢.¢, Consider this : age =35 age=22 Firstly value 15 is assigned to variable age and then value 20 is assigned to it. 4622 es nee ¥ Variable age is created as a container at a memory address, say 202530, and it stores value as 15 init Notice memory address location of variable age did not change with | hangin its value age=20 ee y 20 Now this statement will change the contents of the 50 Statement location where variable age is created, ic, ‘With this statement, the location of the variable did not change, only its contents changed, ‘This is ow traditionally variables were created in programming languages like C, C+, Java: | rst CChoptee 2: PYTHON FUNDAMENTALS Python's Handling of Variables Rens Fondling of Variables BUT PYTHON DOES THIS DIFFERENTLY Let us see how Python will do it, Memory has literals/values at det aoe t defined memory locations, and each memory location has a Wn you give statment ge 5, vale poining ; , vasa age willbe eed atl pointing tren location where value 15 is stored ic,, as. : i ta hes fhe fir ahha f© | age now refering to action 20216 that has valve 15 | aoe | ‘And when you give statement age = 20, the label age will not be having the same location as earlier. It will now refer to value 20, which is at different location i, fats hehrtete to | a i | Now age refer to locaton 20236. © ae So this time memory location o Jble age’s value is changed. ages. The “Thus variables in Python do not have fixed locations unlike other programming languas location they sear te atanges evry thei values change (This rales not fr al pes of xe cjables, though). [twill ecome clear to you in the next chapter, where we talk about Mule ‘aud rmmutable types. 44 i. Wales ond Rvalves 2.5.2 Multiple Assignments Broadly loalue and roaiue can be thought of as Nwalue : expressions that can come on the Is (left hand side) ofan assignment "volve * expressions that can come on the rhs (right hand side) ofan assignment 8, you can say that Pe wes eth ten 2-20 bee ‘Sees kone Ine ov of an sng But you cannot say Nv me oe be tee ‘rrerons tha are agree alos Rvs can cameo, ofan esigrmert sateners ‘The literals or the expressions that evaluate a value cannot come on Ths of an assignment hence they are rvalues but variables names can come on Ihs of an assignment, they are Ivalues, Lvalues an come on aswell as hs of an assignment ~ ra nrmen, ' vate mee, Python is very versatile with assignments, Le’s see in how jam ‘many different ways, you can use assignments in Python = 1. Assigning same value to multiple voriables You can assign same value to multiple variables ina single statement, ¢., » 1 will assign value 10 to all three variables a,b,c That is all thre labels ec will fe to same location with value 10. 2. Assigning multiple volues to multiple variables You can even assign multiple values to mulple variables in single statement, ¢ x,y) 210, 28, 30 It will assign the values order wise, ie, frst variables given first value, second variable the second value and so on, That means, above statement will assign value 10 to x 20 to y and 30 to = ‘This style of assigning values is very useful and compact. For example, consider the code ge below : x y=25, 50 print (x, ¥) It will print result as 25 50 2: PYTHON FUNDAMENTALS just need to write Yay x print (x,y) Now the result will be 5025 a,b, c=5, 10,7 b,c, asad, b+2,c-3 Print (a, by ¢) statements # statenent2 © Statement! assigns 5, 10 and 7 to a,b and c respectively. ‘© Statement2 will first evaluate RHS ie, a'+1, +2, = 1 which will yield 541, 1042, 7-1-6, 12,6 ‘Then it will make the statement (by replacing the evaluated result of RHS) as : by c)a=6, 12,6 ‘Thus, b= 6, c= 12 and a=6 ‘© The third statement print (a,b, ¢) will print sen Isnt this easy ? Now can you guess the output of following code fragment? P.q=3,5 @ r=p-2, par print (p, 4, ) Please note the expressions separated with commas are evaluated from left to right and assigned in same order e.., x=10 Ys Y= XD, X45: will evaluate to following (after evaluating expressions on ths of ~ operator) yo ye22, 15 ice, firstly it will assign first RHS value to first LHS variable i., yea then it will assign second RHS value to second LHS variable ie, yeas. - ‘will contain So if you print y after this statement y will : 46 COMPUTER SCIENCE WITH PYTHON ‘Now, consider following code and guess the output 4028, 38 Ys Y=X418, x4 20 print (x, 9) ‘Well it will print the output as 30 50 Now you know why 2 2.5.3 Voriable Definition So, you see that in Python, a variable is ereated when you first assign a value to it. It also means that a variable is not created until some value is assigned to it, ‘To understand it, consider the following code fragment. Tey running it in script mode print (x) 20 print (x) ‘when you run the above code, it will produce an error forthe first statement line 1) only ~ name 'y not defined (see figure below) eectnimiey 8 real a oan ao oud - ase ek ra TP oy ei pron ae) Fe “cipythan-input-1-<03860f486", Line, in cond ‘it ileCt:7Python Nrk/i n'y vita" t2 Python work”) Fite “C\Propraoata\araconda\ 1b stephan pyar \tiaite ‘eceie(filoame, wamespace)| Fle "c:\propraoata\anaconda\Lib\te packages spate \tileaite Jtecustontespyry ine 18y in ect | "soe ontie( eed), ilenoey "see ranepace) a ch The reason for above errors implict As you know that cara isnot cented until some values assigned to it, So, variable x isnot created and yet being printed in line 1. Printinglusing an uncreated (undefined) variable results into error. So, to correc the above code, you need to fis assign something, tox before using i ina statement, somewhat like xe0 ‘variable x created now ‘Avaraie i ined on when int (x You anign some wale to © ce ang an ndsined vad ae an exressan/tateent ae print (x) anerror cated Name for [Now the above code will execute without any error. CChanee 2 PYTHON FUNDAMENTALS 2.5.4 Dynamic Typing In Python, as you have learnt, a variable is defined by tit hae (of a variable is assigning to it some value (ofa particular type such as numeric, string etc) gee For instance, after the statement x=18 We can say that variable x is referring toa value of integer type. Later in your program, if you reassign a value of some other type to variable x, Python will not complain (no error will be raised), eg, x=10 ee print (x) | varie pointing to 2 ue of X="Wello Word” 1 certain pecan be made point to '2 value/object_of| print (x) ferent ype. Ths i cals Above code will yield the output as: ites 10 HeTTo world So, you can think of a Python variable as labels associated with objects literal values in our case here) ; with dynamic typing, Python makes the label refer to new value (Fig. 2.1). Following figure illustrates it x10 :— Ee 7 ae Figure 2.1 Dynamic typing in Pyton variables [As you can see in Fig, 21, variable Xs frst pointing toreferring to an integer value 10 and then to string value “Hello world” ie Please note here that variable X does not have a type but the value it points to type. Soyou can makea variable point ta value of diferent type by resssigninga value ofthat Ye} Python will not raise any ero. This called Dynamic Typing feature of Python. Coution with Dynomic Typing : ‘comfortable with changing types of variable right types for certain type of operations, Fore cyt 2 PYTHON FUNDAMENTALS 53 Features of print statement ‘The print statement has a number of features © H auto-converts the items to strings ie, if you are printing a numeric value, it wil automatically convert it into equivalent string and print it; for numeric expressions, it first evaluates them and then convert the revutf sing, efor panting (as i id i exarple statement 2 above) ae he * IMPORTANT : Wih print), the objecsitems that you give, mistbe convertible to string type Covering it here with examples may derail our discussion so we have given examples of using Drint() with diferent types of arguments in Appendix B. Please do refer to Appendix B. © it inserts spaces between items automatically because the default value of sep argument is space”). The sep argument specifies the separator character. The print) automatically adds the sep character between the items/objets being printed na line. Ifyou donot give any value for sep, then by default the print() will add a space in between the items when printing. Consider this code Fou dint sing acs wt no = tna a be ine Print ("My", "name", "is", "anit. will print us he out ine has uteri paces er in My mame is amit. +———— tener tem trae deel sep characte pace ‘You can change the value of separator character with sep argument of print() as per this ‘The code print ("My") Ast, "Amit.", sep= 2.1) will print penne « This ne dhe pint) sported the ems My. smame...45...amit. hg sop lane he is © it appends a newline character at the end of the line unless you give your own end argument. Consider the code given below : print ("My name is Amit.") Roe print(*r am 16 years old”) 1 print | function without any It will produce output as value oF name or expression eee Prints 2 lank line. Tam 16 years old So, print() statement appended a newline atthe end of objects it printed, ie, in above code: Myrane is Amit. J or \n + ___ eon autamatialy aed a mtn cascer Ape inthe end of ln pried so athe net Tem 16 years old. print) pints from the net ine ‘The print() works this way only when you have not specified any end argument with it because by default print() takes value for end argument as ‘in’ ~ the newline character’ ¢. A newline isa character used to represent the end of a line of text and the beginning of a new line. . COMPUTER SCIENCE WITH PYTHON you explicitly givean end argument with a print() function then the print() will print theling and end it with the string specified with the end argument, eg, the code print(°W nane is Anit.", end = *$") print(-T.an 46 years old, *) vel print output as Thi ti he pit en a i paves Fred rr he he ty nae Ss Anit. $1 an 6 years old, So the end argument determines the end character that will be printed at the end of print line, Code fragment 1 In int) funtion, the value of end srgument ‘newline character (9 oa seve i ring SURAT is: 2,8, end= 0) nied mince =e Now the output produced will be ike a=20 Tei bes ef end = pi) The reason for above output is quite clear, Since there is end character given as a space (ic, end =’ ’) in first print Statement, the newline (\n') character is not appended at ‘eyo the end of output generated by frst print statement, Thus aren the output-position-cursor stays on the same line. Hence ranue 2* "SBE led mbt utp af second pei seme appears in the same Creat ves for the flowing line. Now can you predict the output of following code (Oto bold a tan manter fragment? (ito bot te name ofa subject (it) to hold talance amount ina bank () to held phone runber What do you mean by dynam typing of avr? What the caution you Wel, you guessed it right. © It is mut take cae of? . oat hipes when you ty to acess ‘e210 Enthustast the vale of an undeined vate ow do you Find Python? What is wong wth the flowing sitenet uber = snout Nnber*) Sar Nuber*nunber rite Python code to. obtain. the Inlance amount Print ("Hello", \ <——— me Waite code to obtain fee amount and ende') : then eluate fe hike at 10% of fes feet «0.0, Now consider following sample programs Nane ="Enthusiast! print (Mello", end = «) print (Name) Print ("How do you Find Python 2") hope 2 PYTHON FUNDAMENTALS 55 Pp 2.1 Program to obtain three numbers and print their sum, em # to input 3 numbers and print thetr sum nt Anput ("Enter number 2: ")) int input(“Enter number 2: *)) rund = Ant( input("Enter nunber 3 :")) SSum= nnd + num2 + nas print ("Three nunbers are pent ("sum is =", Sum) rum, num2, num) The output produced by above program is as shown below ner nurber 1: 7 enter number 27 3 enter number 3: 13, ‘Three numbers are : 7 3:13 sum is: 23 p= Progen New File. and type the flowing cde into it ‘ayNunber = 10 print (myNunber +1) output statement 1 print (ayNunber) output statement 2 Science with Python and ill t there in PriP 2.8 under Chapter 2 after ¢ Please check the practical component-book - Progress in Comouter ) practically doing it on the computer. pootecce LET US REVISE ——— Paton program con contain aru component te epresins, semen, commen’, fats, ck ad net ‘An exression iso legal combination of symbols that represents 0 vale. A statements «programing inseuton Comments are nonerecucble,addtonltormation added in program for readabiy In Python, comments begin with # character Comments can be singltne comment, mul-lne commen and iline commen Function isa named code that can be reused witha program + A Dlckstlcode-blck ia group of semen that are part of anther statement Blocks are represented trough indentation. 4 Avorable in Pythons defined only when some value i assigned tit 4 Python supports dynamic ying Le. avaiable can hold vlus of deren types ct diferentes. The inputs sed obtain np from wer it always reurs rng Ope of ale Cap is generated though print) (calling prin function) statement. ° Capon 2 POBON FUNDAMEN 57 Solved Problems OO What isthe ifere Solution. Keyword isa special word that hana spa and area few. For example, eae hey Identifier is « user defined ; cl name given to a part of a program vi, variable, object, function et enfant nerve Th a fi y th ner ul hy cn hae tiers digits and symbol underscore They must begin with either keller ar undemsene, Fur inate al ‘etc are identifiers in Python. : «etiwanda a entific sning anv purpane, Keywords are reserved What are tras in yon? Hone many types of Heras ae allied in Python ? item that never change thet value during» progam Solution. Literals mean constants ie, the da run, Python allows fie types of tras (0 String literals (i) Numer literals (ii) Boolean literals (io) Special Literal None (@) Literal Collections lke tuples ists et ‘How many ways are therein Pythow to represent integer trl? Solution. Python allows thee types of integer literals (a) Decimal (base 10) integer literals (6) Octal (base 8) integer literals (6) Hexadecimal (base 16) integer literals (oy Decimal Integer Literals. An integer Iiteral consting of 2 veuence of digit is taken 1 Be tlecimal integer literal unless it begins with 0 (digit 27). For instance, 1234, 41, +97, 17 are decimal integer iterals () Ocal integer Lites, A sence of digs stating with do (it zo flowed by ees ©) oat be ex cca integer For instance decimal integer 8 will be written 25 0010 as octane Gan i0,) and decal integer 12 wll be weiter 258 as ota integer 129s) (or Hevadesimal Integer Ler. sequence of igi preceded by Bro BX sake 10 Bean hexadecimal integer. 12 willbe written as OXC as hexadecimal inter. For instance, decimal mal) do14 (as octal) and OXC (as hexadecia) ‘hus number 12 willbe writen ether as 12 (as es Wha wil be the ies offing constants Nay Naty Reenal's's ae ees we? ye" ss Solation eee is Lay theres character ecape sequen) angie aM literal enclosed in single quotes 1 character enclosed in double quot sya" Sizes 1 asthe 58 COMPUTER SCIENCE WITH Pi, Reena\’s" Size is 7 because itis a string having 7 characters enclosed in double quote, escape sequence for apostrophe and is considered a single character) Size is 1, It isa character constant and is containing just one character \" Sizeis 4, Python allows single quote without escape sequence in a double quotes aoe and a double quote without escape sequence ina single quoted string. "m., a we Size is 4. Ibis a multiline string create with \ inthe basic string, oy ye""" Size is 5. Triple quoted multiline string, EOL (.) character is also counted in sin How many types of strings ee supported in Python ? Solution. Python allows fav string types Strings that are terminated in single line © Singletne Strings Strings storing, multiple lines of text. Gi) Muti-sine Strings ‘How can you erate multi-line strings in Python ? Solution, Multi-line strings can be created in hv ways (0) By adding a backslash atthe end of normal single-quot» or double-quote strings eg, Text = "welcome \ To\ yeon (©) By typing the text in triple quotation marks, (No backslish needed at the end of line) Str ="**Welcone To Python ‘What factors guide the choice of identifiers in programs? Solution. (0) Anidentifer must start with leer or underscore followed by any numberof digits and/or kites. (id) No reserved word or standard identifier should be used, (i) No special character (other than underscore) should be ireluded in the identifier. Write the lowing real constants in exponent form : 17.251, 151.0, 00081, 452. Solution (© 17251=0.17251«10* = 017251602 (i) 15102 =0.15102%10° = 0.510203 Gi) 0.00031 =0.31%10- = 0316-3 (ie) 0452 =0.0452x10' = 0045201 What és Nome literal in Python ? Solution, Python has one speci ‘The None literal is use to indicate something that has not yet buen created in simple words absence of value. Its also use to indicate the end of ists in Python PITHON FUNDAMENTALS, 3 Identify the types of following ters? B72) Te True Tr” False falbe™ —OXFACE outs 04789 23789 Floating point 23789 integer True Boolean “True! sting “True” Sting False Boolean False" String OXFACE, Integer (Hexadecimal) 00213 Integer Octal (0789 Invalid token (beginning with 0 mean iti otal amber but digits 8 and 9 are invalel digits in octal numbers) None None 1, What isthe diference betwen an expression and a statement in Python ? Solution, Statement Programming instruction as pr Pyhon syntax Does something Python executes it [Need mot result in a value Expression Legal combination of symbols Represents something, Python evaluates it End result i a value Examples Exemple 23 print ("Hello") era/4 ifaro: Which of th following are syntactically corect strings? State reasons (@) “This course is great!" (6) ‘She shouted "Melo!" very loudly.” (©) “Goodbye” (id) “This counse ds great!" (@ "Welle *r Liked the movie “Bruce Almighty” very much, i) and () are syntactically correc. (Str ile quotes inside them and vice vers.) onrct because opening ard closing quotes cont match use it has no closing, quotes soe Stings ( (). ings (b) and (fare also valid as single {quote strings can use dou! String (©) ( "Goodbye" ) is i String () ("Hello is invalid bes 5. What isthe ror in following Python program ihe srenent print ("My nane 1s", nae) Suggest a solution. 60 COMPUTER SCIENCE WITH PION Solution The above: statement is trying to print the value of an undefined variable name, Th, Alfine the variable name before using it, sahation to abv probl ame "Tanya print ("My name is", name) sing cle is mt giving desire outpmt, We want to inpue value as 20 and obtain output as 4, Cot ow pinpsint the problem ? Number = input( "Enter Number ) DoubleTheNunber = Nunber * 2 Print (DoubleTheNunber) string, so the input value 20 is returned ss Solution, The problem is that input() returns value sing 20" and not as integer 20, So the output is not 40. Also Print() is not egal function of Python ; it should be print) What would be the correction for problem of previons question ? Solution. By using int) with input ), we ean convert the string into integer value, ie, as Nunber = int (input ("Enter Number" ) ) DoubleTheNuaber = Nunber * 2 print (DoubleTheNunber) Now the program will print desired output as 40 if 20 is typed as input. Why is lowing code giving erors ? rane = "Rehan" print ("Greetings 111") print (‘Hello", nane) print ("How do you do ?*) Solution, The problem with above code is inconsistent indentation. In Python, we cannot indent 8 statement unless itis inside a suite and we can indent only as much is required. Thus, corrected code will be name = "Rehan" print ("Greetings 111") print (‘Hello", name) print ("How do you do 2") Write a program to obtain temperature in Celsius and concert it nto Fabre using formate $Cx9/5+32=°F Solution. 4#Celsius to Fahrenheit els = Float(input( “Enter tenp in Celsius :") ) print (Tenperature in Celsius is :", Cels) Fahr = els * 9/5 32 print ("Tenperature in Fahrenheit is :*, Fahr) PINON FUNDAMENTALS 61 What will be the output produced by following code ? value ="Sinar’ age =37 print (name, *, you ane", 17, “now but", end = “?) print ("you will be", age +1, “next year") Solution Simar, you are 17 now but you will be 18 next year. 0. What willbe the output of following cade ? print (x, y) Solution 64 Explanation. First line of code assigns values 2 and 6 to variables x and y respectively. Next line (second line) of code first evaluates right hand side i, y, x42 which is 6,2+2 i. 6, and then assigns this to x y ie, x, y=6,47 so x gets 6 and y gets 4 Third line prints x and y so the output is 6 4 20. Pract the output of following Kye72 XY KEKE 43, KIO print (x, y) Solution vs GLOSSARY a Constant ‘A dato Rem that never changes is volue during @ program run Identifier Nome given by user for © prt of the prosrom Keyword Reserved word having special meaning and purpose. Lexical Unit Other name of token erat Conston Token ‘The smolles individual unt in © program. ‘Sting literal Sequence of characiers enclosed in ony toe of aves Verible Nad sled location whose volve can be manipulated during program run, Expresion —__Lagol combination of symbols thot represents valve 62 Assignments —_-— —————_ Type A: Short Answer Questions/Conceptual Questions 1 What are tokens in Python ? How many types of tokens are allowed in Python ?Exampl your ansnee 2 How ane hey words different from identifiers? 3. What ane literals in Python ? How many types of itera are allowed in Python ? 4. Can owongraphie characters be used in Python ? How ? Give examples to support your answer 5. How ane fasting constants represented in Python ? Give examples to support your answer. (6. How are stringiterals represented and implemented in Python ? 7. Which of these is nota legal numeric type in Python (a) int (b) flat (c) decimal 8. Which argument of print) would you set for (0 changing the default separator (space)? (i) printing the folowing line in current line ? 9, What are operators? What is thei function ? Give examples of some unary and biniry operon 10, What isan expression and a statement ? 1, What all components ean a Python program contain ? 12, What do you understand by block/code block/suite in Python ? 13, What i the cole of indentation in Python ? 1M, What ate variables ? How are they important fora program ? 15, What do you understand by undefined variable in Python ? 16, What is Dynamic Typing feature of Python ? 117, What would the following code do X 18, What isthe error in following code: X,Y =77 19, Following varlable definition is creating problem X = 0281, find reasons. 20, "Comments are useful and easy way to enhance readability and wnderstandabilty of a program Elaborate with examples. Type B : Application Based Questions 1. From the following, ind out which assignment statement will produce an error. State reasons) 9 i385 yu -F Los A Sehnumber = 3300 {o)lngts 48017 — OL Tylor Instant (hi yoible = 6612 {iy float 178-09 () FLOAT = 0:78 08 2, Fin out de cro) in following ode agmens ane (0 emperature 98 cae print temprature) raat Gi) ab, €°2,8,9 ee print (a8, ©) cb a=ayb€ print (2505 x) (0) else=21-5 print PYTHON FUNDAMENTALS 63 3. What will be the output produced by following code fragment (a)? X10 (i) fast =2 X=xe10 second =3 Xax-5 ‘third = finst * second print (x) print (First, second, third) X,YaX=2, 22 First = inst + second + third print (x, ¥) ‘third= second * First print (First, second, third) (ii) side= Ant (input side) ) aside given as 7 area = side * side print (side, area) 44 What isthe problem with the following code fragments? a3 print (a) bea print (b) seaeb print (s) (i) mane ="Prejith age =26 print ("Your nane & age are”, nane + age) (iy) an sea+10 a= "New" gqza/10 5. Predict the output =a yextd x=20, 4x print (x, y) 6 Predict the output x,y =20, 60 Ye, Yow = 18, 1428 print (x, y) 7. Predict the output ) ab922,33 cba ara, a2 print (a, b, ©) @ abe, print (print(a +b)) 64 1m. 2. a 4. COMPUTER SCIENCE WITH PYTHON Prediet the output a, by €=10, 28, 30 PrQrac-5,a43,0-4 print (*a,b,¢:7, a,b, ¢, end“) Print (‘Pa 7:7, Ps a, r) Find the errors in following code fragment @ yaxss. (print (x=y=5) (qa input “value” print (x, ¥) beala print (a, b) Find the erors in following code fragment: (The input entered is X1) {c= Ant (nput( “Enter your class") ) print ("Your class is", ¢) Consider the following code nase = input What 4s your name?) print (Hi, name, '") print ("How are you doing?") was intended to print output a6 Hi , How are you doing ? tie printing the output ae Hi cname>, How are you doing? What could be the problem ? Can you suggest the solution for the same ? Find the errors in following code fragment = input( “Enter your class" ) print ("Last year you were in class") ¢—2 ‘What will be returned by Python as result of following statements? () >>>-type(@) () >>> typecint(@)) (©) >>>. type ine(“@?)) (@ >>>typeC'0") (©) >>> type(a.e) (0 >>> type(int(a.0)) (9) >»>type(float(®)) (h) >>> type(loat(1.0)) (>>> type( 3/2) ‘Match your result after executing above statements ‘What wil be the output produced by following code ? (a) >99 ste(print())+"0ne" () >>> ste(print(“hel10”) "one" Match your result after executing above statements, Can you explain why this result came? ‘What willbe the output produced by following code ? >>» print(print(“Wola”)) () >>> print(print “Hola”, end = "")) Match your resultater executing above statements. Can you explain why this reult came? 3 Chapter 2» PFTHON FUNDAMENTAS 6s 16, Cavefully look atthe following, code and its execution on Python shell. Why is the lst assignment 18, w. giving ereor 7 >> a=e012 >>> print(a) 20 >>> b= G03 >>> € = 0078 File “>> print (num = Float (input(“valuel:”)) ) eg ee ‘Traceback (most recent call Last): ae “", Line , in cmodule> print nun « float(input(“valued:”)) ) sypeerror: ‘nun? 45 an Snvald Keyword argutent for this function © o> print( Float input(“valuet:”)) ) valued 67 = de ily etd No me pana 67.0 20, Prec the output of the following code days = int(Anput(“Input days: ”)) * 3600 * 24 hours = int input(“Zaput hours: ")) * 3608 sinutes = int(input “Input minutes: ")) * 68 seconds = int(nput (“Input seconds: ”)) ‘ine = days + hours + minutes + seconds Print ("The anounts of seconds”, time) {the input given is in this order : 1, 2,3, 4 Tyee C : Programming Pracice/Knowledge based Questions ane oe tat ply a joke. Bt dspay the punchline only when the user presses enter key (Hint, You may use input ) 2% (RIP Bosra fread tday’s date (only dl pat rom ‘ser. Then display how many the cae team oF today's date nly dl pat ‘Then display how many days are left in 4% Weta program that generates the allowing output 5 5 Seite the program with maximum thre nes ode a, Variables and then prin then Ld of a number to 5 tne ez Program ht acts ads of ce and prints is ' z i z : i > i 2 & : i 2 '& Write a short program that asks ™ Your height in cent 7 faces (ft Be ch 5p SBM ee an comer our hy 9 Write a program to read a umber and print 9,93 ang mt Sho fect and 20. Writ a program ond are of rang. we Pm o compute sip net and compoung Interet 18 (Rot a Progtam to red deta ke name, ls pea ‘udent and then print, eats Fre, 14, Writ 15. TUNG PTOBraM tread thre numbers in thee varaes a SPP Fm 00 vats eg

You might also like