Python Variable & Arithmetic Exercises
Python Variable & Arithmetic Exercises
To check divisibility in Python, you use the modulus operator `%`. If `a % b == 0`, the number `a` is divisible by `b`. For example, to check if `n = 37` is divisible by `3`, compute `37 % 3`. Since this results in 1, `37` is not divisible by `3` .
In Python, a common approach to swap two variables without using a temporary variable is to exploit tuple unpacking. For instance, to swap `a = 5` and `b = 10`, you can use the syntax `a, b = b, a`. After executing this, the value of `a` becomes 10 and `b` becomes 5, which effectively swaps their values .
To calculate the average of two numbers in Python, you add them together and then divide by the number of values, which is 2. For example, given `a = 14` and `b = 6`, the average can be calculated as `(a + b) / 2`. Evaluating this expression, `(14 + 6) / 2` gives an average of 10.0 .
Python employs the `**` operator for exponentiation. For example, to calculate the power `a**b`, where `a = 13` and `b = 4`, you use `a**b`. This expression evaluates to `13**4`, which results in 28561 .
Calculating geometric properties like area, perimeter, and volume can influence programming solutions by providing essential data for tasks such as resource allocation, layout design, and material estimation in real-world applications. For example, in Python, calculating the perimeter of a rectangle, given `length = 10` and `breadth = 5`, is straightforward using `perimeter = 2 * (length + breadth)`, yielding a result of 30 .
To calculate the area of a triangle in Python, you use the formula `area = 0.5 * base * height`. For example, with `base = 6` and `height = 4`, the area is calculated as `0.5 * 6 * 4`, resulting in an area of 12.0 .
Simple interest in Python can be calculated using the formula `simple_interest = (P * T * R) / 100`, where `P` is the principal, `T` the time, and `R` the rate. For example, with `P=1000`, `T=2`, and `R=5`, the simple interest is calculated as `(1000 * 2 * 5) / 100`, resulting in 100.0 .
In Python, division and modulus can be calculated using `/` for division and `%` for modulus. Given `a = 11` and `b = 3`, division is `a / b` which evaluates to `11 / 3 = 3.6667`, and modulus is `a % b` which yields `11 % 3 = 2` .
The perimeter of a rectangle is found using the formula `perimeter = 2 * (length + breadth)`. For example, given `length = 10` and `breadth = 5`, the perimeter is calculated as `2 * (10 + 5)`, resulting in 30 .
In Python, to determine if the sum of two numbers is even or odd, you can use the modulus operator. First, calculate the sum `sum = a + b`, then check if `sum % 2 == 0`. If true, the sum is even; otherwise, it's odd. For instance, if `a = 3` and `b = 5`, `sum = 8`. Since `8 % 2 == 0`, the sum is even .