Python • Syntax and Core Types

Python Types — Work with int, float, bool, and str types

Every piece of data in Python has a type that determines what you can do with it.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

When you write a program, you are telling a computer how to manipulate data—numbers, words, true-or-false decisions, and more. But computers store everything as binary ones and zeros. How does the machine know that the bits 01000001 represent the letter "A" rather than the number 65? The answer is data types. A type tells Python what kind of value it is working with so it can choose the right operations, catch mistakes, and use memory efficiently.

Programming languages have adopted different strategies for handling types over the decades. Some languages, like C and Java, require you to declare a variable's type before you use it. Python takes a different approach: it uses dynamic typing, meaning the interpreter figures out the type at runtime based on the value you assign. This makes Python code concise and beginner-friendly, but it also means you need to understand how types behave under the hood.

1950s • FORTRAN Introduces Numeric Types

FORTRAN, one of the earliest high-level languages, distinguished between INTEGER and REAL numbers, establishing the idea that programs must label their data.

1972 • C Language Formalizes Type Declarations

The C programming language required explicit type declarations such as int x = 5;, giving programmers fine-grained control over memory but increasing code verbosity.

1991 • Python 0.9 Released by Guido van Rossum

Python introduced dynamic typing: write x = 5 and the interpreter infers that x is an integer automatically.

2000 • Python 2 Adds Boolean Type

Python 2.3 introduced bool as a distinct type with values True and False, making conditional logic more readable.

2008 • Python 3 Unifies and Simplifies Types

Python 3 removed the old distinction between int and long, made all strings Unicode by default, and solidified the four core types students learn today.

Understanding the four core types—int, float, bool, and str—is the foundation for every Python program you will write. The central question of this lesson is: how do you choose the right type for your data, and what happens when you combine or convert between them?

SECTION 2

Core Principles & Definitions

Python's type system rests on a few key ideas. Every value you create—whether it is the number 42, the decimal 3.14, the truth value True, or the greeting "Hello"—is an object that carries a type tag. That tag determines which operations are valid. You can add two integers, but you cannot add an integer and a string without converting one of them first.

1

int — Whole Numbers

Integers represent whole numbers with no decimal point: 7, -3, 0. In Python 3, integers can be arbitrarily large—there is no overflow limit.
2

float — Decimal Numbers

Floats represent numbers with a decimal point: 3.14, -0.001, 2.0. They follow the IEEE 754 standard and have limited precision (~15–17 significant digits).
3

bool — True or False

Booleans have exactly two values: True and False. They are the backbone of if statements, loops, and logical operations.
4

str — Text Strings

Strings are sequences of characters enclosed in quotes: "hello" or 'world'. They support slicing, concatenation, and dozens of built-in methods like .upper().

A crucial concept is type conversion (also called casting). Python sometimes converts types automatically—for instance, 3 + 2.5 promotes the integer 3 to the float 3.0 before adding. This is called implicit conversion. Other times you must convert explicitly, like writing int("42") to turn a string into an integer. That is explicit conversion.

✦

KEY TAKEAWAY

Think of types like containers in a kitchen. A measuring cup (float) handles liquids with precision, a counting jar (int) tracks whole items, a label maker (str) stores text, and a light switch (bool) is either on or off. Using the wrong container leads to messy results—just like using the wrong type leads to bugs in your code.

SECTION 3

Visual Explanation — The Four Core Types

Python's Four Core Data TypesintWhole numbers42 -7 0No decimal pointUnlimited precisiontype(42) → <class 'int'>floatDecimal numbers3.14 -0.5 2.0Has a decimal point~15 digits of precisiontype(3.14) → <class 'float'>boolTrue or FalseTrue FalseSubclass of intTrue == 1, False == 0type(True) → <class 'bool'>strText strings"hello" 'Python'Sequence of charactersImmutable (cannot change in place)type("hi") → <class 'str'>
The four core Python types, each shown with example values and the result of calling type() on a sample value. Notice that bool is actually a subclass of int—a fact that surprises many beginners.

