Ah, great question! You're ready to explore beyond expr and see how bc and python can handle more complex calculations. That's a fantastic next step in understanding the power of the Linux terminal!
As the "Fun Fact" mentioned, expr is good for basic arithmetic, but bc (basic calculator) and python give you a lot more power.
Let's look at bc first:
Using bc for Calculations
bc is a an arbitrary-precision calculator language. It's often used for calculations that require more precision or more advanced functions than expr.
Here's how you can use bc:
-
Directly in the terminal for simple calculations: You can pipe an expression into
bc.echo "15 / 7" | bc echo "scale=2; 15 / 7" | bc # 'scale' sets the number of decimal places echo "sqrt(25)" | bc -l # '-l' loads the standard math library echo "2^10" | bc # ExponentiationYou'll notice that for
sqrt()you often need the-loption to load the math library. -
Interactive mode: For multiple calculations, you can enter
bcin interactive mode.bc -l # Start bc. The -l loads the math library for functions like sqrt, sin, cos, etc.Then, within the
bcprompt (which won't show anything special, just wait for your input), you can type:10 + 5 15 / 7 scale = 4 # Set precision for floating point numbers 15 / 7 sqrt(100) quitType
quitto exitbc.
Using python for Calculations
Python is a much more powerful programming language, but it can also be used as a very capable calculator right in your terminal. Since Python is pre-installed on your LabEx VM, it's very convenient!
-
Directly with
python3 -c: You can execute a single Python command using the-cflag.python3 -c "print(8 * 12)" python3 -c "print(2**10)" # Exponentiation python3 -c "import math; print(math.sqrt(144))" -
Interactive Python shell: For multiple calculations or more complex logic, you can enter the Python interactive shell.
python3Once you see the
>>>prompt, you can type your calculations:>>> 10 + 5 >>> 20 / 3 >>> 20 // 3 # Integer division >>> import math >>> math.sin(math.pi / 2) >>> exit() # Or type Ctrl+D to exit
In summary:
expr: Best for very basic integer arithmetic, usually for single operations in shell scripts.bc: Excellent for more precise floating-point math, exponentiation, and even some trigonometric functions if you load the math library. Good for both single commands and interactive use.python: The most powerful of the three, capable of any mathematical operation, complex logic, and scripting. Its interactive shell is incredibly versatile for quick calculations or testing code snippets.
You can try these commands in your LabEx terminal right now! What do you want to try first?