0 ratings 0% found this document useful (0 votes) 4 views 12 pages Chapter 4 Programming-Note 1
The document outlines various algorithms and programming concepts, including methods for manipulating digits, decoding messages, and performing arithmetic operations in Python. It also discusses Boolean expressions, data types, and built-in functions, providing examples and exercises for practice. Additionally, it includes programming tasks related to calculating areas and simulating dice rolls.
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
Carousel Previous Carousel Next
Save Chapter 4 Programming-Note 1 For Later Ser Pabog
Chapter 4 Programming - Note 1
1. The following an algorithm that can be pevformed on any digit from 1 to
Step 1: Multiply the input dig by 9.
Step 2: Multiply the result by 12345679, This isthe output
emintnigntrsodonuiee nesters 1)049.049 aa
bya Wo) 922222222
Q?
a3 0) 799997794
The following san algorithm that ean be performed on any postive whole number (Make sure to use the
denary number system.)
‘top 2: alclat the eifforence between the input number an the input number with its digits reversed,
Step 2: Add up all the digits of the result (ignore the ig.
Step 3: the reslt has only digit this: the output. Otherwise, go backto Step 2.
So i
a2 z
pate a)"
9st 4) y
4 4)0
4) 40008
The following isan algorithm used for decode secret messages. requires a secret message and a positive
wihole umber ta be previded as inputs.
‘Step 1: Exact the ist Nleters of the secret message where Ns the provided number.
‘Step 2: Append the extracted letters to the remaining letters of the secret message, This s the output.
For example, ithe inputs are
Secret message = MPLEEXA
Number 4
ForStep1,theertracted letters are MPLE. For Step2, the extracted letters MPLE are appended tothe remaining
letters ExAto obtain the output EXAMPLE
Now determine he sgt output hen teint
SW Seaetmessege NBL
me Sie
2) Remkmeonemichk Re Joct
a feceimease thy up
‘Number: 1
1. State whether each of flloming statements are true o fle.
2)Pythonic a propmming language Trak
-b) Pyne an algpeti a
q)Aprocessorisamadeat instructions. "PONS
@)Aprogramie sade onstruction. TyuAILS Sonn of rare | ond
mae?
4. Mody the input specifications for the addition problem in Table 42 so that both postive and negative whole
numbers are valid inputs. Determine whether the original addition algorithm és. a solution to this modified
Faaae trek ahr i =
ee ego
Sette np and cut requement for ers problem ope | jeotest
ie
2. ibiea howe ponies linen ot euler alti a vtageicinat Mit
Suggesthow canbe improved and wh.
Table4S Input and output requirements for the averoge sare problem
[Tite name othe clas test
Scores of cass test seotes with each students
Sear included once
1. Braminethefellowing program:
[hours = 6 %
| hours = hours +12
print (hours)
‘When Python runs the program, it performs the following steps, but nt inthe order presente:
{) Displays the value assigned to hours on the screen
B) Calculates the sum ofhours and 12 to obtain 12=18
(6) Assigns 6tobours
D) Aesigne IB to hours
‘Arrange the tep2A, 8, Cand D inthe corect order as performed by Pythona)
iian_people = 6
rmchairs = 3
shortage ~ num people
print shortage)
week length = 7
today = 4
today = today + week Length
prant today)
cost - 10
cost = cost + cost
savings = 250
savings = savangs - cost
print savings)4. deny whether each ofthe following code snippets shows a function call,a method call or the use ofan
operator:
a) [prantinane, contact)
by Len(descrspsion)
| numbers. append(3)
4) cost / count
©) [Fereadtined)
1) [-resute
2. Examine the following program:
‘abe(),min1) and print) are bulttin Python functions
State the order in whic the abs(), min) arid print() function call are performed in the program.
(Hint: aninner function call must be competed first soits return valuecan be used asan argument fr the outer
funetion call)
SS
printiabviain-a, @ 11 +1]
st etn sd plot Se balm Pn haba + oparor mst pr sr ace
persion
‘tatetheorderinwhich the abs (),min() andprint( functioncallsandtheaddition operation are performedin,
the program.1. Write a program that uses input (and prant() to solvethe following problem:
eput ‘Output
name: nanedftheuser | «name displayed 3 meson?
separate ines
Toble4.1¢ input and output requirements for
‘mutiple-lne name pain problem
2. Véritea program that uses anpot ) and print() te solve the following pr
Input Output
snamernamedttheuser | «name displayed 3 times ona
single line, separated by spaces
Tole -415 Input and output requirements for
‘inglelibe name pening problemBoolean
Python Relational Operators
ee [Name | Example [ Satna ]
[eau a
[ert eaua
> [arene tan
ls han
F_ [ester enon orequl
| fe eeaieton areata |
less than or equal
Practice Now 1
‘Statement
4
prsntenit = a
Print (Faiae = False)
[a [oe | Ae® ][a | 8 | Aande |[ A | nora |
[ive [rue [wwe] [ue [Fue | true | [Tue | Fase |
[Te [robe | Tue || True | False| fase | [Fate | tow |
[Fabe [Toe | Tue | False True | False
Fate [Fae| False || Falke [Fale | Fate
—- and returns True
ifeithge condition sue only when bath
eens eT
Practice Now 2
Statement Output
fo) prineti or
4) print trae ae 0)VM leo go tar
2..At.a water treatment lant, an alarm rings ifthe water levelin atankisfll and the drainage pipe is closed,
unless an overide swatch is turned on.
Itisgiventhattank_fullisabool equaltowhetherthetankisfull,draanage_openisabootequaltowhetherthe
rainage pipe is pen and override_onis abool equal to whether the override switch is turned on
Which ofthe following Boolean expressions is equal to whether the alarmis ringing?
3) (tack full and drainage_open) oF not everride on
) (tank “full and drainage open) and override on
) {tank full and not drainage_open) and not override_on
@) (tank full and not drainage open) or override_on
3. Aprogrammer wishes to obtain a Boolean that is True only fan int variable, num, isether-1 or any value other
than 10.0r20.
Flin the blanks forthe required Boolean expression below using “and” and “or* only.
um == -1_____ (num t= 10 _____ num t= 20)
Data Type
Practise Now 1
a type (223) ) type (True)
2) type (223.455) ©) type (tone)
ctype (word)Integer and Float
Python Arithmetic Operators
Operator Name Example
+ Aadition |
- Subtraction
= Multiplication
i Division
++ Exponent power)
11 oor Division
3% [Modulus (remainder)
Operator Example Equivalent
“il
Practise Now 2
x= 10 ‘Output
int (x)
wi
print (x)
x//~10
print (x)‘Bultein Function Return Output
inn) Retums an int equal o the argument converted | printint2.024))
ta an integer (i possible) For floats, the
‘conversion cuts off the digs afterthe decimal | printinti-3.9))
point
printin("2024")
float) Relums a float equal tothe argument converted | printfosti2))
to. floating-point number (f possible).
printioat-2024))
prin(foat("2024"))
max() RRelums the maximum value out f the given prinimax(2, 2, 4))
arguments,
alist=[2,-2, 4)
printimaxialist))
min) Returns the minimum value out of the given printiming2, -2,4))
arguments.
alist = [2,-2.4]
print(min(aist))
absi) Retums an int oraflost equal to the sbsolute | print(abs(2024))
value of te argument.
print(abs-2024))
powa, b) Retums a foat equal the frst argument (2) | prit{powi2, 4))
‘ized to the power of the second argument (b).
7 print(pow(2.0, 4))
print(pow(2, 4.0))
round) Returns an int equalto the argument rounded to | print(reundi2.024))
the nearest integer
print(round\-2.024))
round) Returns an int equal to the argument rounded to | prin(vound(2.024))
the nearest integer
pin(round(-2.024))
roundia, b) Returns a float equal tothe first argument (a) | printrounsi2.024, 2)
rounded to the number of decimal places
indicated by the second argument (6)Built-in Math function: range )
Return a sequence of integers
range(3)
ieee Detar
range(4, 8)
rang ee non
range(3, 20, 4)
range (a,
import math
Math module Return Output
math ei) Retums an int equal othe smallest integer printmath.ce0.25)
fester than or equal to the argument
printmath caik-0.25))
math oor) RRetums an int equal tothe largest integer smaler | printmath foar0.75))
than or equal tothe argument
printimath foor(-075))
mathsart) Retums a float equals the square rst ofthe | printmath sqr(25)
srqument
rmath.truned) Retume an int equal to the prinmathunct2.024)
ergument with digits efter the
decimal pointcut of (ie. truncated),
printimath.trunc(-2.024))
import random
Function Return Output
random randin{) Retums a random int between the two arguments | prii(random rancint(2,7))
(inclusive),
random.random() | Retums @ random float between 0 (inclusive) end | printrandom.random()
1 (exclusive)
101. State whether each ofthe expressions below evaluate to True or Fase.
a0>1 Bl>e c2>0and2<1 d)2>00r2<1
2. Whats the output ofthe fllowing code?
product - 10.49 + -2
converted to int = int(product)
print (converted to int)
a) 21 4) 020 a2
3. Predict the output ofthe following code:
remainder - 17 ¥ 6
print (remainder)
4. Predict the output ofthe fllowing code:
x=
kya
xte2
print (x)
5. For each value ofx below, predict the result ofthe respective rounding functions. Check your answers by
printing the actual return values in Python
x ore | 1965] 01 | 00 | 01 | 1965 | 2028
ath cello
ath. floor (a)
rounds)
ath. travel
ee 22 mes ores onang cts
"ri |
6. When two si-sided dice are tolled, the resulting sum cen range from 2to 12 inclusive) with 7 being the most
aly
‘Wirt a program to simulate rolling two six-sided dice and output the resulting um.
. The area of atriangle with base b and height hs given by the formal A="/sbh.
‘Write program to solve the following triangle area calculation problem:
Input ‘Output
base of tangle ~ Aeea of rangle obtained bythe Formula
shrbeight of triangle Abb
Tene 30 rev ondonet ornate og area ate plen
(band h should be provided as inputsby the user and converted to floats)
8 Thehypotenuse cof a rght-angled triangle with ather two sides of lengths a and bis given by Pythagoras's
formula ¢= Ya.
Wirt » program to solve the following hypotenuse calculation problem:
apt Output
‘ar length of triangle’ side Length of triangle's hypotenuse obtained by
+ bilength oftriangle's side Pythagoras’ formula c= Va"#B, rounded to2
decimal paces
Tees pon aapet wcoroscta fa ype anton potion
{ond b should be provided as inputs by the user and converted to floats)
12