[go: up one dir, main page]

0% found this document useful (0 votes)
63 views18 pages

INF1511 Exam Pack 2022 Visual Programming (Chapter 2)

Uploaded by

Wizzard
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)
63 views18 pages

INF1511 Exam Pack 2022 Visual Programming (Chapter 2)

Uploaded by

Wizzard
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/ 18
ARITHMETIC OPERATORS [ovenanion ~~ Tosscmnion may ‘acon == Subtraction zy Mutiptication x7 Division RIT “euneating dso xy ‘Exponenbotion (27) zee Module operstor = ‘Unary minus ay ‘nary plus ‘Mulnpicovon and dvson operators havehigher precedence then action an subtraction \EGOULSIGEERATR | )- returns tne remainde of te ation operason ‘TRUNCATING DIVISION QERATOR (//) Known as} ‘+ Trumcates the result to an INTEGER (ignoring the remainder) 1+ Works with both integers and leatng-point numbers ‘TRUE DMISION OPERATOR (/) Also Rms the result HIRRTRRBERF operands are integers “+ Retuins floating-point result ether operands ate loatng-point aumbers PRoGram USE TRUE DIVISION B AREA OF TR bela Print ("ihe aca of teasngle see") Pint ("Base=td,neight is tdy azea of triangle is S£¥(byhya)) #a: dee Sf-float fe area of traingle is: 110.5 angie is 119,500000 £-1.0/3.0° (ptate) Print (tiversge of three v Prine ("average of three ¥. Print ("average of three v ‘Avezage of three variables 4: Riesage of Shree Ueeithies $2 While using the FSERASTSRTEBERAE ‘Ensure that either operand is 2 floating-point number (© Avoids getting an incorrect truncating integer + BEGIN the source fle with this statement - SEH SfUEE= REE SIVISIOR 1 Ensuces that the true division operator works without truncating operands '© AND that script uses the NEW-STVLE E1.QATING-POINT DIVISION OPERATOR fron _furure_ import division chro variapies 48°, a) ‘average of three vartaples ie 10.0 To2pply: © Double asterisks (HH = *-> EWU function — pow ta Exception if: ‘© alslessthan zero AND + bisa floating-point value witha non-zero fractional part PROGRAM ‘CALCULATE THE VOLUME OF & SPHERE division Prine ("he voile of sphere ts $.26" y) phere to 113.14 To get the value ofp without computing i (22/7) ‘Statement Heon aath import pi PROGRAM THE VOLUME OF & SPHERE USING THE MATH MODULE from math dnport pL tn4/32psepou(e, 3) " Wolune of sphere ie 113.10 Statenent from the math inport pi eo Imports the value of pi fron the math module ¢ To be used directly in arithnetic expressions Assign multiple variables at onetime RULE: ‘Left and right hand side must have the seme number of elements 1+ Values assigned on a one-to-one base examples: Sin, avg = pejer, (pegee) /3 Escape sequences ‘special characters that represent nonprinting characters Begin with a BAcKSLasH Bell (Seep) Backspace Form feed New ine Carriage return Tab. Vertieal ab ‘uteral backlog Single uote Double quote ‘+ ng DOUBLE-QUOTED string Escape characters INTERPRETED + ina SINGLEQUOTED string Escape characteris PRESERVED Program ‘+ DEMONSTRATES ESCAPE SEQUENCES print (‘e120 wo Print ("Hello wo prine (‘Festival discou rine (‘rsa\te ie") prin ("rents se") print ("He said:\"I am going\=*) Print (*\\text enclosed in Back eashes\\*) Print (‘Bell souna\a") Deine (Name\eomas1\eCe Helle World! rete het today Belle wozla! it's hot today Festival Géferunt fe said:"t am going” \text enclosed in back slashes\ Bell sound. (Wakes a bell sound) Name “Enail Contact Address ai\are\te not voday') I\are's hot cosay") \e\p\e\e\B\D\D\e\osEar") .ct\zAaaress") [BUSI function - Returns the data typeof the object ‘Suatax: type Ce) Accepts al types of parameters integers Strings ste Dictionaries “tuples Functions lasses Modules cotHello" 12,541 e-("apsie", ‘mango", "bsnana") print |eyee (a)! Brine |syee(D)) Brine |sype(e)) petne |sype(a)) eine (syne (2)) Sloat Misery seuple"> (GEPALVAUUE -atue preceded by 88.08 BER unction OR format code ERAIVAIUE- vac preceded by 6 OR BRI unction OR format code proGram ** CONVERSION OF DECIMAL VALUE TO OCTAL/HEXA - FORMAT CODES Ned and in nex a" ¥(ey2)) PROGRAM '+ CONVERSION OF DECIMAL VALUE TO: exA FUNCTIONS peine ("18 in octal is INPUT METHOD - To get input from the user + Prompts user to enter data ‘Reads one ine from standard input + Returnsit asa string ‘Which can then be assigned toa variable an vers erurad is pad iba vas nag format f ies tobe CONVERTED When you do some arithmete operations on "Sect th as eo I ‘Operands of DIFFERENT DATA TYPES - takes place Python converts the operand with the “smaller” type tothe "larger" type {ERE function To convert numerical or string into an INTEGER datatype Data tobe converted is passed as an argument o the int () function Beet taienece!D) ‘+ x object Converted into an integer + base ~ Refers tothe base conversion, any value between 21026 ‘default value ts 10, ‘© COMPUTES THE AREA OF A RECTANGLE - LENGTH AND BREADTH SUPPLIED BY THE USER put (Enter Tength: *) beinpus ("Enver Breadth: *) asine (2) Hane (5) Print ("Ares of tesangie 4 Area of ersangie is 50 print (thres of circle is*,a) rint (*hres of circle is 4.26" tay © Numericals are internally represented in the form of BiNARYDIGHS . perate on these binary digits NOTE : hit and bitwise operators can only be applied to INTEGERS anc LONG INTEGERS 1X8. (Bitwise AND) cerapenng sof any arecompared RRB ne coreaponcing bot III (ont when both its ar 2,2 turns 2 Ereowretune 3 Print ("The result tise ao between 10 and 7 is*c) 2. XLV (bitwise ORD Corresponding bits of x and y are compared RETURNS O'f the corresponding bit of x AND yO (Returns 3, either x ory is 2) © OTHERWISE returns 1 + ether OR Vis. overator RETURNS a-t0 7 enalb Deine ("The result of bitw ‘The reoult of bitwise OR between 10 and 7 Se: 3 LALLY (wise eclsive 09 + Corresgonding bts of x and y are compared RETURNS ETHER or yi d (When its are diferent) + omnerwnseRUREMY tne coresvonding bs of Je OR between 10 and 7 is: ea Deine ("zhe resuit of Bithise exciuesve OR Between 10 and 7 422", <) SS eure tht ns Hn EET + Digits padded with 0's onthe right side + SAME ns ini IBy 22 e10 and ya2 (Xx 2"*y > 10% 2"*2) brace peint(*efe shifting - Multiplying 10 by 2*+y(2) beconee:",b) Left shifting - Multiplying 10 by 2+*y(2) becomes: 40 ‘S.X22 ¥ (Binary shift right) * Return with the bre ERG to tne RICHTER + SAMEAS| Het and Yet Ot > 10/27) bras ng ~ Dividing 10 by 2*+y(1) becomes:",b) ~ Dividing 10 by 2*+y(1) becomes: 5 (COMPLEX NUMBER ‘© Combination ofa component + Both represented by ‘© IMAGINARY COMPONENT. © Multiple ofthe square route of minus one Xx V=H © Denoted by} same :3 #12) a3 =o component +12 Imaginary component ecual to HR REAL and IMAGINARY components con be RCCESSEDIISE ‘© GD and Sag attributes neal /nimag PROGRAM "+ CALCULATES THE ADDITION OF TWO COMPLEX NUN 2-3.082.25 ‘two complex numbers aze",a, "ana", >) ("The addition of the two complex susbers azo”, 2) me ("The addtion of tuo imag a y numbers are ‘The txo complex numbers are (341.23) and (-2-9)) The addition of the txo complex nunbe: The addition of two real nunbers are: ‘The addeion of two imaginary numbers are NOTE : Complex nusters are Helps n making declsons and contain aw ofthe program Decices which BLOCK OF STATEMENTS o execute onthe Basis ofthe LOGICAL EXPRESSION Block of statements atfached with fas wellas with ats ‘After evaluation of he LOGICAL EXPRESSION BR te fi othe HEB lock tatrnent URS played esclosed in parentheses( ) syntax 1 (dogieai expression) Statenent (2) +f the logical expression evaluates to fo TRUE ii statement is executed acint (input ("Enter grades: ")) SF (n>=60) print ("First division") else print ("Second division") coreor: Enter grades: 75 Second division users enter grades through Snpue() macho + Using Lf.. e180 etatenent, you eneck ene value in variable = + Ifa te groater than of egusl co 60 ~> if block will be executed + Ifa Ge less than 60 “> else Block Will be executed (Second aly) sest atv) ox Less than. = ‘Greater than oe Less than or equal to (Greater then of equal to Equal to Not equal to SEG cos mLoce wma sie stock sine (input ("Enter grades: ")) print ("First division") else print ("Second division") elset print ("third division") ooreor: Enter grades: 75 First division Enter grades: 46 Second divieion Enter grades: 0 + When you have MULTIPLE LOGICAL EXPRESSIONS to evaluate "Nested igs andlWiETtatoments MERGED to form an BME statement + Statement avoids excessive indentation if Qogical expression) statement (3) elit (egical eupreseion) tenant (2) eLig|logical expression 2) statement (2) statement (=) f= elf ese STATEMENT meine [input ("Enter gzadas")) print ("First division") elif mo=a5: print ("Second division") else! print(*third division") Enter grades: 45 Second division Enter grades: 40 + Combine two oF more logical expressions + LOGICAL EXPRESSIONS ate COMRINED wth the TIEAUORERATORS, . aa ‘connected with the AND logical operator returns TRUE if All the logical BRBPBSEIOA) Rew GR AA ofthe ogi! ESPERISRS STANTS RO RAIS Logical expression preceded bythe NOT la operators negated © togial expression tat evaltes to MMIII wren preceded bythe logical NOT operator PROGRAM ‘+ USE OF LOGICAL OPERATOR AND wmeint [input ("Enter grades: *)) Sf 0-80: pring ("Ziret fe abaas BR n blsplay x and ineresent value by one 6 ‘+ Stops execution ofthe current iteration by skipping the rest of the loop and continuing to execute the loop sath the est erative vale mmocnam > PRINTS VALUES 170 19, X¢EPT FOR? kt eeencie ied S while Loop is ser co execute till k cesches value 10 * Kis displayed and value is increnented by 2 2 Le Seatenent checks value of k- when J, value de only snerenented by 1 and not priced + Loop ontinuas and printe ene incvenontes value, namely = ‘+ Indicates an EMPTY BLOCK of statements ‘* Acts asa placeholder for code that you want to write later © PR RD HHL ooie note of the indentation, Kini ie 2 ststenent on ite ovn ‘value 1 is initialized to vaciable k while Loop is set co execure till k reaches value 10 + Toop checks if vaiue of k-=7 + LF kA7' is 7 pase otatenent Le executed, value ie not printed © ke then increnentes by 2 © {eu Leiner Tpelge / print scatenent ie executed 16 "THE RANGE FUNCTION © ange) ‘+ Generates and returns a sequence of integers “© Commonly used in looping statements ange [Yl sange ts ¥s9tep) ‘+ Returns lis whose items are consecutive integers from 0 (included) to x (excluded) range (X,Y) ‘© Returns list whose tems are consecutive integers fram x (included) to y (excluded) + Empty istitio= y 4+ step isnot defined, default value is 2 ‘© Ust from x (included) toy (excluded) ‘+ Difference between each value—value defined by STEP ‘+ Stop ess than 0 © Range counts down from x to y © Bx range(10,2,2)~10, 8,6, Function returns BEE wen + a >=yand steps posive + wee yang step negative Function raises an BBG when: © step=0 ‘Te for lop: ‘+ terates through a sequence of objects ‘+ SEQUENCE ~ Container object inthe form ofa list, tuple or string swTax. ng_vaz in seque est] 4+ FIRST ITEM in the sequence (© Assigned to the iterating_var and the statement block's xecuted ‘+ ONE BY ONE each item Inthe Sequence is assigned 1 iterating_ver and the statement blocks executed unt the entire sequence i finished ” program ‘© DISPLAYS NUMBERS 1 T0 10 for 4 in vange(1,11): #default step value ie 1 (each number print ("odd nusbers in che range ace:*) for i in range(2/11,2): eine! ddd nunzere in the range ars 5 ep 2 value ie added to generate the next vals panezy 3 ‘+ Used to display elements from a TUPLE ‘+ Tests for membership in a sequence, such 2s; 2 strings © Ists © Tuples “IWO membership operators * in © Returns Boolean value true iit finds the variable inthe sequence © notin © Boolean value true it does not find the variable Examples: ‘ab in abcde ~ TRUE + 21n(10,3,5,8,1,4)— TRUE ‘+ bob notin at - TRUE for 4 in (7,3¢8,444)5 choice () "© Picks and returns a random item fiom 3 sequence = Used with lists © Tuples Strings ‘SuNTA: To use choice youneed toimport 2 random module ‘choice (sequence) xecnoice (range (2, 101)) print ("Random munber is", 2) oureur’ ‘= PRINTS BRINE NUMBERS oc TWEEN 2 AND 101 oureur: nei) in zangs(2, 101): for 3 an range (2,3) print (i) © print (2) oot (© tor 1o0p generates values trom z to 160 (9 Value of w gor ar 1 till loop assigns = new value ( 3 im ange (2/4): ‘te abjes0: x=0 Value in variable i is divided by 2 through (1-1! if vaiud in Variable i civides by any of these values, without = remainder, it is not a prime number ‘print (3) o Value in variable prints wnen ir does ro! and (2 = 1) divide by any value between 2

You might also like