# [Part II]Operators and Random Function in Python🐍

Subscribe to my newsletter and never miss my upcoming articles

Welcome back to the series "Learn Python with me!" 👋

Last time we talked about how to print the output to the terminal using `print()`, how to take an input using `input()`. We also know that `input()` by default takes a string, which can be converted to our desired data type.

Concatenation, I hope this term rings a bell. We use the `+` symbol to place two strings together, side-by-side.

Once you are ready let's take our next step!

### How does the computer understand our Python code?

We were writing Python Scripts which are files with a `.py` extension containing Python code. Computers only understand 0s and 1s(binary). They are actually not as smart as we think them to be. Python uses an interpreter to convert the code that we write to machine language(which the computer understands). The interpreter goes through the script line-by-line .

We can also run our Python commands in the console. If you are using PyCharm you will find the Python Console in the lower left hand corner of your screen. You can even run Python in any terminal, by simply typing `python` and clicking enter. You will see something like this👇. The `>>>` symbol is prompting you to write your line of code. If you do not see `Python <version>` in your console then you have to download Python in your computer. Download it from here.

We will be using the console to experiment with what we are going to learn next.

### Arithmetic Operators

These operators are used in mathematical calculations. These operators only work on `int` and `float` type variables or values.

Let's list the arithmetic operators here.👇

• `+` ->used to add two numbers. (We have already used this when we wrote the code to add two numbers). eg,5+2 = 7

• `-` -> Addition cannot go without Subtraction. So here it is.eg, 5-2 = 3

• `*` -> Multiplication. eg, 5*2 = 10

• `/` ->Division. eg, 5/2 = 2.5

• `%` -> Gives the remainder of the division . eg, 5%2= 1

• `**` -> Exponentiation operator. eg, 5 ** 2 = 25 (5 to the power 2 = 25)

• `//` -> Integer division. It truncates(cuts off) the decimal part of the answer. eg, 5//2 = 2

Note that the above are binary arithmetic operators, since they deal with two operands. Operands are the values or quantities on which the operation can be done.

`Unary '-'` -> Is a unary operator. It is used to denote negative numbers. eg, -2, -3.0 .You can clearly see that it deals with only one operand.

We will be using out Python console to test out these operators. Before that, we should be clear about something.

#### Precedence of Arithmetic operators.

A mathematical equation is solved by following an order of precedence of the operators.

The order(highest to lowest) is as follows:-

1. Parenthesis -> ()

2. Exponentiation -> ( ** )

3. Unary minus -> ( - )

4. Multiplication , Division , Integer Division, Modulo(Remainder) -> *, /, // , % (they have the same precedence, they are evaluated from left to right in an equation)

5. Addition, Subtraction -> + , -

Let's solve this equation to understand it a bit better.

Q.`1 + 3 * 5 / 2`

We don't have a parenthesis, exponentiation or unary minus. So we go to the next step.

=> `1 + 15/2`

`/,*,//,%`are evaluated from left to right . Hence we evaluated 3 * 5 first .Next we will evaluate 15/2.

=> `1 + 7.5`

=> `8.5`

We will use Python Console now , or type `python` in your terminal and click on enter.

I want you to type this and see the results in the console.

1. `1 + 3*5/2` -> Check the answer that we evaluated above.

2. `5-3//2` -> after evaluating, try using parenthesis in the appropriate places to get the answer as 1.

3. `8-6+5//4` -> after evaluating, try using parenthesis in the appropriate places to get the answer as 6.

Use pen and paper if necessary and try to evaluate them on your own. After which you can write them in the console and check your answer. Note that I have used two ways to get to 6. Using parentheses in your equations even when you know that precedence will take care of it is better, since it is less error prone.

You can exit python in your terminal by calling the exit() function, which means typing exit() and hitting enter.

Next I want you to see these results very closely.👇 #### Observations:-

• Division `/` always gives a float value as an answer. Two operands can be both `int` or either one can be `float` or even both can be `float` , but it still gives a float value as an answer.

• Integer division `//` as the name suggests, rounds the division to the nearest whole number.

• Addition depends on the operands. If at least one of the operands is `float` , the result is float.

• Exponentiation `**` depends on the result. `2**-1` means 2^-1 , which is 0.5(`float`) whereas `2**3` means 2^3 which is 8(`int`).

#### Float is a bit a crazy!

When we try to evaluate `1.9 - 1` we will expect 0.9 to be the answer. But that is not the case. It gives the result as `0.8999999999999999`. Python cannot display certain numbers exactly. It follows binary approximation. To read more about it check the docs here.

Try some calculations on your own and see for yourself how a certain operator works on changing the data type of operands. These conversions between types that happen on their own are called Implicit Type Conversion.

Similarly, we have Explicit Type Conversion.

We can change the result to the type we want it to be. We have seen an example of explicit type conversion where we added two numbers. We convert the string values that the `input()` takes to the respective`int` values. We can do the conversion in the same line as we take the input.

``````def main():
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
sum = num1 + num2
print(sum)
if __name__ == '__main__':
main()
``````

Let's find the BMI of a person. The person enters their weight and height and we will provide them with their BMI.

The formula for BMI(Body Mass Index) is Weight(in kg)/(Height(in m^2))^2. (We can assume that the user provides their weight in the correct unit)

Give this a good go and then have a look at the solution below.

``````def main():
weight = float(input("Enter your weight is kg: "))
height = float(input("Enter your height in m: "))
bmi = weight/ (height**2)

if __name__ == '__main__':
main()
``````

We take the values as `float` since height and weight can very well be in decimals.

