Pages


Monday, 3 December 2018

(Post 4/Year 1 Week 1)Learning python part 4:Python basics-Basic math and Different data types

In part 4,we will be learning about the basic math of Python

Basic Math

Most of us are familiar with the basic operation with math in school such as +,-,*,/ (addition,subtraction,multiply,divide),but below is a quick recap anyway


##addition
print(8+5)

##subtraction
print(8 - 5)

##multiple
print(8*5)

##divide
print(8/5)

Output



Besides,the usual operator there are also special operator such as exponentation,modulus and increment

##Exponentiation—raising to a power
##If you wanted to multiply 3 by itself 5 times, you could write

print(3 * 3 * 3 * 3 * 3)
print(3 ** 5)

##Modulus—getting the remainder
print(7 % 2)

##Increment and decrements
##similar to addition and subtraction
number = 7
number += 1
print(number)

number = 7
number -= 1
print(number)


Output




Different Data types

Most of the time ,you will be using these three types of data str, int or float
  • float() will create a new float (decimal number) from a string or integer.
  • int() will create a new integer from a string or float.
  • str() will create a new string from a number (or any other type).
So let's try to convert the data below

##1.Changing an int to a float
a = 24
b = float(a)
print(a)
print(b)

##2. Changing a float to an int
c = 38.0
d = int(c)
print(c)
print(d)

e = 54.99
f = int(e)
print(e)
##you can see that f is rounded up
print(f)

##3.Changing a string to a float
a = '76.3'
b = float(a)
print(a)
print(b)

Output



Checking the type

You can also check the type of the data as below

##4.checking the type
a = '44.2'
b = 44.2
print(type(a))##str
print(type(b))##float

output


No comments:

Post a Comment