2.2 Integers, Floats, and Strings

In Python, data types define the nature of the values that variables can hold. The most common data types you will work with are integers, floats, and strings. Each of these types serves different purposes and has its own characteristics. In this section, we will explore these basic data types in Python, how to work with them, and common operations you can perform on them.


2.2.1 Integers (int)

An integer in Python is a whole number (positive or negative) without a fractional part. It can be of any length, constrained only by the memory available on your system.

2.2.1.1 Declaring Integers

You can assign an integer value to a variable by directly writing the number without any decimal point.

Example:

x = 10     # Integer value
y = -5     # Negative integer

2.2.1.2 Basic Integer Operations

You can perform basic arithmetic operations on integers, such as addition, subtraction, multiplication, and division.

Examples:

x = 10
y = 3

# Addition
print(x + y)   # Output: 13

# Subtraction
print(x - y)   # Output: 7

# Multiplication
print(x * y)   # Output: 30

# Division (floating-point result)
print(x / y)   # Output: 3.3333333333333335

# Floor Division (integer division)
print(x // y)  # Output: 3

# Modulus (remainder)
print(x % y)   # Output: 1

# Exponentiation (power)
print(x ** y)  # Output: 1000 (10^3)

2.2.1.3 Type Checking

You can check the type of a variable using the type() function.

Example:

x = 42
print(type(x))  # Output: <class 'int'>

2.2.2 Floats (float)

A float is a number that includes a decimal point or is represented in scientific notation. Floats are used to represent real numbers and can have a fractional component.

2.2.2.1 Declaring Floats

You can assign a float value by writing the number with a decimal point.

Examples:

pi = 3.14       # Float value
x = -7.5        # Negative float
scientific = 1.5e3  # 1.5 * 10^3, or 1500.0 (scientific notation)

2.2.2.2 Basic Float Operations

Just like integers, floats can be used in arithmetic operations. When you perform arithmetic between an integer and a float, the result is automatically a float.

Examples:

a = 5.0
b = 2

# Addition
print(a + b)   # Output: 7.0

# Subtraction
print(a - b)   # Output: 3.0

# Multiplication
print(a * b)   # Output: 10.0

# Division (result is always a float)
print(a / b)   # Output: 2.5

# Exponentiation
print(a ** b)  # Output: 25.0

2.2.2.3 Type Checking

You can verify that a variable is a float by using the type() function.

Example:

pi = 3.14159
print(type(pi))  # Output: <class 'float'>

2.2.2.4 Rounding Floats

You can round floats to a specified number of decimal places using the round() function.

Example:

pi = 3.14159
print(round(pi, 2))  # Output: 3.14 (rounded to 2 decimal places)

2.2.3 Strings (str)

A string in Python is a sequence of characters enclosed in either single quotes ('), double quotes ("), or triple quotes (''' or """ for multi-line strings). Strings are used to represent textual data, such as words, sentences, or any other sequence of characters.

2.2.3.1 Declaring Strings

You can declare a string by enclosing the text in quotes.

Examples:

name = "Alice"              # Using double quotes
greeting = 'Hello, World!'  # Using single quotes
paragraph = """This is a 
multi-line string."""       # Using triple quotes

2.2.3.2 String Operations

  1. Concatenation: You can concatenate (join) two or more strings using the + operator.

Example:

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Output: John Doe
  1. Repetition: You can repeat a string multiple times using the * operator.

Example:

greeting = "Hello! " * 3
print(greeting)  # Output: Hello! Hello! Hello! 
  1. Length: You can find the length of a string (number of characters) using the len() function.

Example:

message = "Python"
print(len(message))  # Output: 6
  1. Indexing: Strings are indexed, and you can access individual characters using square brackets []. Indexing starts from 0.

Example:

word = "Python"
print(word[0])   # Output: P
print(word[-1])  # Output: n (negative index starts from the end)
  1. Slicing: You can extract a substring by using slicing with the syntax string[start:end].

Example:

word = "Python"
print(word[0:3])  # Output: Pyt (substring from index 0 to 2)

2.2.3.3 String Methods

Python provides several built-in methods to manipulate strings. Here are some commonly used string methods:

split(): Splits the string into a list of substrings based on a delimiter.

text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits)  # Output: ['apple', 'banana', 'cherry']

replace(): Replaces a substring with another substring.

text = "Hello, World!"
print(text.replace("World", "Python"))  # Output: Hello, Python!

strip(): Removes leading and trailing whitespace from the string.

text = "  Hello  "
print(text.strip())  # Output: "Hello"

upper(): Converts the string to uppercase.

print(text.upper())  # Output: HELLO

lower(): Converts the string to lowercase.

text = "Hello"
print(text.lower())  # Output: hello

2.2.3.4 Type Checking

You can verify that a variable is a string using the type() function.

Example:

name = "Alice"
print(type(name))  # Output: <class 'str'>

2.2.4 Type Conversion

Python allows you to convert between different data types using type conversion functions. For example, you can convert integers to floats, strings to integers, and so on.

2.2.4.1 Converting Integers to Floats

You can convert an integer to a float using the float() function.

Example:

x = 10
y = float(x)
print(y)  # Output: 10.0

2.2.4.2 Converting Floats to Integers

You can convert a float to an integer using the int() function. Note that this will truncate the decimal part, not round it.

Example:

pi = 3.14
x = int(pi)
print(x)  # Output: 3

2.2.4.3 Converting Strings to Integers/Floats

You can convert a numeric string to an integer or float using the int() or float() function. The string must represent a valid number, or it will raise a ValueError.

Example:

num_str = "100"
x = int(num_str)
print(x)  # Output: 100

float_str = "3.14"
y = float(float_str)
print(y)  # Output: 3.14

2.2.4.4 Converting Numbers to Strings

You can convert numbers to strings using the str() function.

Example:

x = 42
y = str(x)
print(y)  # Output: "42"

2.2.5 Summary

  • Integers: Whole numbers without a fractional component. Common operations include addition, subtraction, multiplication, and division.
  • **Floats

**: Numbers with a decimal point or in scientific notation. Floats allow for fractional values.

  • Strings: Sequences of characters used for text. Strings support various operations like concatenation, slicing, and built-in methods like upper(), lower(), and replace().
  • Type Conversion: Python allows converting between different data types using built-in functions like int(), float(), and str().

Understanding these basic data types is fundamental to working with more complex structures and operations in Python. In the next section, we will explore type conversion and more advanced operations on these data types.