The diagram above organizes the four types into a visual grid. On the left column you see the numeric and logical types (int and bool), and on the right you see float and str. You can always check a value's type by passing it to the built-in type() function. For example, type(3.14) returns <class 'float'>. This is your go-to debugging tool whenever you are unsure what type a variable holds.

SECTION 4

How Types Work — Operations & Conversions

Each type supports a specific set of operations. Integers and floats support arithmetic: +, -, *, /, // (floor division), % (modulo), and ** (exponentiation). Booleans support logical operators: and, or, and not. Strings support concatenation (+), repetition (*), and indexing (s[0]).

Arithmetic Rules for int and float

INT DIVISION vs FLOAT DIVISION

7/2→3.5(float)∣7//2→3(int)7 / 2 → 3.5 (float) | 7 // 2 → 3 (int)

The / operator always returns a float, even if both operands are integers. Use // for integer (floor) division.

MODULO OPERATOR

77 % 2 → 1

The modulo operator % returns the remainder after division. It is commonly used to check if a number is even (n % 2 == 0) or to wrap values around a range.

IMPLICIT CONVERSION RULE

int+float→float∣bool+int→intint + float → float | bool + int → int

When you mix types in arithmetic, Python widens the narrower type. bool → int → float. Strings are never implicitly converted to numbers—you must use int() or float() explicitly.

Explicit Conversion (Casting) Functions

FunctionExampleResult
int()int("42")42
int()int(3.9)3 (truncates, does not round)
float()float(7)7.0
str()str(3.14)"3.14"
bool()bool(0)False (0, 0.0, "", and None are falsy)

Common type conversion functions and their behavior

⚠

Watch Out: String + Number

Writing "Age: " + 17 causes a TypeError. Python refuses to guess whether you want "Age: 17" or something else. Fix it with "Age: " + str(17) or use an f-string: f"Age: {17}".

SECTION 5

Detailed Breakdown — Each Type Up Close

Type Conversion FlowchartArrows show the direction of implicit (automatic) wideningboolTrue / Falseint42, -7, 0float3.14, -0.5autoautostr"hello"str(x)explicitstr(x)str(x)int(s)Implicit Widening: bool → int → float | str requires explicit conversionSolid arrow = implicit (automatic)Dashed arrow = explicit (you must cast)
This flowchart shows the type hierarchy. Solid arrows indicate implicit (automatic) widening: Python will promote bool → int → float without your intervention. Dashed arrows show conversions to and from str that you must request explicitly using casting functions.

int — Integers in Depth

Python integers have arbitrary precision, meaning they can grow as large as your computer's memory allows. In many other languages, an integer overflows after reaching a fixed limit (like 2³¹ − 1 in Java), but Python quietly allocates more memory as needed. You can write 2 ** 1000 and Python will compute the entire 302-digit result without error.

float — Floating-Point Numbers in Depth

Floats follow the IEEE 754 double-precision standard, which uses 64 bits to store a number. This gives about 15–17 significant decimal digits of precision. However, some simple decimals cannot be represented exactly in binary. For example, 0.1 + 0.2 evaluates to 0.30000000000000004 rather than 0.3. This is not a bug—it is an inherent limitation of floating-point arithmetic that affects virtually every programming language.

bool — Booleans in Depth

In Python, bool is technically a subclass of int. This means True behaves like 1 and False behaves like 0 in arithmetic contexts. Writing True + True gives 2, and sum([True, False, True, True]) gives 3—a handy trick for counting how many items satisfy a condition.

str — Strings in Depth

Strings in Python 3 are sequences of Unicode characters, which means they can represent text in any language—English, Japanese, Arabic, emoji, and more. Strings are immutable: once created, the characters inside cannot be changed. Operations like .upper() or .replace() return a new string rather than modifying the original. You can access individual characters by index ("Python"[0] gives "P") and extract substrings using slicing ("Python"[0:3] gives "Pyt").

SECTION 6

Worked Example — Building a Temperature Converter

