Menu

Basic Data Types

Introduction

Python is a dynamically typed language, meaning you don't need to declare variable types explicitly. We'll start with Python's core data types: integers, floats, strings, booleans, and None.

Numbers

Python handles numbers intuitively:

# Integers
10 + 5    # 15
10 - 3    # 7
4 * 3     # 12
10 / 3    # 3.3333 (always returns float)
10 // 3   # 3 (floor division)
10 % 3    # 1 (modulus)
2 ** 8    # 256 (exponent)

Unlike some languages, Python's division operator / always returns a float. Use // for integer (floor) division.

Strings

Strings in Python can be created with single quotes, double quotes, or triple quotes for multi-line strings:

name = "SaneGenius"
greeting = 'Hello, World!'
multiline = """This is
a multi-line
string."""

# String formatting (f-strings - the modern way)
print(f"Welcome to {name}!")  # "Welcome to SaneGenius!"

# Common string methods
"hello".upper()       # "HELLO"
"HELLO".lower()       # "hello"
"hello world".title() # "Hello World"
"  hello  ".strip()   # "hello"
"hello".replace("l", "r")  # "herro"
len("hello")          # 5

Booleans and None

Booleans in Python are True and False (capitalized). None represents the absence of a value, similar to null in other languages.

is_active = True
is_deleted = False
result = None

# Falsy values in Python:
# False, 0, 0.0, "", [], {}, set(), None
bool(0)    # False
bool("")   # False
bool([])   # False
bool(42)   # True
bool("hi") # True

Type conversion

int("42")     # 42
float("3.14") # 3.14
str(42)       # "42"
bool(1)       # True
type(42)      # <class 'int'>

Assignment

  1. Read the Python tutorial on numbers and strings.
  2. Experiment with each data type in the Python REPL (just type python3 in your terminal).
  3. Practice string formatting with f-strings.

Knowledge check

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!