So, in the last session, we learned how to make integer, float and string variables.
Today let us do some operations using integer and float variables!
- Write and run
a=2
b=5
print(a+b)
print(b-a)
product =a*b
print(product)
bhaag=b/a
ultaBhaag=a/b
print(bhaag,ultaBhaag)
Which of the printouts are integers? Which become floats? Python will leave the results of operations between integers as integers, unless they are forced to show a decimal value 😀
2. Now write and run
a = 2
b = 1.0
print(a*b)
What is the type of output? If any of the original variables is a float – the result will also be a float.
3. We can also define variables simultaneously as follows:
a,b,c =3,0,1
print(c)
print(a+b, a-c)
4. ‘%’ is a modulo operation in math. It gives you the ‘remainder’ after a division.
For example, 5 /2 ( 5 divided by 2) is 2.5, right? Then 5%2 would be 1 ( If you divide 5 by 2, you can go 2 times to get 4 and then ‘1’ is remaining).
Write the following and print them. (Try predicting the answers in your head first).
Leftover = 7%c
Leftover2 = 3%2
Your ‘c’ was previously defined in the preceding cell most likely.
5. Power operation is **
Write the following and run
Number = 4
NumberSquared = Number**2
NumberCubed = Number**3
NumberSquareRooted = Number**(0.5)
print(NumberSquared, NumberCubed, NumberSquareRooted)
Exercise:
The number 1729 is a very interesting number. It is called the taxicab number or Hardy-Ramanujan number based on an interesting story (Google 1729 and keep the Wikipedia entry handy for this exercise. There is also a nice movie based on those two mathematicians – especially the young Indian genius – Ramanujan.).
A. Define four variables a,b,c and d such that
- The additions of the cubes of a and b result in 1729
- The additions of the cubes of c and d also result in 1729
[ Hint: Third paragraph of that Wikipedia entry / the first equation of that Wikipedia entry ]
Cube them pairwise and print the results (1729 will be printed in both times).
B. Now, define three variable p1,p2 and p3 which are the factors of this number 1729 (factors of a number ‘x’ are prime numbers which multiplied together gives the number ‘x’) [Hint: on the right box of the Wikipedia entry ]
Print out the product of these variables.
C. Now,
Add the four digits in the number 1729 (9,7, 2 and 1 ) and save the addition in variable called ‘Masahiko’.
Invert the order of the digits in ‘Masahiko’ and save the new number as ‘Fujiwara’ (Both Masahiko and Fujiwara will be numbers that are less than 100).
Now multiply Masahiko with Fujiwara and print out the result!