Let's build a small program that reads a temperature in Fahrenheit from the user, converts it to Celsius, and prints a formatted message. This exercise will require us to use all four core types: str (user input), float (the converted temperature), int (rounding), and bool (checking if water freezes).

Fahrenheit to Celsius Converter

  1. 1

    Step 1 — Get User Input (str)

    The input() function always returns a string, even if the user types a number. We store the raw input: user_input = input("Enter temp in °F: ") If the user types 72, then user_input is the string "72", not the number 72.
    user_input = "72" (type: str)
  2. 2

    Step 2 — Convert to float (Explicit Casting)

    We must cast the string to a numeric type before doing math: fahrenheit = float(user_input) Now fahrenheit holds the float value 72.0. We chose float instead of int because the user might enter a decimal like 98.6.
    fahrenheit = 72.0 (type: float)
  3. 3

    Step 3 — Compute Celsius (float Arithmetic)

    Apply the conversion formula: celsius = (fahrenheit - 32) * 5 / 9 Python evaluates (72.0 - 32) * 5 / 9 = 40.0 * 5 / 9 = 200.0 / 9 ≈ 22.222222222222221.
    celsius ≈ 22.222222222222221 (type: float)
  4. 4

    Step 4 — Round to int

    For a cleaner display, we round and convert to an integer: celsius_rounded = int(round(celsius)) The round() function returns 22 (an int when called with one argument and the result is whole), and int() ensures the type.
    celsius_rounded = 22 (type: int)
  5. 5

    Step 5 — Check Freezing (bool)

    We use a comparison to produce a boolean: is_freezing = celsius <= 0 Since 22.22 is not ≤ 0, is_freezing is False.
    is_freezing = False (type: bool)
  6. 6

    Step 6 — Print the Result (str Formatting)

    We use an f-string to build the output message: print(f"{fahrenheit}°F = {celsius_rounded}°C. Freezing? {is_freezing}") Inside the curly braces, Python automatically calls str() on each value to embed it in the string.
    72.0°F = 22°C. Freezing? False

SECTION 7

Strengths & Pitfalls of Each Type

Each type excels in certain situations and can trip you up in others. The table below summarizes common strengths and pitfalls you should watch out for as you write Python programs.

TypeStrengthsCommon Pitfalls
intExact arithmetic, unlimited size, great for counters, indices, and IDsDivision with / always returns a float; int(3.9) truncates to 3, not 4
floatHandles decimals and scientific notation, essential for math/science calculationsRounding errors (0.1 + 0.2 ≠ 0.3); avoid using == to compare floats directly
boolClean conditional logic, can count True values with sum()Many values are "truthy" or "falsy" (e.g., 0, empty string, None are all False), which can cause unexpected behavior
strRich built-in methods, Unicode support, f-string formattingImmutable—cannot change characters in place; concatenating in a loop is slow for large data; "5" + "3" gives "53" not 8

Strengths and pitfalls of Python's four core types

✦

KEY TAKEAWAY

Think of type errors like plugging a USB-C cable into an HDMI port—the shapes don't match, even though both carry data. Python's type system is your adapter: int(), float(), str(), and bool() are the converters that reshape data so it fits where you need it.

SECTION 8

Connection to Advanced Concepts

The four core types you have learned are just the beginning. As you progress in Python, you will encounter collection types like list, dict, tuple, and set that group multiple values together. You will also meet type hints (introduced in Python 3.5), which let you annotate your code with expected types to catch bugs before your program even runs.

Core Concept (This Lesson)Advanced Extension
int for whole numbersdecimal.Decimal for exact decimal arithmetic (e.g., financial applications)
float for approximate decimalscomplex type for complex numbers (3 + 4j)
bool for True/FalseCustom __bool__() method to define truthiness for your own classes
str for textbytes and bytearray for raw binary data, encoding, and network protocols
Dynamic typing (no declarations)Type hints (x: int = 5) plus tools like mypy for static analysis

How core types connect to advanced Python features

Mastering int, float, bool, and str gives you a rock-solid foundation. Every data structure and every library you will use in the future ultimately stores and manipulates these primitive types. When you understand how they behave and how to convert between them, debugging becomes far easier and your code becomes more reliable.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

