# Python Basics: More on types

Types represent the classification of data and determine how values can be stored, manipulated, and interacted with. Understanding types is essential for effective data handling, proper function usage, and ensuring accurate program behavior.

For more posts about Python, follow the link below👇👇👇

In the previous post, we spared some to understand what variables and references are in Python. You can find it by following the link. 👇👇👇

We have already learned that Python is dynamically typed, so you don’t need to explicitly declare the variable type. On the other hand, variables have types. We have already seen two of them - *string* type (text) and *integer* type (number). Now is a good time to explore Python's types even more.

## Basic types

### str

In Python, * str* is a built-in data type used to represent strings, which are sequences of characters. A string is used to store and manipulate textual data, such as words, sentences, and even symbols.

Strings can be created using single (') or double (") quotation marks. For example:

`greetings = 'Hi, PyCharm'`

Strings can contain letters, digits, symbols, and even whitespace. You can concatenate strings using the `+`

operator:

```
>>> greetings = 'Hi'
>>> who = 'PyCharm'
>>> full = greetings + ', ' + who
>>> print(full)
Hi, PyCharm
```

You can also access individual characters using indexing (square brackets):

```
>>> print(full[4])
P
```

Python provides a wide range of string manipulation methods and functions, allowing you to perform operations like slicing, splitting, joining, formatting, and more:

`>>> sentence = "This is a sample sentence."`

- slicing:

```
>>> substring = sentence[5:13]
>>> print(substring)
is a sam
```

- splitting:

```
>>> print(words)
['This', 'is', 'a', 'sample', 'sentence.']
```

- joining:

```
>>> joined = '-'.join(words)
>>> print(joined)
This-is-a-sample-sentence.
```

- formatting:

```
>>> formatted = f"The length of the sentence is {len(sentence)} characters."
>>> print(formatted)
The length of the sentence is 26 characters.
```

Strings are versatile and widely used in programming for working with textual data, formatting output, and interacting with users through input and output operations.

### int

The `int`

data type represents whole numbers, which means they don't have any decimal places. Integers can be either positive, negative, or zero. They are used to perform various mathematical operations.

For example, you can define integers like this:

```
>>> x = 5
>>> y = -10
>>> x = 0
```

Integers support common arithmetic operations such as addition, subtraction, multiplication, and division:

```
>>> a = 10
>>> b = 3
>>> addition = a + b
>>> print(addition)
13
>>> subtraction = a - b
>>> print(subtraction)
7
>>> multiplication = a * b
>>> print(multiplication)
30
>>> division = a / b
>>> print(division)
3.3333333333333335
```

It's important to note that when you perform division with integers, Python will return a floating-point number (decimal) as the result, even if the division is exact.

If you want to perform integer division (floor division), you can use the `//`

operator:

```
>>> division = a // b
>>> print(division)
3
```

You can also use the `%`

operator to find the remainder of the division:

```
>>> reminder = a % b
>>> print(reminder)
1
```

In summary, the `int`

data type in Python is used to represent whole numbers, and you can perform a variety of mathematical operations using integers.

### float

`float`

is a built-in data type used to represent floating-point numbers, which are real numbers that can have decimal places. Floats are used to handle values that require fractional precision, such as numbers with decimal points or numbers expressed in scientific notation.

Floats can represent both whole numbers and numbers with fractional parts. For example, `3.14`

, `-0.5`

, and `2.0`

are all examples of floats. They can also be expressed in scientific notation, such as `1.23e-4`

which represents 0.000123. The `e`

or `E`

character indicates the exponent. Floats support common arithmetic operations like addition, subtraction, multiplication, and division. When performing arithmetic operations involving floats and integers, Python automatically promotes the integers to floats for consistent precision. It's important to be aware that floating-point numbers have limitations in representing certain values precisely due to their internal binary representation. This can sometimes lead to small rounding errors in calculations. When comparing floats, it's recommended to use methods that account for potential precision issues, such as using a small tolerance value to check for approximate equality, instead of using exact equality (`==`

).

Here are a few examples to illustrate the above:

```
>>> x = 3.14
>>> y = 1.5
>>> addition = x + y
>>> print(addition)
4.640000000000001
>>> subtraction = x - y
>>> print(subtraction)
1.6400000000000001
>>> multiplication = x * y
>>> print(multiplication)
4.71
>>> division = x / y
>>> print(division)
2.0933333333333333
>>> sci_notation = 2.5e3
>>> print(sci_notation)
2500.0
```

Floats are widely used for various scientific, mathematical, and financial computations where fractional precision is required. It's important to be aware of the potential precision limitations and take appropriate measures when working with them.

### complex

In Python, `complex`

is a built-in data type used A complex number is a number that has both a real part and an imaginary part. It is written in the form `a + bj`

, where `a`

is the real part, `b`

is the imaginary part, and `j`

represents the square root of -1.

For example, `3 + 2j`

, `-1.5 - 0.5j`

, and `4j`

are all complex numbers.

You can perform various operations on complex numbers, such as addition, subtraction, multiplication, and division. Python provides functions and operators to work with complex numbers and extract their real and imaginary parts.

Here's a quick example of using complex numbers in Python:

```
>>> z1 = 3 + 2j
>>> z2 = 1 - 1j
>>> addition = z1 + z2
>>> print(addition)
(4+1j)
>>> subtraction = z1 - z2
>>> print(subtraction)
(2+3j)
>>> multiplication = z1 * z2
>>> print(multiplication)
(5-1j)
>>> division = z1 / z2
>>> print(division)
(0.5+2.5j)
>>> print(z1.real)
3.0
>>> print(z1.imag)
2.0
```

Complex numbers are useful in various scientific and engineering calculations where real and imaginary components are involved.

### bool

In Python, `bool`

is a built-in data type used to represent Boolean values, which are binary values that can be either `True`

or `False`

. Boolean values are fundamental for making logical decisions and controlling the flow of a program.

Boolean values are often the result of comparison and logical operations. For example, when you compare two numbers, the result is a Boolean value indicating whether the comparison is true or false. Similarly, logical operations like `and`

, `or`

, and `not`

also produce Boolean results.

Here are some examples:

```
>>> x = 5
>>> y = 10
>>> is_greater = x > y
>>> print(is_greater)
False
>>> is_equal = x == y
>>> print(is_equal)
False
>>> is_not_equal = x != y
>>> print(is_not_equal)
True
>>> logical_and = is_greater and is_equal
>>> print(logical_and)
False
>>> logical_or = is_greater or is_equal
>>> print(logical_or)
False
>>> logical_not = not is_greater
>>> print(logical_not)
True
```

Boolean values are essential for controlling the flow of your program using conditional statements (like `if`

, `elif`

, `else`

) and loops (like `while`

and `for`

). They help determine which code paths to follow based on certain conditions.

## Type conversion

When writing a script, in many cases you will be either parsing a file or reading from terminal input.

**function to take input from the user. Whatever you enter as input, the input function converts it into a string.**

**input()**Let's write a simple script that will read two numbers from the keyboard and compute the sum.

```
a = input('Provide a\n')
b = input('Provide b\n')
sum = a + b
message = f'The sum of a and b is {sum}'
print(message)
```

Now we can run it. We will provide 1 and 2 as inputs for a and b respectively.

```
Provide a
1
Provide b
2
The sum of a and b is 12
```

How come the sum is 12...?!

The *input(...)* function provides everything as a string. So in this particular case, we concatenated two strings instead of summing numbers. To address such situations, Python provides a conversion mechanism. Type conversion refers to the process of changing the data type of a value from one type to another. You can use built-in functions like *int(…)*, *float(…)*, *str(…)*, and *bool(…)* to perform type conversions. For example:

```
>>> num_str = "42"
>>> print(num_str)
42
>>> type(num_str)
<class 'str'>
>>> num_int = int(num_str)
>>> print(num_int)
42
>>> type(num_int)
<class 'int'>
```

```
>>> float_str = "3.14"
>>> print(float_str)
3.14
>>> type(float_str)
<class 'str'>
>>> float_num = float(float_str)
>>> print(float_num)
3.14
>>> type(float_num)
<class 'float'>
```

```
>>> value = 123
>>> print(value)
123
>>> type(value)
<class 'int'>
>>> str_value = str(value)
>>> print(str_value)
123
>>> type(str_value)
<class 'str'>
```

Keep in mind that not all type conversions are valid, and some might result in errors if the conversion is not possible.

Now we can fix our script and add necessary conversions.

```
a = int(input('Provide a\n'))
b = int(input('Provide b\n'))
sum = a + b
message = f'The sum of a and b is {sum}'
print(message)
```

When we run it again, we get the correct result.

```
Provide a
1
Provide b
2
The sum of a and b is 3
```

The sum is now 3, so it's working!

**What's next?**

Subscribe to receive more posts like this directly to your email!

**Ideas💡, questions❔❓ ? Feel free to start the discussion 🗣️🎙️!**

Ready for challenges? 👇👇👇

## Comments ()