2.4. Data Types#

Float (float):

Represents real numbers with decimal points. Floats are used when dealing with continuous values, such as measurements or fractional numbers.

2.0 + 3.0
5.0
one_half = 1/2
type(one_half)
float

String (str):

Represents sequences of characters, enclosed in single, double, or triple quotes. Strings are commonly used for text manipulation.

greeting = "Hello, World!"

Boolean (bool):

Represents truth values: True or False. Booleans are essential for conditional logic (e.g., decision-making in code).

is_active = True
a = 10        # integer
b = 3.14      # float
c = a + b     # adding an integer and a float

a = 10:

  • We assign the integer 10 to the variable a.

  • In Python, integers can be positive or negative whole numbers.

b = 3.14:

  • We assign the float 3.14 to the variable b.

  • A float is a number with a decimal point.

c = a + b:

  • We add a (which is 10) and b (which is 3.14).

  • Python automatically converts the integer a to a float during the addition.

So, c will be 13.14, and c becomes a float.

2.4.1. String Manipulation#

Strings are a sequence of characters that represent text data, and they can be manipulated in various ways.

greeting = "Hello, " + "World!"
name = "Sid"

greeting = "Hello, " + "World!":

  • We are using concatenation here, which means we are joining two strings together.

  • The + operator for strings appends one string to another. So greeting becomes "Hello, World!".

2.4.2. Adding Booleans#

In Python, True and False are actually treated as 1 and 0, respectively, when you use them in arithmetic expressions. This means you can add, subtract, and even multiply booleans as if they were numbers.

a = True   # equivalent to 1
b = False  # equivalent to 0

result = a + b  # this will be 1 (True + False = 1 + 0 = 1)
  • True behaves like the integer 1, and False behaves like 0.

  • When you add True + True, it’s like adding 1 + 1, so the result will be 2.

  • When you add True + False, it’s like adding 1 + 0, so the result will be 1.