What is the difference between the integer 5 and the string "5" in Python? Why does 5 + 5 produce 10 while "5" + "5" produces "55"?
Show answer
The integer 5 is a numeric value stored as type int, and the + operator performs arithmetic addition, yielding 10. The string "5" is a single-character text value stored as type str, and the + operator performs string concatenation, gluing the two characters together to produce "55". The same operator (+) behaves differently depending on the types of its operands. This is why understanding types is essential—it determines what each operation actually does.

Question 2: BASIC CALCULATION

Predict the output and resulting type of each expression: (a) 10 / 3 (b) 10 // 3 (c) 10 % 3 (d) float(10)
Show answer
(a) 10 / 3 produces 3.3333333333333335 (type float), because the / operator always returns a float. (b) 10 // 3 produces 3 (type int), which is the floor (rounded down) result of dividing 10 by 3. (c) 10 % 3 produces 1 (type int), which is the remainder after dividing 10 by 3. (d) float(10) produces 10.0 (type float), an explicit conversion from int to float.

Question 3: INTERMEDIATE

A user enters their birth year as input: birth_year = input("Year born: "). Write Python code that calculates their age (assume the current year is 2025) and prints "You are X years old." Explain which type conversions are needed and why.
Show answer
The code would be: birth_year = input("Year born: ") followed by age = 2025 - int(birth_year) and then print(f"You are {age} years old."). The input() function returns a string, so we must cast to int before subtracting. We use int() rather than float() because years are whole numbers. The f-string automatically calls str() on age to embed it in the output message.

Question 4: APPLIED

You are writing a program for a school store. The price of an item is 4.99 and the quantity is 3. Write code that: (a) computes the total cost, (b) checks whether the customer gets a discount (total > $10), and (c) prints a receipt string like "Total: $14.97 | Discount: True". Identify the type of each variable.
Show answer
The code: price = 4.99 (float), quantity = 3 (int), total = price * quantity (float, because int × float → float, yielding 14.97), gets_discount = total > 10 (bool, evaluates to True since 14.97 > 10), and print(f"Total: ${total} | Discount: {gets_discount}") (str output). This problem exercises implicit conversion (int to float in multiplication), comparison producing a bool, and f-string formatting converting all types to str for display.

Question 5: CRITICAL THINKING

Explain why 0.1 + 0.2 == 0.3 evaluates to False in Python. Then propose two different strategies a programmer could use to correctly compare floating-point numbers for near-equality. Discuss the trade-offs of each approach.
Show answer
Floating-point numbers are stored in binary (base 2), and the decimal value 0.1 cannot be represented exactly in binary, just as 1/3 cannot be represented exactly in decimal. The stored value of 0.1 + 0.2 is approximately 0.30000000000000004, which is not equal to 0.3. Strategy 1: Use a tolerance comparison like abs(a - b) < 1e-9. This is simple and widely used, but you must choose an appropriate epsilon value for your application—too small and it still fails, too large and it considers genuinely different numbers as equal. Strategy 2: Use Python's math.isclose(a, b) function, which handles both relative and absolute tolerances automatically. This is more robust and readable but requires importing the math module. A third option for financial calculations is to use the decimal.Decimal type, which avoids binary representation issues entirely but is slower for large-scale computation.

SUMMARY

Lesson Summary

Summary

Python provides four core data types that form the foundation of every program. The int type stores whole numbers with unlimited precision and supports arithmetic operations including floor division (//) and modulo (%). The float type handles decimal numbers using IEEE 754 double-precision but comes with inherent rounding limitations. The bool type represents True and False and is a subclass of int. The str type stores immutable sequences of Unicode characters.

Python uses dynamic typing, inferring types at runtime, and supports both implicit conversion (automatic widening from bool → int → float) and explicit conversion using casting functions like int(), float(), str(), and bool(). Use the type() function to check any value's type, and always remember that input() returns a string that must be explicitly converted before performing arithmetic.

Varsity Tutors • Python • Python Types — Work with int, float, bool, and str types