Today we are going to see the following topics in python.
- Data Types
- Type Check
- Type Conversion
- Mathematical Operations
Data Types
In python, we have 4 types of data we usually refer to them as data types.
1. Strings
It is just a string of characters, and when we create it we have to put them in double quotes. example:
print("Hello world")
We can also get a specific element from a string by passing its index in [], this method is called subscript.
An example is below:
name = "John"
print(name[2])
# The out will be "h"
Always remember, indexes in python start with 0.
We can also check the length of a string by using len() function. An example is below:
name = "john"
print(len(name))
# The output will be "4"
len() only works with strings.
2. Integer
Integers are just whole numbers, and we don't need to put them in double quotes.
Example:
age = 24
3. Float
Integers are just decimals numbers, and we don't need to put them in double quotes.
Example:
bill = 124.5
We can also determine the number of decimals by using the round() function.
For example, our bill is "99.22425" and we want to display only 2 decimal numbers, we can do that in the following way.
bill = 99.22425
print(round(bill, 2))
# The output will be "99.22"
First we have to add the decimal value, and then the number of decimals we want.
4. Boolean
It is a simple data type and we define it by True and False.
It is mostly used to check the authenticity of conditions and logic in code.
Type Check
We can check the data types by using type() function.
print(type("Hello World"))
Type Conversion
We can convert data types of values by using some default python functions.
We need to convert data type in certain cases. For example, if we want to concatenate the age and name of any person. It won't happen unless both data types are "string", because we can only concatenate strings. For this, we have to change the data type of age from integer to a string.
int() function is used to change the data type to integer.
str() function is used to change the data type to string.
float() function is used to change the data type to floating numbers (with decimals).
Mathematical operations
We can mathematical operations in python by using normal math symbols.
- "+" for addition
- "-" for substraction
- "*" for multiplication
- "/" for division
- "**" for exponent (power of any number)
Mathematical operations are work according to "PEMDAS" rule. This means they'll perform in the following sequence:
- Parentheses (first)
- Exponents (second)
- Multiplication (third)
- Division (forth)
- Addition (fifth)
- Subtraction (last)
We can't perform a mathematical operation on strings and booleans.
Top comments (0)