Lab activities for general Python programming workshop.
Attached is a calc.py
script, which is a basic functional calculator program.
Whilst you can complete the tasks in any order, they start easier and get harder, so we'd recommend completing them in order. Each new feature must not break functionality introduced in a previous.
Each task is presented with an example output. This is merely an example - feel free to write it however you wish.
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 5
Invalid choice - try again
Enter choice(1/2/3/4): 5
Rather than entering numbers for each of the operations, use the mathematical symbol ("+" for addition etc)
Select operation:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
Enter choice: +
Select operation:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
Enter choice: +
Enter first number: 2.5
Enter second number: 3.5
2.5 + 3.5 = 6
When prompted for a number, if someone enters something which isn't a number, show an error message and ask for the value again
Select operation:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
Enter choice: +
Enter first number: no
"no" is not a number. Try again.
Enter first number: no
Extension: If someone gives an invalid value for the second number, don't ask for the first number again.
Select operation:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
- Exponent (**)
Enter choice: **
Enter first number: 2
Enter second number: 3
2 ** 3 = 8
In Python, the "power of" operator is **
.
Select operation:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
- Exponent (**)
- Square Root (sqrt)
Enter choice: sqrt
Enter first number: 9
sqrt 9 = 3
Select operation:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
- Exponent (**)
- Square Root (sqrt)
Enter choice: /
Enter first number: 3
Enter second number: 0
3 / 0 failed: ZeroDivisionError: float division by zero
Enter choice:
Available operations:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
- Exponent (**)
- Square (sqrt)
> 2 + 3
= 5
Support "Reverse Polish" notation, where the operator comes after the numbers
Available operations:
- Add (+)
- Subtract (-)
- Multiply (*)
- Divide (/)
- Exponent (**)
- Square (sqrt)
> 2 3 +
= 5
This should work in addition to normal (infix) notation.