Let's look at the terminal. There are a few expression shortcuts that we should know:-

• `num = num + 1` can also be written as `num += 1`

• `num = num - 1` can also be written as `num -= 1`

• `num = num * 1` can also be written as `num *= 1`

• `num = num / 1` can also be written as `num /= 1`

For people who might be familiar with num++ or num-- etc in other languages, it is not present in Python.

### Constants

We have not seen a lot of constants in our lives since the year 2020, but thankfully the world of computers and mathematics has some.

Constants such as pi = 3.14159265.... , c (speed of light) = 299792458 m/s, phi(Golden Ratio) = 1.618034... (pi and phi are irrational numbers that go on forever, I have mentioned the digits I had in my memory. When dealing with these numbers, we normally use them till 2 decimal places)

Constants in Python, by convention are written in Capital letters above the main function. Why above the main function? So that the constants can be used in any function in the program. Remember, when we spoke about `scope` of a variable in the previous part. Variables are visible only inside the function in which they are declared. Placing our constants above main, we making it visible to any function that might be present in the whole program.

Remember when we were kids, and did not know what energy, mass, speed of light even was, but whenever someone mentioned Einstein, the first thing we said was E = mc^2 😁.

Let's write the program for that using c(speed of light) as a constant.

``````C = 299792458
def main():
mass = float(input("Enter mass in kg: "))
e = mass * (C**2)
print(str(e) + " J of energy ")

if __name__ == '__main__':
main()
``````

Let's run our program. Note: If you don't know what e+18 means in the result displayed above, it means 10^18. e is a short form for scientific notation.

Here you go, a short and sweet program using one of the greatest contributions to science!

Constants are also convenient to use when you need to maybe include more decimals to the value stored. If you have used the constant all over in your program then you do not have to go about changing it everywhere. One single change of the value where it is declared above the main function will reflect everywhere.

### Math library

Some mathematical functions are in-built in Python. We need to `import` it into our Python Script.

Just add `import math` above at the very top.

Some important functions are :

• `math.pi` → mathematical constant pi

• `math.e` → mathematical constant e

• `math.sqrt(x)` → square root of x

• `math.exp(x)` → returns e^x

• `math.log(x)` → gives back the natural logarithms of x (ln x)

The best place to test these out quickly is our terminal. There are a lot more useful functions that we will learn as we go further into Python. For a full list check the documentation.

### Random Number Generation in Python

There is "no true" randomness in Python or even Computers in general. There is always a specific equation or relation providing us with the tools we have. These are pseudo-random number generators.

Under the hood, it is generated following a certain way, but to us humans it looks pretty random.

Think of the generator as a mysterious box which is closed. You can just see what goes in and comes out of it. What goes in is called the "seed". It is a value that enters the box, goes through a complex function and comes out as a certain numerical value which seems random. The initial seed can also be specified by us, with the help of the seed() function.

If the seed is not specified the computer uses the seconds that have passed since Jan 1 ,1970 as the seed, called the Unix time. Hence the value cannot be the same the second time you use it, unless you specify it.

#### Why do you want to specify the seed?

Maybe you are using random numbers and your program gives an error or does not work the way it is supposed to for only certain values. If you specify the seed, there will be a specific sequence of numbers that will be generated, so that you can debug your code, instead of waiting for a long time to see if the number repeats itself. Hence, specifying a seed makes debugging easier.

#### How do we use random library ?

Like the `math` library, Python has a `random` library. We need to import it into our program using `import random` . A couple of useful functions are mentioned below:-

• `random.randint(max,min)` -> Returns a random integer between max and min.(Note :- max and min inclusive)

• `random.random()` -> Returns a random real number( float value ) between 0 and 1.

• `random.uniform(max,min)` -> Returns a random real number(float value) between max and min.

• `random.seed(x)` -> Sets the seed of random number generator to x.

Let's take roll two dice and see their outcome. Note that the number of sides of the dice is 6 (constant)

``````import random

NUM_SIDES = 6
def main():
die1 = random.randint(0,NUM_SIDES)
die2 = random.randint(0,NUM_SIDES)

print(die1)
print(die2)

if __name__ == '__main__':
main()
``````

Every time you run the program you will get a different set of outcomes for each die.

### Comparison operators

These are used to compare two values . Their result is always a bool value, that is, True/False.

• `==` equals operator is used to check for equality.

• `!=` not equals operator is used to check if some value is not equal to the other.

• `<` less than operator.

• `>` greater than operator.

• `<=` less than or equal to operator.

• `>=` greater than or equal to operator.

Note that all have equal precedence.

Going back to our terminal. ### Logical Operators

We have three logical operators. These are used in conditional statements resulting in True/False

• `and` -> This is a binary operator. When we write `x and y`, the result will depend on the operands(x,y). This statement will be True, if both of the conditions are True.

• `or` -> This a binary operator. When we write `x or y`, the result is True if either of them are True. It is False only when both are False.

• `not` -> This is a unary operator. It reverts the value. ### Precedence of operators

arithmetic > comparison > not> and/or

Q. `5 * 7 >= 3+5 *(7-1) and not False`

=> `35 >= 3 + 5*6 and not False`

=> `35 >= 3 + 30 and not False`

=>`35 >= 33 and not False`

=>`True and True`

=>`True`

Try this out in the console too!

We learnt about various operators and the random function in this part! The most beautiful part about programming is how everything comes together. We can discuss any issue in the comments below! Let's help each other grow📈!

Next we will be talking about Control Flow in Python🐍

Happy learning!