You are on page 1of 174
ala os -B fae daly dal | chapters: Variables &Arithmetic | Dee en ‘The Three Rules + Rule 4: Think before you program Gay hye ese a * Rule 2: A program is a human-readable essay on (65 os da eid problem solving that also happens to execute on a ADL paeiny es Hee OS Slane 2 computer ei Baie pala bal + Rule 3: The best way to improve your programming and eB ed A tnd problem solving skills is to practice What is a Computer Program? Program + Aprogram isa sequence of instructions. A Sy Cag a Mas Ge 5 LE gh ally + Torunaprogram ist os cal create the sequence of instructions according to your design and the language rules turn that program into the binary commands the processor understands ive the binary code to the OS, so it can gve it to the processor 05 tells the processor to run the program when finished (or it dies :-), OS cleans up. OS: operating system ad pe Lose pd Midday NAD Ae pM ga ada old 5211 3) pil HAULS print j0¥ gsi HE Gyula) CLAN Uggs aly yah Lely oats Le plan g UNS Se yl aad ABD gD pM ok oy Ge dal on la pais Sl Sly pula yay Sls CLAS way all JY input Oo ce Ke yn pA ay gS yl 8 Jip an gia 1015 OU) G+ SEs WII A as (binary System) inal Mghags ony gl Oa AU) OA) All gg on ALM Jha = ial Sas gleall fy cts oss - Se) Gy AS YT Sly oT a a A cy ll gly Sl ay Interpreted + Python Is an interpreted language + interpreted means that Python looks at each instruction, one at a time, and turns that instruction into something that can be run. * That means that you can simply open the Python interpreter and enter instructions ONE-AT-A-TIME. * You can also import a program which causes the instructions in the program to be executed, asif you had typed them in. * To rerunan imported program you reload it. a pha 34M ka) an Land AS up AN 4A NA gal) jal) Jha gs ll ay interpreter ga aay 9 saul dal Ee es a Lh ae Ue dy lll Aa el ge tail ge Sl gs ph YE Lhe Gl ay pee Sle i) Day SYN a AS eal es i gd oe le 45 oI ae froma module to another plat! tinal ys SI jals Gian opBe aS Gas pal gl ol pul Leg! iy gy gol Zak 8! cay Lely Gal a Sl pail yan ll Jaa iS le pS cuath ian (nay Keeway O (Ra aie) 5 pall GE LS AL QI ga lh gl Sl Ik Gi gn Dalai BV gpyder tune ll Lua se es 5M GA interpreter J) USI Llp 2 Aas ol yl) YI gl 2,6 4d SS (A Alaa Gs code editor J} 1 5385) ele iY AUS Cyt pine La ty print (4+ 2 a ie ye Gol AILS he syntax G98 Ge A NT LS Gi HS an sales Ge Si ST Sa Uf lp SRG Gd gl ual pS A le ey La ay gal gl Jy De ap 4S Lin! Oe code editor Ji gé x82 8 Sis (output) cu ee eli il SLI Ja yconsole Ui 2838+ the code interpreter yb Ge 13s Cian Bi Sony Aan Cl ab 5 Sip gl LS anh pl Sa Sy Oly 03 2B Sa soiyy 1 HN GFK al SAS fa ale Linc se (Run) Saitll 45 a sly LL 3 I+ abel eg -B fae daly dena CD Sinetron = numeric data Gay) 9 Goad GG eM pay 12 60 4987 663 of as Stel J 5S cs (eal qe) fan ols all LEY Gl (Integer) Mame alse! a Sail oS float 9 integer JS cI Lads (jute! gs) dance yey Tamral Yasee abe 5 (float) Aa ase! Lb “6.9 0.0 69.3 + 5.2 4.0 J+ SURES G55 OI feat De GSES GREASE <= 22 float 0.0 =! Liss integer 0 sl); float > 4.0 2)! Liss integer 4 2s) 2g) Lad Strings Sail ad 2 a sequence of characters € (als 54) pli) sl Gsye elu) jp oe techs uals GE on Jase pee I jaa glee Oley CEA! a Gi ae Vy CNEAY Gt ly Mai) ate 575 BI Gym leg sn string ule Jes I "Python 3.8" se string yo Ss Gaal We Gapeatll GoD i i LOL bash pin gl ae Sibel gk US Gases gat ape Geet EO Ge et Gl Y\ Gal vat aye 7 gst 'ae3's ce als: "python" J gl siagl aS Goal Aan Go pail cl Ly SRG SPOESROBENEWS OI Ll 4s) 6 BAS it J in ayal) De GGG! Gaus DL se Gland Ge She Glia "PYTHON’ papal Gude cup ypane yall! BAY "Testa" 58d cud ll oe string J A Gamat 1) Tis ay Laslasl 6 ply” ye "Testa 31 Testi he G8 AY! Gaz Jy ME 9 LY pene string Ugh Jhb cling (fas Gs sh Testis’ 5 "Testi¥t" Lis Sons Y Us thay logical or Boolean data GHRLA G 3 Min Lp as} expression jus tae Ce Wal se pking False 9 True bel bid Galas Jens Chall Cag Ay oa EO ity ant gf Malas Mal Bll Mab jy 4 Bn Lad GS Sieg SSE gue IS Ll ll Hass Seas we se plthe gd para gy dp Panta ep aiyaed oak Grasaisigerissargsiaass 3, x=a3 integer 59 13 Sls (0) AE pal z ello” string 4©si9"Hello" isis (Z) 94 stall aul var = True boolean +5 True ws (var) 9 At el float_var = 9.6 | float 4© sis 9.6 ius (float_var) 94 ital! aul rigs Jala All cl pall pa! olay (String) Snail itil 21 Alot Las SS (1) 1 (0) cael fade plas Cans tte A string Gs Ge Lak O38 Ly Gopal GIS ai ay easel Fable Gs Saal) GSU ELE a US gels ya ae gel Gamal Ge Geel CHAPTER 1: VARIABLES & ARITHMETIC abel Leg -B hs dah done dl aps Le Cals ual apne ca 7 + 3 Bl Lag) 4 “ABC” “ABC” cans es ad! Sly Mal) all lb gle galas A all gs gf RAIMI £52 9 oe Ladd a ic! 0 We sy Jes ode ee ono BAWS Qi aie ew le Oi hl .20"*3ceTrue A ol! OX! SRS Aws Na git! jal! caasd end 25 suns lll paul aii le 6851 Lad ely BEI A | Gopal 5DE Oy FIA Output print) paki fl8 jowtohLI Aae« print (‘height’, ‘width’ ) height width print() ———_+| print (25008, 10500) 25000 1¢ AB Gt gh EES AiG Ge Lhe 3H prompt LI ee 9) ke A) US) Gp ly USS yd p UpstilGw SIEN GUS Lab PUSS ‘slag ( feub dn J fn A eI) input Abas Jaa ae 5S! 3 Alan Jal Sine gd lp ye 3S any 25S Input Ale oye.y ae U3 ig sta wali ll G8 sy prompt daLus 43 4206 yi! Ga dl console UI Gi sale Laie (console window Ji Gi eLSY! ais (Lai console Ji oe Wiss 5) 4 Example: ely gab ll Gi laste input Has Jeay gis Cand Gi Ya Jas 43) in da 3S TE JS de se prompt Asal print("test") weesa prompt vis print(1) [30]: rant ile( Cs /nera/manlapyler ppl temp-pyy wAlra'G [sera maan] appeerBP) x4 cinput(“Enter your name") ce Shel cea ly enter daa ans As J alo) ei 03) print(xtix2,x3,xa) Stn a gph Leal SS sting Sx pd LIES Gay As a > 5 print oe > snp she erer your mae: Ane 5 0 pn ta import fia) Aaa eh GLE pial 9 90 p55 ASS Guy Gilaphad Ga Ue [import math Jf C4 Hea) All & pea all ia ABN yu SASS ing A ah gh gala aly Ge gal J ele stil gall tans Lew Gyn y Ly Sey ast Leal 3165 LI coe Bihan Gh bases JM eal ye yal ibn I gay La gS foe ang by Jp gal lt Lath alls (2S) niall Bal) pid Je JED G5 import lS 5c (module) Bin OWT Sa gall gh ee Sr ALS a al am ga i ay ag A lS ey we I save bial (py ilu sisi! Lia) desktop Jl le test] iad x) Xi file A0Y Ge save as sb Le qld yl CHAPTER 1: VARIABLES & ARITHMETIC satel Gus! 5 she dap na dl Paro om x Fat Sno ce fat Dagon jh a Yew Dee, eer>RGeGncSeyme Bese fo Smo =1e ~ eeteenencemeced 2 =e le wore = P : seasene E w@ Name: Aws we 2017899 pot are (file > save as) 6h geste inl, test Ge rah reste! 9-4 test2 Xie cil CV! desktop Jide test2 stestl cael pl ckhia Gane AGL GN rmport testa 25 sya os test eked : i J ofl ae spall Gs Lal Spell US ll ys test2.py Aa! Sy Lin! desktop le ais iy 8! gay 6 f= we im (3s renfte( ier mme/Oektgitest2py wr /tne/oman/Oeog gains woes import US Sobor testi J import che $Le gli test] Ge od geal gus tes HUE aloe ae co Min hb ph ty pak 5 test import chee Le su cI desktop J ee ca sine canal lk th test A eZ BG ae ae ie 1 SY ae Se print(e #2) Ss er tll gol Ho Aa gpl WS G85 test dos pie test] cx) 5 Cope itbdelaal Alan cs Hs Zelabll alee G3 test. CS es test ce ll pl gas asl gall ll al 125 is Sas (test2 oz) 25 A $5) Sits $5) al daa pj chy lial ol Ip ll ge als cu aly Ky Ga 8 GS ll iy ba SE GH ENG PRI Se By SEE SHE Bp AT & OR math 8 LsSal os ply sles ton SALOU S ale Sse pal J ad Sy Ll yal Ue (libraries) AB US yo dy Dd SIM aye Sin tan / sqrt / pi / pow W} Ma 52S dylan Cislee plsSiul cy math eles sya Ge gl DEA G8 imathasqrt label JIS Sa sill Se alg! Sip Me J math pi Go ce Uns 5 lee Sa goal eee} import math %2F 7 a, RREEEPMRIARNGe Rie ractos oF she ctrcie £1) Wl float Eo 20 wp. 3 print("Area of the circle is : %.2f" ¥area) (ne GENS) Ral om cathe eg 4M Bains pie ad SS clghad acy) GL pladtil ISL OM math library slgaul a Vy 4s tales Gaal gal 98 input Mag BUS Rah gio) S55 Dill es Spt I y Sa LEYS a AN og Ja aoa gl JR co) Daal dal Le sais 9g! floatfinput...) plasiel ns ya 1S y ob ll Saal) Lyall Ub a any lll nb Cy string West Bea JS ony (cases Desai € pagal C928 > str poe string J sal ge a int essay integerd Ua! gs 3) float ¢ hl Gad gy Lal ce math Ga pi ele siul oi 2( ill dias) * we ged ll Maka Ge yun area oiiall Gi gir G) ea fl gb Aiall Oo im AY 4 se area pitiall And leas Area of the circle : Alas tele oy Mele dea a the 4A! ab s of the circle gIDS gal 5 8 SG pl G8 4S JES pasa Area of the circle is : 50.27 Write a Python program to calculate the area of rectangle? CHAPTER 1: VARIABLES & ARITHMETIC satel Gus! 5 she dap na dl ed cp Daal ag Lag fy al lg tiny phlei agin ll * Upll ga EE ese GA GI REL I yt op EI a Hele te (oy Qh Ad J pe) SOY) Sa Zeta ag yi C0 td al pe Sage * yl ou Atl eo Andy Malad length = float(input (‘enter the Lengt! width = Flost (input ("enter the width: ares = length * width print("the area of rectangle of Length”, lengths \ [ir er rectangle of Length 44.36 and width 223.11 992.5056 “and width", width, area) Absh ey cl tigi d in (66) rune c/ivers/amin/oetraplSeconpy, wire res morneat >] enter the Length: 4.36 Js) Bing SI y Je s poe Ls ol paciall 223,215 44,36 pall Jao! nadia J Siai Aishall 5 pall 26 es ASS ak Cae Gnd oly B18 Ss pall oy ALA Sly Gn 9p OS gal" Gy be print det dag Ll ‘gh ALegl hal gai ll le Ul J print("area = %.3#" % area) Gl float 35 63) area tall Ugh Au js BE %,3f Maal on iy" " J) Gas caGS Lan Gaal 2) ok % 5 RY aay EN gle Seal als pS Mp Wanye aol gat I" Sl al sl 4 (& ple Ulin 3) GIVI a a te jee area = 901.596 teu #8 a: deal! det sal! Alem aes area Example: suppose that the value entered for both input statements is 1 (s ="1",t="1"), what will be printed? S = input("enter a number: *) t = input("enter a number: *) print(s + t) OH" jo MB 1D AY MALS ll pl fag pl aS Masks 8D print Man gu lSLe 1 L&SYI Galee NG JS pasta PRI hei a) ye gage oe he ol pe 8! pai AIS ats pill Alalasy ob) Gol string Jal gal Gis Ge ash Ga (ata ea A (ting es a ats Ap als string cet he SVN ky 11 Ae ay eps 7" = "2" + Example: print("s" +t") > output: st ies Haare gle Sy chan a ie pane sly (outputs alas oS ais Js > ae Al) strings A ca eal ils yy Sal all cay geal) LS + ELEY print(2+2) 34 print("2" + 22 print "Python" + “Tanguage") > Pythonlanguage print("Python" +" "+ "language") > Python language eB Oh ys coe string! | Sips int ababab print("*" * 5) Donte print("1e" * 4) > iwier010 print("10" * "4") > Js 9 110 string & 8 Le A) JSS ca Le string Ul Ge LAS pb tas input SSVI la eas Jena = int("22") £22. integer J Ullal Spas al) Aga) yg any StrINg £3! G+ O98! AS Y CSly Aad float("2.8") =2.8 float a ls\a dail! Jas ~ — str(31) 'BL" string col) Lelitay Ayal! Iya as Ab CMe GS lpalasiul (Sy Input alan Ge pode ge Glu atl ipl pastd of I LLY! yaw - Gay USS ie gaily add ML arly dial an wg pane gle Line y Alen UES SUSY lgaladind Ses entero slau! Sige ULV w Signal) Gal gn WY (small) Fptne Ugh e =F jy LST ras Le J keywords) gun Ua Hage Rae # True, False, None = Ls sine ism Si ati ian Gh Gl a Al Ge 9A oily SUD bel gigs line OU LA Vea AB Vy gals DS Gal ik EB lal Lag OOS Ge 7 Ay lad Saad JS cL Sl aes Gite Aad Gal gin pe yl ala os -B fae daly dal Q) All keyword in python are in ( lowercase & Capitalized * One thing we did was to import the math module with import math import math + This brought in python statements to support math (try it in the python window) + We precede all operations of math with (math.). © math.pi for example, is pi. ©_ math.pow(x,y) raisesx to the y" power. he Ss 9 bya Cian yc SY Ge sal 4 ale gal y AIS 5| module ce 5 he math Ula aia 725 ges Lia Sal (math) 03 pial 9 G81 gl ay ak Mall cls Chall pS LS aaa import math Ge Ge YOST ox OdaSl gy ps Com math powlsy) al 4! gil gl 1 a dala SSN Gay = 1296.0 math.pow(6 4) math.pi = 22/7 = 3.141592653589793 nis math.sqit(36) = 6.0 ones on all fn gle math.sin(30) = -0.9880316240928618 cus sil (uw asad) un ple ela GE Glos AVC SN, Ch Lell yo ES ony Example import. math BB) CAI My HAAS © ae Hay ae as Uw ll be x (cee aad) Qn LY, ¢ Jl all Ge uel $Y! a 2 sae A ally 2, 21 HAS 2s ADE tex x Oe Gal z math. Sqrt JMS. ce gail opis 29.5) GIS & jana y (math pow G+) cunitll 2 print (math. sqrt(math.pow((x-x1),2) + math.pow((2-21),2))) 1,4142135623730951 sick 3 ill ial @ pull J import math x10 Outputs: v3 2=mathpow(xy) math.pow(x=10,y=3)= 10°3 = 1000.0 print("math.pow(x=10,y=3)= 1083 =", 2) Getting input The function: —_input("Give me a value") + prints "Give mea value" on the python screen and waits till the user types something (anything), ending with Enter + Warning, itreturns a string (sequence of characters), no matter what is given, even a number (1'is notthe same as 1, differenttypes) 3) it gf ely lag 3 sal gy Ce qa AB a gS EY ua! Qs a. gt Se input ays ey AS Gas Sy eS a a eg I LES YS ay Ge KE (prompz) LALA Ge iS) Gal a pe Gag} sens gai y]) G8 sy input Ales Dyno y Se KASD U8 D9) oi) JS) GI Gang He psdtuedl Gyn VS gies a enter & ical) & console #85 (iiss LAs «ol psd |i Console 4 4 (prompt) Bgl gla Dans yal ay Lal ebb EN 1S) a 5 gy as (1 coh a "TY ie La US gj tel US i ts st Gane ‘Assignment = +The = sign is the fight statement +The value on the rights essociated with the variable name on the eft * It does not stand for equality! + value = Rvalue Sg) etl je fy) gag Ge Spe ll Ge Als Ge GS il gS wy string A input GSS plaka py Dash cas N19 I (Je payee) Sone ala os -B fae daly dal + X41 2y> thisis error y Jaalt JS fie yey Cyber y chil Us gn pln un age caaly tle any Lk hal Gl be x=22 print('My var has a value of x=",x) + print takes alist of elements in parentheses separated by commas + ifthe element isa string, prints it as is + ifthe element is a variable, prints the value associated with the variable + _ after printing, moves on to a new line of output = ()) Ae, play Sac! py Metall Alam A uae Goa 8) AYGS Oey gue sll Slo agp yal) puoliall delay agi print ella! dey Seba Gob Y 8 SI Jala a tine am Soy) Lal a LS string £9 C+ paliall print he gobs G14 Bo) i ele aap 5 SNAN) BAS) al he Aah Mele ye GS pedal 13) (LLG ya US as string Ig) ose! oY Gs UY sey hoe aan go Jy) pe yall os aS US Ld caste al 8 Us hl J gm allan paul al ge 400) AL Si jes end" " aie 53! print() a ps § 36 ja Example x =12 print(‘My var has a value of x=",x, end= print ("test") Output: My var has a value of x= 12 test ann ps le yay pl! a le Cu test clint + if there are interpreter errors, that is Python am run your code because the code is somehow malformed, you get an error + You can then import the program again until there are no errors SOUS edi fn 5B Vim 9b ay Se 2) OY CGAL NS On tyne lg Cae 2 SAS i LS spy Ja ae SBD Se at St Alls Go (SA ne a sn Se 1 a pal ess Gy RY Uh Gs nef ela i ny Syntax error. -1 iba ll UR ty gy call Ss cay LEN ef Ming print{2) J Gulf cu bls go lial J print(B241 alia ye ual « lay "Ahmad! 3a strings Sig "2 Hall Ble gh ns "Ahmad Sadat ye Nila ye Goa LD Andee yo OILY Wadia Ua Sly" 4 Gell gl Gang "LD string Jt its «all Ll "AR eel lay string UJ)! jouw syntax error wil ges 'Ah'mad’ 4) "Ah"mad" Waal string Ji 2s ge Slate 6 BAYT g 93 GG! Cus error phat Y 'Ah"mad’ 3! "Ah'mad" Lax .string G4 ual set yada el Filely ge HalSl plas) gl Sag! Gb Ange 3 jpn als Iai I while Ga Js While pliSisl ia ij aan ls ol LAS w pble attal type Hag Gitige pd fe OLS J gs LO BLE al (Gas JS hat gl) atv ss “co RBA Je pgp gad a ge age gd ge symtan errors Q) ge #488 Aba ony Abc a Aaah Exceptions error (runtime error) -2 one oe oi (Sil J ale Se SES Le egal So EV Ug eal lS a MGS el! ay Deg JS Sy eal 2 y fm gle Aanll integer sl float 2815 string Linas! go ya Ow Ahan Ae is 3 alk lg tl 2 ty Jon 3 a ny Use WE a! gl oy ie SEY lel oe Finjan CaS Din i ng VS ely ot GB 6 AN yun le 8 yan Jl Sa cruntime Example: Ke2 print(x) ese Gy gel ane print(4 + *2") “ z=X4W print(2) ide 2 gba ay Mg ey Vee J (Gu: 2 Wo runtime error le Mis Lil gl) ag) nay Lay 2D Ag Sy ala os -B fae daly dal Logical errors -3 Mel ak (ake a ont Sal Ty ag Ya ey a Y A i in Sd AN gay 5 cad gam Wy) De a input J) cp ae ae JEG Sy nS all yall he SAI ye Cha Sa 4 a phat Web sa Gina I string yd Cals Uf Ca gf Lubes LS OK, input las ab oe input ("enter a number: ") spe gaia Ways string 42 ID 6 Lge pane Sy EA JA gai a input (enter a number: ") Map ganado 32 Cael phn JAI Ge na ges ie a +58 AY print(s + t) Us hls i la OA logical error 22 aay hag yslbe US) § ols 23 1K 1. Using most IDEs, if you save the file without a .py suffix, it will stop colorizing and formatting the file. 2. Resave with the .py, everything is fine stop colorizing a5 59! cle QM gojuu pol Vay 981 SIG 4) (py) sls yey al yl Lain yg Salt AURSYI Ge PET) a7) Leip! a pha! ally ans! a string J) ak Ye ae Guna Gy gh Ale hall ol code editor J) sits ade =F — FP (se a a ks Sy HE Cao Mba) gl Dom ii E eng dpe ate els, Boae of Fas Aa a es le oi es ES US & oe eae rs stop 420 E20 G1 Maia oe Gl py lhl els) eh Se at cic ANS Mes formatting Lee os (a | oe OOD yoscdt (by) 98 chy Stile asta pa 9 {: Whatis the correct file extension for Python files (Sli Jl) a py pe Answer: a «pt 4. pyth {An expression is a combination of values, variables, and operators * Expressions perform some operation and return avalue + Expressions can act as statements, but statements cannot act as expressions (more on this later). * Expressions typically do not modi values inthe interpreter ty ihe Spey aoe oF i OSS pet As expression J 6+1 wy 34*y-(21+a) a Sh yal gS jad Yan GS gg hg ale yl x=2 print(x +4) YESS Ga Al gpl pl kin Lk Dis 9 Ja te yk Ja 0 (244 eam Sk) 6 gag ad ny An ad JI Gosh dan J Ma ye Inala Ae Ge LT Ly A gt zaseaty shad Sgdan aep US gg aie Gas gm yl lan gyn any a Qe gh ce 6 he Gt Mie dagll ie ny statement a (2= 5+ 4 y) Mais all Li expression yiasssn (5 +4 *y) eSall.Z pital Sa dans (eB cas Legal gla pec) Gane ye SalI Sly statement -S Jaw o! US expression J fp ula gle an psa as de pan Bag yal a Da import math x=float(22) output: y=float(7) 22/7 = 3.000 > herexis an integer variable z = int(x/y) o heres is a float variable print(" z= 22/7 = %.3*" %z) jat(22) =22.0 > herexisa float variable (after conversion) print(z + 17) (int(expression)) integer & »! G+ C33 tie 5 float & 3 G+ y=7.0 9 X=22.0 G2 ial Gat 5 S math module SIs VJ (oD ecg ptahe ph le ge mneger a) allargil a pond entice inthe) sinti2207770)sint(s1azesriazesyies) —3 (Galil ca ay ala os -B fae daly dal eS Y AS gay "AM SSIS CaS ky phe fhe 3+ GN ga tte 20 gp Sadly 2 + 17 SS gus Su Sell Slag 3 z= 22/7 = 3.000 Gs iat aie gles 3.000» € 3 on (os Vint ose ce DSA Unit import math x=float(22) y=float(7) Output: 2=x/y z= 22/7 = 3.143 print(* 2= 22/7 = %.3¢" 2) | 20.1428571428571 print(z + 17) * However, python is sensitive to end of line stuff. To make a line continue, use the \ print("this is a test", \ re ottimvacion output —_thisisa test of continuation AGS JaS.y ate Jou Jif shall SAV GT gH ghee GE Spb Alp GG Cail ike ds alla Cys aaa print(" CS sté"s become ...",\ “excellent Pyhton programmers ~) ‘D output: CS std's become... excellent Pyhton programmers. The use of tabs is also something that Python is sensitive to. We'll see more of that when we get to control, but be aware that the tab character has meaning to Python “Ja gS Doty 85 agit cy) Ua! aad Us G1 Maka sayy alae Uy Sage HAD ee GS SHEL aD J CAL (jt 4 yas (if 2220 San) HY tyes Gl Leal Gg be if wy, co gt Bead JA EN AMR! I FI i gh Gis if Alig Gall MeL dem JS Mal) ay a ine as pheginas jb g e Aed ANN oS a print(y) ge Sh Sa eal IS ap apd 8 le SB Ge SSI a C1 GL 4 GL EA SIS GAN SEA Go if eg Sie ree control J 4as5 a —pyhomeomments + Acomment begins with a # (pound sign) This means that from the # to the end of that line, nothing will be interpreted by Python. + You can write information that will help the reader with the code 2 Wey lees interpreters) WIA Ys Ab sll Je gle B36 Uy ed og gl AAS Sy CI Oe She gay ld SN comments Jc ie $ Sa. ACen le acetal cal ain gl eal al Ga) Gla gee ele ke 9 single line comment ‘3%! i 1S interpreter Salogsy Soe ce 5 le shall ily ase ie eg gl of GS 5A oka AES LE) ASIAN gl ISA Hameed dae oe sdosny she le OS UI Jee ee x = 2 this 1S a Comment bike Wetbagen POT pene Bi Wale oF Z rare SRO I ie Output 2 Bg gl Dal Is gal Le Gk sf 92 comment J Gt a ine ‘cutput Jl les) Jal! sic #f us 5390.94 “print (x) Tultiple line comment Ng 5) tases comment JI Ji 3)" 532) 3 Ge comment JI ae Gite Ge she Ge SI le comments SES maw 9 Lay a atl ALS (9 Ga LEV! Gy blall jes Y SS) Name: Aws Name: Aus 1p: 2017899 F—| multiple tine comment ae tse [rate neconmert | Lecture > oy sarene ala os -B fae daly dal 1! Which of the following is considered a comment in Python? (Gigs: Us) a. /this's your comment b. [i this is comment ‘Answer: ¢ c.myfirst python program g._[thello*/ example from the slides: calculate the circumference of the circle (erm), Hints: using our formula: crmf= 2°PI*r gic URSA CS 4!) Lede mathpi lS math ol yur Vy elias caliph AISI (m2 sill Gans 22) oe fay 3 ane 2 float oll bats input alas yh Se Anil SSI Go Cas ll nad Ua Je as pla QM clint ((22/7) asl ds ill Ge A Say!) crf pill U8 gala dele UL n8l, 2% 7 * math.pig ses crmf lead! Ge ys 8 pte Aa Cat glans Hae Go BSL als pl AUS Sy a ey (2% math. pi gut deb) alee Goa aie Js cre import math ec ‘ : As a 6. 2E ops Sta hl Ge ad r = float(input(‘Enter the radius of the circle r = *)) Ee ee ose crmf = 2 * + math.pi aS ale sas print(*The circumference of the circle is crnf = %.26" %ermf)|__ 2H HU Ube es Ud ss The circumference of the circle is crmf = 3.14 244 ealiyd ely cl DAY Ly i 05 Uae pst IIE Fone ides Sh of SS ee Gill cl ail US Gay Keywords: You cannot use (are prevented from using) them in a variable name. Cie lasted YSIS ay 35 gama! SL I keywords J and del | from while | elas jp CLAS) oa import» print is me al i as elif lobal with - ‘assert else if neld Sj pad SUIS! gle Alia) cain y jlnall Uysal) Teak | except | import True] Si et Gia salad Spall Gad jpn El gl ge as class | exec in False asia! Ja GS Jt La omunu | final in None def for_—_| Tamsin must begin with a letter or underscore _ > Ab_123is OK, but 123_ABCis not ok. + maycontain letters, digits, and underscores > this_is_an_identifier_123 + maybe of any length + Can't use keywords as a variable name + upper and lower case letters are different > Length_Of_Rope isnot length_of_rope + names starting with (underline) have special meaning. Be carefull + the standard way for most things named in python is lower with under, lower case with separate words joined by an underline: > this_is_o_var Valid / legal: ts > my_lst Invalid / illegal: > 22 > square_root function 1) pal faa hg Ys) ol pul gb I Gale jas gl Sl aly MLE SGI ATI I Gye oe pial aul gay oI Guest eas Valid names examples: Vari, length , python , test, WIN7 , S113, x, _ Invalid names examples: call& , D$ , B@T , var 22 , firstvariable , Ad-99 x IS aul ay ol Syms Yo hb je Ds I aL al bs Ge 2 Valid names: 600 , xyz , Var_STR3, areal , 12 abel daly Ane dl Invalid names: 12st, Ovarl , 600_ FS! 5) 200% 31105 3 aly Jae pe es Oh pall pl od ae var sattall aid gal Var satay y sata) Gad yal a Yall CAB IS) gute a pall Ge Cait 44S all 2 Example an=4 print(an) > Errorll! an is not defined. Example What is the final value of variable XZ? Answer: 13, xz = 13 Whatis the output? Answer:XZ = 3 xz = 43 xz = 3 Sha Se Giolthll aas ays sll string Jb £385 Y print("xZ =", xz, "x2 =", XZ) 208 eg a Soh Wy pe JS 5 yell CLIN (J 3a) cline GIA GS, «yall oI GL Vejen GLI og pl a al con ky ass gh NLT ll oy Ha) JS aye oS gh ies jog al a Aad lp gn i atl Ul, Valid names examples: Print , import_ , If, print, importmath , ELSE, For, And , nOt Invalid names: print , import , if , else , for , and , not, None ims aaa eal so) dea ly Atal al Se 6 Bool US Gl pate psdky cbinary system J) WY! dal Cl) sual lle alll Jyay LOS Interpreter UI 3y983) Coo A Ging Fay yl al ST GLA CRE KN pal Gy ina anny GI Sas 6 US Ue iy 9h (ADD aye. ge 389 SS Cy a Maca Le hell 0B) Ges all ony ec underscore (Day lei U pale’ pike Gy yas CLIS «sl lower with under 4: jl Qsilly Cl pital Aaa Sabai -7 4a! inl Sell Ssh Sa ..my list 9 the_sumof_the_grades 3!length_varieble J _ OE Which one is NOTa logal variable name? (Cla Jia) a. All choices are correct >. _my_var Answer: d & my_var d._my-var + Python maintains a list of pairs for every variable: Name |Value — yariable's name —pa_ — variable's value + Avariable is created when a value is assigned the first time. It associates a name and a value + subsequent assignments update the associated value. we say name references value pi Aik atl Lal Sa got pul igs SIAL jy ALI 3 yay A dag yl le) daa yall LI 5, assignment = 0) 5 jut} plasty tidy 4) aan ag ut i Aad Sa 9 OS sail Eh Aaa Aa Ge oly JAS ms gure [a] Bass inter py Mane gad 3 y fSE AD TEA GS, AE ALDI Sine Ah nom 22 wine 3 22 Ghd Mig ca ag Joe lg ab 9 hai Une 2h print(M) #line a [24 24 nel Mah gi 24 = 2" 12 Gh gail ak Sie ine 3 2a eel tine 4 Urey 24 gay M pA Sag glen gh + In many computer languages, = means assignment. my_int =my_int +7 Ihs : left hand side ths = rhs rhs: right hand side What assignment means ist — evaluate the rhs of the = — take the resulting value and associate it with the name on the Ihs + example: my_var=2+3*5 = evaluate expression (263+5): 17 S17 gh 251 oy le pl gts — change the value of my_var to reference 17 P= L2) jus gle ykiad 48(17) pal Ga Ags Lal ge ala os -B fae daly dal + Example (my_int has value 2): my_int= my_int +3 — evaluate expression (my_int + 3):5 DS pte = LE ce le nl gt — change the value of my_int toreferenceS > | a le atl 98 (5) ntl a Kes al 5 caey le apm yall pall ill ti) ans ool a Caney Syaataly assignment sal J) cat iu = 5a) Bh jhe cle apm pl tal ANS + There are limits therefore as to what can go on the Ihs of an assignment statement. + The ihs must indicate a name with which a value can be associated + must follow the naming rules myint = 5 Yes fae tle myint +5=7 No tans th deat ten gle ghee gs ag) ya Vy ean y ll i Reserved operators in Python (expressions) yand) Sia Aiba dale s (== 4< >) Sie tia daleg (fats ay +) Slats Jaleo Mh gS £8) 8 all pa SU) hy ce OSG on la pes (or ymetic operators (As!) Abs I algal) 1 SaaS eau Stee (jemi 2 (Costs gsuleut 3 error exception error gles 0 gle sie Glad GS-4 ala os -B fae daly dal Clie all ya A hl aly Li Gals WSS LS hal 6) B20 9A Clickee cual B COSI 5 27 %-58=-27 (e220) Bo ya a Lg se a ey hl AS pa cls ie ae ALLS 8) ym Dn Al MSO Lage 2 Le ss) LR S88 aS (Divior) B 518) Ss R12) GN Gel ey age a gab sj me tak BAG el gad 9 gag) all gis day fda Jin hala Cy gla lke Lage 7 Tags 2yle esse Glink B10 gsi 2 le 123%2 144% 20 15%2 32%2=0 athe Example: 2°74. =2" =16 ae 2? = =025 False | True Ui ais Relational operators Gjadl Lige 2 (5) Go feel 5) ) esis! 2 (Ss =< cial) aaa ge = 5 ua) at (s+) gah soe Al soc) ole (os) gate co i BLS) (=) ots (==) 41 ) Byte BL) 5 ate 24 ron opm, (ir) ote YE 6 Lee a LY OM, GR Gab Ie ge Le error ol gis Walaa y Gad Gi anal a (and or not) Logical operators “ila! Jalal) 3 ipo yn YS aa! (© 4 |) & >)Ritwise operators 4 ({ } T 1 (_) ) Grouping .5 (Q: Which operator can be used to compare two values? (Izu Ji) a= bo c d. >< ‘Order of operations and parentheses Operator | Description + Precedence of *,/ over +,~is the same Lo Parenthesis (grouping) + Remember, parentheses always takes precedence Prive, Negative Muttipliation, Division, Remainder, Quotient a) real hai Addition, Subtraction LBA AAS GANT Ge Lat) Gah * call 2 aol ba de (oe ol gem Sealy all Sa SY!) tan lly — tga) Jal Ga Ge %y al By ff tment al / al Lad * yell fel Uae Dhlyteal 5 Cat AI seal Ge MS Gln Opies Gap Ha yA As cage) Examples - ers Ppp pa arin Cam siranerara Output: -4 | print((-2)**2) > Output:4 Q: What will be the value of X in the following Python expression? (si Jl) x = 24+9*((3*12)-8)/18 x a. 300 x b. 27.2 x nese Answer: b x 4.308 Python punctuation/delimiters ($ and ? not allowed), —T"[# Ti ost tb BW ad CL. yay TOD TT we) Ma 5S AS strings A ats 9 Ne Lae) Lgalasial Jas V2 9 De I ell print(“test$2") Coste 3 sel comment 9 string CS gi il pil gl iy pau all ia “ PYROMYBET + integers:5 gene + floats:12 alia ae + booleans: True Mate + strings: "anything" or'something’ (Js G+ Made) Gat + lists:y= [ ] ad xe ['2",1,1.3] + others we will see ix Gate ane 3) ga Sone sig) PUL Go IS le Rl SSG Bey string DI audhy chil gl sh ge Ua ay as vsti Cus True USS (uppercase 3S 44K JS yo tym Js!) False 4 True Li! 4 boolean 4 af o) LGV! lls LEY! jas Bigas pt true Ol es pti true dad Gal 1S false Cadi cual False Oly true [os an fig Alaat pst) gy ais A Gl IBIS Be Ge a Ue any 3 pall go EG St gf Sy nY ill) tists Man Sinai sda 61.6 ch gle ‘What is a type + atype in Python essentially defines two things: ~ the internal structure of the type (what is contains) — the kinds of operations you can perform + ‘abc.capitalize() is a method you can call on strings, but not integers + some types have multiple elements (collections), we'llsee those later Leased Ley MLA gy GA VH g pl Sa UE! OF Se GA Stig Le gay SN cael oon Gs gd BA capitalize ileal sie gle Way 51g Sige LelsSial (Ses Vy ta pa GH LS Ghile Chall og 9 UAB ISA ga strings JI ge Walid Go 3) upper case 2S string J! 4+ Ga J! Jans oi strings Ul qs is 88 method Ay string SI Dis jase a fe pone 90s ¢1N Gams string 3 Ey gl Ss Integer aa ps8 o! OSs Vy (MY Galas Tiny desis 2 4! sets sl lists x= hadi" .capitalize() Output: Hadi prant(x) Example: xs Output: prant(str(x) + “heLlo") 10hello print (x//3) 3 x = "yu edu" print (x.capitalize()) Yuedu Heh idee Lass 10 pty Sata Lal gle ol int ae gx iol dag Sy) i G1 Ge da yo Gee Le eae Gell J Sais! string Al Ue paill ais al tells dual Le string ll x jst! dad Lagat les string £55 Ge Med cas Madly + 8 Jt) Ugllas ala os -B fae daly dal error Sis gil gs iy ne dasa dan a gS US gains Syms Y Uns integers string culde cue 3 can daily Saad BS gobs Seth alan SR Saal (string £5 Oe Oates cas By LAY Gal ys + 5 Ut] Uae Ua) 10hello MeL alae gab JE VES gol] Lal BS pl error eal al gna hy ot ESO+ pie x OS sl) 3 Que tan ad 3 le x Aa fel dle 2 "yu edu” 2, int(2") > 2, but int(2.1' fails + float(2)—> 2.0, float(’2.0") > 2.0, + float(2') + 2.0, float(2.0) > 2.0 + str(2) —>'2', str(2.0) > '200, str('a!) > 'a! AY ASI" UI aes ag od eed Saal Ge Hy ey tah Gedy je aoe "1" Oly pee Call Eg CL LS lb J calasl se string 4e.55 je input JAY! dhe gi Js! 6b oF gl ol U Sig float 3 integer 8 448 I ab at egal Spo gh MS GAIMY bit Ga Y ABS All al ae ala yn intlexpression) 1 dapat Sel Sy OSI, integer & 5 ells Lad cl spats os integer} 2s ay sat Jpn 3 Sy Aad US ol Cay LAS expression JJ int("11”)=11 > string value to integer 1 int(3.6) > float to integer int("25a") > error (“a” isn’t anumeric value) | int(“32$”) > error (“$" isn't a numeric value) (9.8 aN) cual ig oy all «Jal GS. ing int SSL AE YN Jpn ca int(36.9)=36 | int(-9.6)=-9 | int(3.24) | int(3.2+25) | int(22/7) = 3 int("75")=75 | int('2)=2 —— Jint(-14") =-14 | int(“#14") = 14 int{*10.5") error J int('14) Derror | int{"0.25") > error | int(“1/4") > error float(expression) (eek sie 5) float i lelils Le ea ot 2 A (0) Aa i 0S float integer + iad J float(4)=4.0 | float(2)=20 | _float(11)= 110 | float(22 + 6) = 29.0 ES LEY! jay Ite a ASS js Le Sy ob Ge 5 he string) sss OSs ol Gas float Gl string 3+ Ll cla Este (Gym J) Role Spey Ge gles id float("2.3")=2.3 | float("-2.3"|=-2.3 | float(“60") =60.0 float(“#14”) > error | float(“14-")- error | float{"14 + 3.2”) > error str(expression) string ol Uses Uli Le US le Sts ine ay 92 an YH ST SSM A string al WSs Le Jets str(1)="1" | str(22.02) = "22.02" | str(3+7) = "10" str(“a60&") = "260%" (string als Wifes a 8) Aa ipa ns Ya lA Oe lle aan Lg str(33-+7)="40" | str("33#7") = "33-47" aly 3 gilen ses Gd ie EAS gD SUD Si ob All aS at JBla dagat I JE eas tS ayn ale 5 str(fioat{int(*22”))) = str(Hloat(22)) = str(22.0) = “22.0” 8 ll Jyai Falsey 1 4ad ll Jpas True J} ci float integer ¢! 4s) 445 4!) Boolean int(False)=0 | —_int(True)=1 | —_float(False) = 0.0 | float(True) = 1.0 AI hte a a Leagl at (SJ! a al) false Cusls False Lewis true Cuals True <2! Sly chaise 6 ala os -B fae daly dal int(false) > error ‘| float{true) > error | int("True”) > error | _float("False”) > error BUS LE 5p) SLUG Jn string G3 Boolean iyi ie 7 str(False) = “False” | str(True) = “True” 9 Bid Che Ga gill Gels False 4! True Wl iad ale GS: 3S Lin danas Aa yh pins LIYE 9) & Boolean D8 False 3! True W! int(7>4) = int{True) = 1 || float(S 1=5.1) = float(True) = 1.0 || float(1>=3)=float(False) = 0.0 aly ABS) 0.0 J 0 Aa Led ia! 1Y Cus bool YI Asi Boolean & 8 GUdas gl Liat! Se alinl Aol 9 True last lls 52 les False phat 42 8 abake l 3i(" 4") & dé string lel Jaa} 19 Lend 5 (string dool0)= False |bool(0.0)=False | boo"0")= True _| bool\"ahmac”)= True | bool{14)= True + Integer ~ addition and subtraction: — multiplication: * ua Lage — division math library <3} 8) ce Aq pal) + quotient:/ float Wes! + integer quotient: // + remainder: % + Floating point — add, subtract, multiply, divide: +,-,*,/ Agcy Jal yl ot oes 3/1=3.0 aie iii see 3y/1=3 30//1=30 30//1.0=30 |341=4 3041-40 3410-40 Vagisil acl aly Hycaly) Jalal gap gle ia Gay Binary operators BE 6 Ny 436 + 3) dh He A UI pliay + aint=4 + blint=2 + aint+bint > yields6 aint—b_int > yields2 + aint* bint Dyields8 hoe pa IE Lael (str_var) AA ae gad oN Me Aa Ge tll EB ILS gle GE age DL integer & 5 ce kia ye 4d ALS Lull ole ol OSs string 40.93 o) dau! stryar=4 Dityperinteger variable value: ar Y print(17/3) # gives 5.666666666657 2s sg 025 % print(2 **4) # gives 16 32**:221/ (2*2)= 142025 7 print(2**-2)# gives 0.25 Two types of division The standard division operator (/) yields a floating point result no matter the type of its operands: + 2/3 > yields 0.6666666656666666 + 40/2 yields 2.0 Integer division (//) yields only the integer part of the divide (its type depends on its operands): + /3 0 + 4.0/2 20 print(17/3) > 5.666666566666667 Modulus Operator The modulus operator (%) give the integer remainder of division: + 5%3 D2 CHAPTER 1: VARIABLES & ARITHMETIC [ERA ala os -B fae daly dal + 10%3 910 TR? _Again, the type of the result depends on the type of the operands. 3 fs ‘Mixed Types 3 What is the difference between 42 and 42.0? zr + their types: the first is an integer, the second is a float Whet happens when you mix types: + done so no information is lost 42*3 9126 42.0* 3 126.0 FIGURE 1.9 Long division example. ‘Order of operations and parentheses 2 print (a7 /-3)# gives 5.seescessee? 2 print(a7 / 3) # gives 5. var (op)= expression coe sins sued hil Leads GD) AY! Jal pny Lt YI Nia Lede alt 3) % lh ia gals ale gl alld Jats J alll uty Cy ah sal as all Kas1 is equivalent to is equivalent to C4s "841 is equivalent to = c+ (2*8+1) K /= (x#9)**2 is equivalent to K=K/ ((x#9)"*2) us (S+w)-(f-1) _isequivalent to U=U* ((5+w) ~(f-1)) Wodules Modules are files that can be imported into your Python program. * use other, well proven code with yours Examples the math module + we import a mocule to use its contents + we use the name of the module as part of the content we imported math module prarssessse3s——————— import math lo-ssrs7ossase7sses print (math. pi) # constant in math module |Help on built-in function pow in module math:| print (math. sin(1.2)) # a function in math rows, ys 2) help(math pow) # help info on pow Return sty (x to the pover of y) soa tlay gl oes) tal y gi YalsSial Lal ie SS Zina dap Gle gi Fale Tals Ge fhe math a modules J math.pi lee si math module Gi pi eles! Cs!) he laa ea Gee aS module J au! sas lly Saye pall dle ny J co las help land ala os -B fae daly dal sin(x, 7) Return the sine of x (messured in radions),| help(math.sin) ‘Developing an Algorithm Algorithm: 4 method — a sequence of steps — that describes how to solve a problem of class of problems Aine Ua Jo 4hS Gaes - Ci ASD (ye Wada 45 0 51,5) in ally Cy Las cl pay ign US Ja eal ana y GS A oa Wa Oe 3 & yl in anes py helt ole gly 62) Soe eine How do we solve the following? > fone inch of rain falls on an acre of land, how many gallons of water have accumulated on that acre? Selah IS he S58 call Ga lla 4 «aN a clad gle seal o saly SSI he ee iy GS I YH SAIS QS 1. Find the volume (in cubic ft) of water (where volume = depth * area) S 2. Convert the volume to gallons — an gh GALS Mel yw Gas Oy gH MI ase pra gl eye ell ga agi) | From internet: Sill jis sce od apts all | 1 acre = 43,560square feet Sell gi Rag Ai aun php ng ll aah Fal pool Gegses tt | inch = 4/22 foot ‘Gps cl ball 5b) ysl y | 1 cubic foot = 748051945 gallons 1, Find volume in cf of water of 1 inch over Lacre = 43,560 square feet How many Linch = 1/12 foot fall when | inch of rain fal > volume = depth * area= (1/12 * 43560cf) on I acre of land? 2. Convert volume in cfto gallons creer > gallons= volume * 7.48051945 About 27, 154 gallons (1/12 * 43560) * 7.48051945 (1,02,800 liters) of water. = 27154,2856035 asl 4a Cl gas bs Oy # Calculate rainfall in gallons for some number of inches on I acre. inches str = input ("How many inches of rain have fallen: ") inches int = int (inches str) volune = (inches int/12) *43560 gallon ~ volume * 7.48051945 print (inches int," in. rain on 1 acre is", gallons, "gallons") inches_str = input ("How many inches of rain have fallen inches_int = int(inches_str) volume = (inches_int /12) * 43560 gallons = volume * 7.48¢51945 print( ) print("Fallen a (", inches int , " ) inches of rain on 1",\ “acre is = %.2f " %gallons , " gallons of water") The Rules 1. Ruled 3 Think before you program Rule 2 > A program is a human-readable essay on problem solving that also happens to execute ona computer. 3. Rule 3 -> The best way to improve your programming and problem solving skills is to practice. 4. Ruled > Test your code, often and thoroughly! Relay acl aly Gg YS Gl Len US ole Jal coy LL UE Ulla Uy 66 Y4) 25 ll Ja pes CA Sys e Lely Sa ly Kasha ga Lael igs yl dle as) WY cl Tay aT 1s Python case sensitive when dealing with identifiers? a) yes b) it depends on the name, sometimes yes and sometimes no ala os -B fae daly dal ¢)_no 2. Which of the following Is invalid name fora variable? ay >) HbAic Answer:¢ <) CAI9-9 a) Dexa 2)_all of the choicesare valid Bia Way underscore ce tbe she Jy! 3. The output of the following code is? vari = '3" vard = "5; print(vari + var2) a) 8 b) 53 ) Error (you can't use "+" with strings) a) 35 2)_none of the above Answer: d 4, The output of the following code i? a) 3 b) 6 4 4) 30 2) error print(int("3.6")) Answer: e 5. Whatis the output of the following code? x=13 y=x*2 fzt=xty result - 2-5 print("2", ys "x") a) 382613 b) 226% c) zyx a) error 2) none of the above Answer: d 6. Which one of the following has the same precedence level? a) Negative and Addition b) Reminder and Division c) Parentheses and Exponentiation 4). Addition and Multiplication Answer: b 7. What willbe the value of x in the following Python expression? x=1+642-((3* 2) % 81 // 8) / 10 a) 13.0 b) 134 ©) 12.95 d)_none of the above Answer: a 8. What is the output of the following code? print(x/y, end =" “) print (x//y) a) 220 b) 22 ala os -B fae daly dal ) 202 d) 2.0 2.0 2)_none of the above Answer: In Python, a variable may be assigned a value of one type, and a) True b)_ False then later assigned a value ofa different type: Answer:a 10. What is the output of the following expression, 3°1°*3 a) 9 ) error ) 27 a) 3 Answer: d 11. What is the output of the following code? 1s = “What is your 2 name? What is your age?” Syntax Error 3 _print(s) 12. Whatis the output of the following code? 15 = "What is your 2 name? What is your age?” What is your name? What is your age? Wsnotanerror! multiple ines string , 3 print(s) 13. Suppose that the value entered in the input statement x = input(“enter a nunber zaK+tx4x4Kx print(int(2) // 10) a) 33 beror ga d) 333 e) 3. what will be the output of the following code? Answer:d 0 14. Which of the following variable names is valid? a) myint = "pre" b) var = 11 c) import = 2.3 4) student nunber = e) "str_var" = “ABC” 52 Answer:a 15. What will be the output of the following Python code? a) Error rz >) -16 2 c) -144 3 4) -54 la 2) -6 5 6 a print(s) Answer: 16. Which line does contain an error in the following code? a) line 1 int_var = 33.5 b) ine2 fost var < 4 strvar = str(int_var + fi o lines float_var = float(str_var) a) linea strvar t= “int(2.3)" 2) lines print(Float_var // int_var, oat_var) Answer: ste, f) line 6 line 7 This code doesn't contain an error . What is the final value of x? ‘import math x 22//7%4 math. sqrt (4*1**2*4) - (math. pow(int(math.pi), 2)) Answer: 2.0 ala os -B fae daly dal 18. What is the output of the following code a) 6**6.0"*6.0"*6**6 fl print(2*3, end: ) S0*6.0"60"60"%.0 > print(12/2, ende"**") Answer 3 ereorerers gf print(24//4, end-"**") 3) geterronone fe print (442, end="**") b_print(6%10) )_None of the above 19. Tn Python, itis okay to use keywords (such as print, det... etc..) as aname for a variable, if you didn't use these words before the variable assignment statement. a) True b) False Answer: b 20. What is the output of the following code? a) 242344 fh markl b) 47 j2 mark2 = 23 o) 92 b marks = 44 qaawene d) 88 4 total += markl+mark2+mark: ~ 2) None of the above 5__print(total 21. What will be the output of the following code 2) 50 TA 45 b) Error 2 _n = 83 ) 83-38 3 proj “#165” a) 45 4 ®) 83 pene) Answer: d ) 8 7 print(_n, end= 8 print(A-_n) no success =_n +5 Q1) Which the following is not a correct assignme’ a) mylnt +=5 Answer: b)mylnt= 5+7 c) mylnt +5 =7 a)_mylnt=5 02) What is the output of the following code: 1 x = float(21) 2 yl fotey Answera 3 Wt= int(x/y) +34 6+245%4 4 print(w + 17) a) error ) 40 20 04a 03) Which of the following is correct? a) x= float('2.1') b) x= int(’5#2") “Answerza o) x= float('5+2) d)_x=int('2.1') 4) Which Tine does contain an errorin the following code? 1 x=6 2 = “Sani‘a" S eox pase Answer: b 4 print(_x) 5 print(n) a) line #5 b)line#3 _c)line#2___d)iine#a__—_e) ine #1 CHAPTER 1: VARIABLES & ARITHMETIC ala os -B fae daly dal 5) What is the output after executing the following code: a ox-7 2 yox43 5 ee Answer: b 4 result - (y %2* a//2 + 4¥2)/2 5 print (result) a) 100 t) 8.0 120 c)none ofthem ___d) error 6) What isthe output alter executing the following code: w= 33 AD BD ie dS -4 = 93 IAN stat Sf Od 3td_name - ‘Soni'a’ Aap string ots ine eB Samia” ls error Ice tprint std_nane) "cape AIS py Sodom UH eee Ge print (w) Se sting 2 8 joy a UE RELL im mark = 4 +2 30S cal error get WDE! 09: Gant 18) LES a) 33 aN ple Al 4h sy “Samia” SS string J 8) error ) Samia 4) 93 Answer: b 2) 95 a7) Which of the following variable namesis invalid? 2) {sum_=35 5) 8total ¢) All of them are correct Answer:b a) wi a). 8) Which of the following is invalid? Dm (undencon) ER pie ARO a) _st_=1 DT pals jay cial Di bs WS, ls o) _a=a L__*++s»=ereess os Answer:d a) _none of the mentioned Q9) Which one of the following has the same precedence level? a) Addition and Subtraction b) Addition and Muttiplication ———— c) Multiplication, Division and Addition Answer:a 4) Multiplication, Division, Addition and Subtraction —_ 16) What is the value ofthe following expression? _ print(22//3+3/3) a) 2.33 8) 83 ) 8 Answer: d 4) 80 a 13) What will be the value of Xin the folowing Python expression? x =249*((3412)-8)/18 Anawonb a) 28.2 ) 272 308 4) 30.0 12) What is the output of the following code? print (((((45#5)*2)-8)/2)-13) Tawar 2) 50 b)30 os a3 nswer: 13) What is the final output after executing the following code: import math wee sou 45 t= 5 + int(math.pi) % 3 + we*2 Answer: € print(t) 2) 66 _b)72__c)noneofthem _djerror__—_—e) 77 CHAPTER 1: VARIABLES & ARITHMETIC ala os -B fae daly dal 14) What is the final output after executing the following code: import nath Answer: ¢ Z = math.sqrt(25) + y // x + 2**3 print(2) a) 12.0 b) error ¢) 14.0 d)11.0 e) none of them Q15) What is the final output after executing the following code: ve tmark ays br se forse bs Answer'b print (total) a)_error b) 5045 c) 4550 EE e) none of them 16) Whats the fina outputafter executing he Tollowing cous import. noth aera bier aey3 z= nath.pi+7*b- at*2 % 18 /4 Answer: print ane()) a) noneof them 6) 50 eyaa 4a, o-aa Q17) The expression int(x) implies that the variable x is converted to an integer. a) True qoawen b) False nda 6) Whats he output ofthe folowing code? [xe TO a) syntax error 2 b) 1010 6) 109 Answer: a 3) 910 - 9 _print(xy) “Tad What a he output ofthe Folowing wade? se2eas bes pat 3.9 cua fas b sae? [ Answer:d | Brine int()) a) 6 b) error, os gs 226) Which of the following is considered a comment in python? a) /*Mid Exam*/ b)# Mid Exam Answer: b ©) /# Mid Exam. a)_| Mid Exam 021) What is the order of operations for the following expression: y= 3*3/(4//3+8)%6. al +* I % db) et 1% 2) % +t SH a) Syntax error yt sir % pees Answer: b ala os -B fae daly dal 022) One syntax error in the following code, determine the line number: a) 3 tis fost 7-65 2757 45 3) 8 rine = 5.34" andy j7 ki Gr = 8) 41a) +5) ‘Answer: a) 2 prant(ni = = 2*" ra) 2) 4 prant(e.capttaiize()) 6 Jb bevizs a: print int(6)) 23) What is the output of the following code? f -* coding: utf-8 -*- Created on Tue Jul 13 23:53:02 2021 @author: Teacher import math Answer:a n=10 hes area=w*h print (area) a) No outputs _ b) SyntaxError )10°5 4)50 e) area #105 24) In python language, you can continue typing the same statement or expression on multiple lines using the following symbo\s) a) \\_b) ae oe @)/ ei ay Answer: f 25) Select the correct variable name(s) using python|anguage: a) _Student_name >) hello_var$ ©) nama_order_123 a) 1_name_order 2) abc2000" f)_key order@® 26) An example of Boolean values is: a) true _b) false c) "True" d) "False" e) True #) (2,3,4,'a"] Answer: € 27) Which of the following statement(s) is/are true in regard to python programming language: a) All choices are correct 5) Python is an example of interpreters languages aren ©) Python is an example of compiling languages eS! a) All choices are false 2) Python interpreter check for all types of errors before running the program 4)_Inpython, you can run statements one at a time 028) What is the output of the following fragment: 1 print("Is 100 odd? 2_print("Is -1 odd? Answer: a +c Ly A o« 381 SY ag Sl) I es '» 100%2, end: »-1%2) a) 1s 100 odd? True Is -1 odd? True b) ls 100 odd? 0 Is -1 odd? 1 ¢) 1s 100 odd? False is -1 odd? True a) _Alloptions are correct 025) What is the output of the following code: ff x=10 Answer: b 7 22" prine(serooestr(y), int(z)) b B ls ala os -B fae daly dal a) 1722 b) 17 22 Answer: ¢ c) 107 22 4) 10722 e) 107 22 (030) What is the type of the variable (m) after executing the following code: a) float 1 b) boolean ) integer a) string Answer: a GEN 2) list a print(m) (031) What is the output: as 2=10/2%3*8//5+2 0) 2 <) None print(z) Answer: a d) 27 Suls5.0 2 cull a 2) 12 aga Wale gs ALY! 032) Python scripts files have names that end with a)_py &) docx ).-pyh d).python__e) exe Answer: a 033) Which of these words are reserved words in python? a) elseif ) elif <) else Answ +d a) while 034) What is the value of x after the following statement executes: int (98.6) Answer: b a) 6 _»)98 100 )99 035) What is the value of x after the following Statementexecutes. [Il x = I-2"*3/5"2 a) 6 2 print(x) b) 4 ) 42 Answer: ¢ a) Error 036) What is the output of the following code: = 20.5 ; a) rint(type (Float (int(x)))} Answer: b b) float) Saansny 2 cine ph La Jang int) Mg J 8 Sata a) _ go. float 9 type oi Js cad € 5 as) int ay in type 3 ign abe ce float cg 037) What is the final output? 15 a) 2 45 b) 2 (+ a6 Answer: b ¢) error in code t= 5 a) 2 print(-2 + 2) 038) Which of the following statement is valid for output? 3) print("Good iuck) b) PRINT("Good luck") Answer: ¢ ¢)_print("Good luck") 039) What is the output of the following code? yy = 5 ** 2 a) Error: invalid syntax 2=5 ** 3 Answer: b b) 25 125 jprint(v1) rint(v2) ala os -B fae daly dal 40) What is the output ifthe user enter value 4 a) Error 0) 18 9 10 ik = input Ik = X+2*3 lrint(x) “enter x") #4 Answer: a ai) What is the output? a) 16 18 b) 18 18 ) 18 16 //y+2*7 lprint(z+2) rint(z) 042) What is the output? a) 100 b) 1010 101 a) 100.0 import math 8 ly print (math. pow(x,y)+1) 43) What is the output of the following code? a) 15 >) 10 gu d)_None of the answers 244) What is the output of the following code? a) 910 b)_ Syntax error 9 109 4) 1010 Answer: ¢ AB) Lage math library <1 St cy cp float Yes Answer: b print(2@ - 3 ** 2+ 8 // 3 ** 2)| 45) Find the line that has error: a) Line #3 b) une #2 9 line# a a) Line ws 2)_Noerror =6 x3 54x (1 + x)%y Is print(z) ) x= int(input (“enter value for x") ¢) x= int(enter value for x") 4)_x= input(int("enter value for x")) Jprint (x,y). Answer: ¢ Answer: b Answer a Q47) Wratisthe output? Tx=int( 12") a) Error 4 I= X+5 co) 512 lprint(x) a) 125 48) What is the output? lvard = 1 a) 6 lvar2 = 2 b) 33 lvar3 = "3" ©) Syntax error z= vard+ var2+ var3 4) 123 print(var1 + var2 + var3) The End of Chapter 1 Answer: b Answer: ¢ ett Selection + Selection is how programs make choices, and itis the process of making choices that provides alot of the power of computing pe) Gas Ge oy AN HIS Sat et esol ay ash J LEY Less than ; Aina by 33 Greater than Ete 3A, (relational/ Boolean operators) J) Iie ge 1A Stubs <= | Less than or equal to (boolean) False 3! True Ul Lule ili) ei Gl jh os Ou Ea I laa aay Y gt Leg Ail 9 Qa hall yay ae Cal ‘greater than or equal to mare SAN = HUN ay Ae | ec I on ie Sa a pla ae Ugaskns False 9 True Wl Boolean £ 5 Gs 408 a> fis Laps OG cued Co gL GI Lt} string 26 281 £98 G+ 284, string aaa! cui Ge EAD one Y Sal g 3 Oe ca oe Hl ON GST 3 fall askin § of cM ll Jaya Cony HD GAD GLa 5 pS A ticks Uns lh gga i pally AEGRAPGIRGSE Sw suing ee oN oT ahem omrcke eee « float »| integer <= ex Boolean! fe Se yintegers ex float © fie Sas 2G Lil Syall= gle ASS A Salas ied Lu Boolean 25 U Jk. and FBIBENO » FEMA IS yo 4a 25 False y True USO SS Sgsall pews False IIs True print(true > 4) Disequal to> | print(t>4)_| Output: False rint(False <= True) > |s equal to > | print(0 <= 1) | Output: True Output: False ERRORI! Output: True TaD sel as False 3 True ao! gl Boolean i! bests a = bool None 3" 3)" 3 [] BE Mobject is! t string 410.0 3) 0 laly Gif 15! False Lal! bool Uo. True 4a bool Upsuiligssle 0 True ei empty string/object 3! 0.0 3! 0 val ual av! dats Lag! Lith True letad ois bool("False") Sa S2 Y a! sys Way L boolean 24a! Aaall False sli bool(False) Lub S15 bool(7)=True | booll"0")=True | bool(0)=False | bool("")= False and, or, not 4s (logical operators) Mail Jal al Lal Siw (ab Gb) False J True J Jaais True. 3 False said Jy cnot 0 False pias alld J 92 Ley True Lagat Ce gall DS GIS 13 True ee gaa cand 0 False Gat shill 3S cS 131 bid False ie ety ‘True eke ot SSITrue Gaye) sal 255 ol AS coro False False False False True False True False True True True! False False True False True True True True False GI ay 410 Ge aL aay Ue ad YI JL CL agg A al ca [ee taponenttion ] A snot SaaS MIL SV. sal or Jalal! |Suil 5 cand Jalal ‘Multiplication, Division, Remainder CHAPTER 2: CONTROL 1 Ala) gash atbe3 b and arb >=7 3 Trucor False True not 2+3>4 and 264 >= 7 a4 notS> 4and >=7 Output: print(a *b+3 b and a+b False and False > False print(b / a == a and 16 / a != b) Pse Trueand True True A) Sid) AY) a True mes False US 1315 False mines True ind Cols 1348 gilial) puntll Sea sinot + Sul! SU tag ABLE Dag lal ly gigas JSS. 9 pa Gg gas yal Ly Als gla il) not(a>0) is equivalent to: Bias yo ely GSA ag ae ha 1 LN ey sll Le not DS oh 4 Ld Leg Aa a Lgl ab Cu al Operator [Not operator Wade DAs ual SM ag GL cal pital > « SS) pais le ALN Gs gi Le glee GA not! not iL} < >= seta ie gle Jan Sah cise J ectle yle gas peat gle not La! & < Examples: not(2 > 5) > acd T= not(a arb not(x > y and 5 I= 6 or not(True)) > x <= y or 5 == 6 and True and not(not(a > b and 4 < 7)) > a>bandac7 or ‘and Not it: Not not Python if statement TF boolean expression: suite statenents + evaluate the boolean (True or False) + ifTrue, execute all statements in the suite Simple if Sis igual disuall og ih ae Ug) cya Le ints 1 SY Jal oe Jan de yume lily aud if tll dle ‘ag gb if Legh af NAD hal 5 Sie all Jat Lab oaks ply UR So A iy ya Uh if 5 Aaa Las Sagi) OMT (Sand JS C15 15 cgi gly Hage GN ll 68) GLEN A 4 oe GsSe (tab space) Mal! 3! ELA ULE gS ese Ls dat Saal if am ise JANN aah bj Sil ll acs le WB al SY) oa le Sa Y Ga Cs Sead gle Say FD dad) ye Jeg) fA gl ae ap gh AEG oly gall Utne False day 1! False 4! True dal ol yu Sting if Alan eyo lade si True cits 8 Lad gl False 3) True M2 ae po ogy Bag) A a gif gl gl pl AS Dl 4 pie string gloss a 0S 5 4! False y True ei Ghee OS Ike ya WS i False Aan GE Gl ph jl uab J ASS Y False 3\ True + iS J yi gle a Lay if 14a Leal ag! gt Uy cerror ll gaise Bing Cis yy pmb pall aes Gl Ih ha BAUS Yk pL Jon SCG 6 ot aids al} WLS OSs Ons if anata ya My Del if Regd as cg a 03k 6 pled ghd Lal) soy Y Da cig Sh (Aye ee la gH) Lad Jal Li ony (Mp Gin a oh ges Sg a Ny AS ya yb AL) Cages Sl al lt y as gil if I) Les ol Gl DEA 8) Gat pal sin x = Float (input ("your mark: ")) if x >= 48: xa22 print ("Passed!") print ("Thanks") oe ey bed if Lp Ale OM = 65 oI gl 65 bed Shs patti oh Geel xl Med stl po asthe J GL J OS GSA VIAN) JEN TS Gd cathe (a (suite) Sul Jog SA ee VL True lo 165 >= 48 el 9 4B CHAPTER 2: CONTROL 2 ‘Aula jag! = 5 fide tal ae dan oh GV if len yi eal ops Passed! gibi elu dan ob x= 67 Gunad 2 sha x Aah ie tt an J flan Thanks Pessed! SAS cla pl p09 Al ag Ge Thanks coe a fale Goh A DY La Sas aol Sats ol IL False IY $41 >= 48 Os 2 5681.41 JY dee i Us) Staal ol a al Dd Ua gah ASL Mle a if el ay lag) (ALY gl Ge a an Gi) if ag lg any HT J Jagd GM aU Siy “Thanks Jit (sSie ce poal) 6! gl Thanks N aap Ag Al QU edd als Lake Li 67 Ga Sat ane Jk A Cd 6S GS Le Sa on GL JEL Gi 2 aly Example: What is the output of the following code? What isthe final value of x? x= y=8 ifxoy: x22 print (x) Ray Sle phe gl Dy cal yD sei if lam any am any Y 4th Ley Sat) Jaa itt Gl False IY £4>8 Ue de pl 4s! x= 4, y = 8 At Bample: ct a2 if x%2 I-20: Ol! Output: print (“ok”) False Yes print ("YES") alg dale Jani SY False = bal GU GSU ball dap (alo ag SG True = bp GUS A Gu ae sa if False == False: print (True) Output: True dag go ynfD all Si in eS GE True pe ll i lbs @ gad gee gas Lae False sad False Ua pa True gis tol SEs False 3 True BSS ts 1 gy SSVI 6 Aly a gl A) ony Lie J Ue che Bl oS 9 iY 2810 ie pal ia frase: GAS IFO: UI € False gs bool() J ito Joo as if True: yas if "0" & iF 42**0: if “Fas: if 3//7: an) print( print ("A") print ("a") print("2") print("B") print ("2") if /else statement Lf boolean expression whe ST CHAPTER 2: CONTROL 3 shes Os il ol (suite) 1,41 Hat) Saal) S82 True GS Ilda I) a8 6 if as og all SUH Lead eal! Say Js aS Vy (suited) Mabel) 43 Daal ge pbs False Se pill cis 15) (Si Y suite? LI gl) Alaad Sb 4b alll Dee 1 if /else statement das gs eda! (statements) Jacl! if Alas 46 ua else : Cans inl) (suite2) la dans Sty . : je af [Fatse|: ‘Action 1 | Action 1 will ‘Action 1 | Action2 will else be executed else : be executed ‘Action 2 ‘Action 2 Bample kei if (2 = 50} Leb xt esl ap aleny print ("Great job!") $139 oa OS aint oll SGI DAG « af total < se: print ("fail") print ("Try harder") Warning about indentation + Elements of the suite must all be indented the same number of spaces/tabs + Python only recognizes suites when they are indented the same distance (standard is 4 spaces) * You must be careful to get the indentation right to get suites right. Lush cl adh CAEL Gia y MBL) yn pasll qua gDs Ciel § 4) al) di GL AA eal 65 cl ns Gu LS Kat at Ugly sill ail gle Anil asl cane So gte! Oy SHEA OS O: Whats the output of the following code? (Sls Jims) grade = 67 if grade >= 50: print('Pass') else: print('Fail') IndentationError Fail ‘no outputs Pass ‘Answer: a What is True, and what is False True: any nonzero number or nonempty object. 1, 100, "hello", [2,6] + False: a zero number or empty object. 0,"",[] CHAPTER2: CONTROL 4

You might also like