Page 218 - Computer Science Class 11 With Functions
P. 218
nepatlOuSpuS:
>>> Enter a number : 10
POSITIVE
NtxS,latSlutlwriStlnlfunctonlShnSlncctpStlntlinpuSlnlbinnryloptrnSorlnndlSwoloptrnndtlnndlcoepuSttlShtlrttuaSlofl
nppayinglShtloptrnSor.lThtlfunctonletrtaylchtcktliflShtlgivtnloptrnSorlenSchttlnnyloflShtloptrnSortlwiShinlShtlttSl
{+, -, *, /, %, //, **},lnndlrtSurntlShtlrttuaSloflnppayinglShtloptrnSorlSolShtloptrnndt.l
Program 9.8 WriStlnlfunctonlcalculator(operator, loperand, roperand)lShnSlcoepuSttlShtlrttuaSlofl
nppayinglShtloptrnSor.
Solution:
01 '''
02 objective: To evaluate an integer expression with two operands
03 Approach: 1. To accepts the operator and the operands from a user
04 2. Use function calculator() to evaluate the expression
05 '''
06 def calculator(operator, loperand, roperand):
07 '''
08 objective: to apply operator to integer operands
09 inputs:
10 operator: operation to be performed (e.g., /)
11 loperand: left operand (e.g., 30)
12 roperand: right operand (e.g., 4)
13 return value: evaluation of expression: loperand operator roperand (e.g., 30/4)
14 '''
15 if operator == '+':
16 return loperand + roperand
17 elif operator == '-':
18 return loperand - roperand
19 elif operator == '*':
20 return loperand * roperand
21 elif operator == '/':
22 return loperand / roperand
23 elif operator == '%':
24 return loperand % roperand
25 elif operator == '//':
26 return loperand // roperand
27 elif operator == '**':
28 return loperand ** roperand
29 else:
30 return '???: invalid operator'
31 #ltOperand,rtOperand: operands to left and right of the operator
32 operator = input('Enter operator from {+, -, *, /, %, //, **}: ')
33 ltOperand = int(input('Enter left operand (integer): '))
34 rtOperand = int(input('Enter right operand: (integer): '))
35 answer = calculator(operator, ltOperand, rtOperand)
36 print(ltOperand, operator, rtOperand, ' = ', answer)
nepatlOuSpuS:
>>> Enter operator from {+, -, *, /, %, //, **}:**
>>> Enter left operand (integer): 3
>>> Enter right operand: (integer)4
3 ** 4 = 81
>>> Enter operator from {+, -, *, /, %, //, **}://
>>> Enter left operand (integer): 243
>>> Enter right operand: (integer)12
243 // 12 = 20
216 Touchpad Computer Science-XI

