ASAmol Shukla
Projects
Courses
Prompts
Skills
Contact
Resume
Course Outline
Syllabus Overview

Complete Python Course: From Zero to Professional

Courses/Complete Python Course: From Zero to Professional/Lesson 2: Variables, Data Types & Input/Output
35 mins lesson duration•7 mins read

Lesson 2: Variables, Data Types & Input/Output

The five core data types (int, float, str, bool, None), dynamic typing, type casting, memory references, and reading standard input.

What is a Variable?

A variable is a named label that points to a value stored in memory. Think of it as a sticky note attached to a box: the note has a name (like age), and the box holds a value (like 24). You can move the note to a different box anytime — that is called reassignment.

Variables are how programs remember things. Without them, every calculation would be lost the moment it finishes. Almost everything you write from here on revolves around creating, reading, and updating variables.

What You'll Learn in This Lesson

  • Meet the five core data types: int, float, str, bool, and None
  • Create and reuse variables with proper naming rules
  • Understand Python's dynamic typing and the type() function
  • Read input from the user with input()
  • Cast values between types with int(), float(), and str()
  • Understand how variables reference objects in memory

Dynamic Typing in Python

Python is a dynamically typed language. This means:

  • You do not declare a variable's type — you just assign a value.
  • A variable can hold a number now and a string later.
  • The type is a property of the value, not the variable name.
label = 100          # label points to an integer
print(type(label))   # <class 'int'>
label = "text"       # now label points to a string
print(type(label))   # <class 'str'>

Use the built-in type() function as a spyglass to check what kind of object a variable really holds. It is invaluable for debugging — when something misbehaves, the first question is almost always "what type is this, really?"

Memory References — What Really Happens

When you write x = 10, Python allocates an integer object in memory and points the label x at it. If you then write x = "hello", the label is simply pointed at a new string object. The old integer is now unreachable, and Python's garbage collector automatically reclaims it.

Mental model: variables are never boxes that "contain" values — they are name-tags tied to objects. Reassignment just moves the tag.

This model explains a lot of Python's behavior, including the alias traps you will meet in Lesson 11. For now, just remember: x = value creates or moves a tag; it never copies the value.


The Core Data Types — Your Building Blocks

Every value in Python has a type, and almost every program you write is built from just five core types:

Type Keyword What it holds Examples
Integer int Whole numbers (no decimal point) 42, -7, 0
Float float Numbers with a decimal point 3.14, -0.5, 2.0
String str Text — a sequence of characters "hello", 'AI', "2026"
Boolean bool Logical truth values True, False
None NoneType "Nothing here" — exactly one special value None
age = 25          # int
price = 9.99      # float
name = "Amol"     # str
is_student = True # bool
result = None     # NoneType

Each type has superpowers (and quirks) worth knowing:

  • int — unlimited size. Python integers never overflow. 10 ** 100 returns a 101-digit number instantly — languages like C or Java would crash with an overflow error.
  • float — decimals, with a tiny catch. Floats are stored in binary, so some decimals are only approximately exact:
    print(0.1 + 0.2)   # 0.30000000000000004  (not 0.3!)
    
    This is not a Python bug — it happens in every programming language. When exact decimals matter (like money), use the Decimal module (covered later in the course).
  • bool — booleans are secretly integers. True equals 1 and False equals 0:
    print(True + True)   # 2
    print(True == 1)     # True
    
  • None — the special "nothing" value. Use None when a variable has no value yet. It has its own type NoneType and exactly one value:
    result = None
    print(type(result))   # <class 'NoneType'>
    

type() vs isinstance() — Two Ways to Ask "What Type?"

Function Asks Best for
type(value) "What is the exact type?" Quick inspection and debugging
isinstance(value, Type) "Is this value of Type (or a subclass)?" Real checks in your code
print(type(42))                  # <class 'int'>
print(isinstance(3.5, float))    # True
print(isinstance(42, int))       # True

Use isinstance() in real code — it understands inheritance (e.g., bool is a subclass of int, so isinstance(True, int) is True).


Naming Rules (Non-Negotiable)

Rule Example
Start with a letter or underscore name, _count
Use letters, digits, underscores after the first char user_age2
Case matters: Age and age are different —
Cannot use Python keywords if, for, class are reserved
Convention: snake_case for variables total_price, user_name

Python keywords you can never use as names include: if, else, for, while, def, class, return, import, from, not, and, or, True, False, None, in, is, lambda, pass, break, continue, and more. Type help("keywords") in the REPL to see the full list.

Meaningful names matter. user_age is better than ua; final_price_with_tax beats fpwt. You read code far more often than you write it — name things for the future reader (which is usually you, six weeks later).


Reading User Input — The input() Function

Use input() to read a line of text typed by the user:

name = input("What is your name? ")
print("Nice to meet you,", name)

Critical rule: input() always returns a string, even if the user types a number. If you try to do math with it directly, you get a TypeError:

age = input("Age: ")     # user types 25
print(age + 1)           # TypeError: can only concatenate str

The prompt string inside input("...") is shown to the user but is not part of the returned value. Every interactive program — games, calculators, logins, menu systems — is built on this one function.


Type Casting — Converting Between Types

Casting changes the type of a value. The three casts you will use constantly:

Function Converts to Example
int(value) Integer int("24") → 24
float(value) Float float("3.5") → 3.5
str(value) String str(100) → "100"

The standard pattern for reading numbers is input, then cast:

age = int(input("Your age: "))     # "25" -> 25
price = float(input("Price: "))    # "9.99" -> 9.99

If the user types something that cannot be converted (like "abc"), Python raises a ValueError. We will learn how to catch these errors gracefully in Lesson 21.

Casting gotchas:

  • int("3.5") fails (ValueError) — a float string needs float() first, then int(): int(float("3.5")) → 3.
  • int(3.99) truncates toward zero → 3 (it does not round).
  • bool("False") is True — any non-empty string is truthy (Lesson 5).

Comparison: Dynamic vs Static Typing

Aspect Python (dynamic) C / Java / TypeScript (static)
Type declaration Not needed Required
Reassign to new type Allowed Not allowed
Catch type bugs At runtime At compile time
Beginner friendliness High Lower

Common Mistakes to Avoid

  • Mistake: Doing math on input() results directly — Fix: cast with int() or float() first.
  • Mistake: Expecting 0.1 + 0.2 to equal 0.3 exactly — Fix: floats are approximate; use round() for display or Decimal when exactness matters.
  • Mistake: Using reserved words or invalid characters in names (2nd_year, my-name) — Fix: use second_year, my_name.
  • Mistake: Thinking age = "25" makes age a number — Fix: check with type(age); it is a string until you cast it.
  • Mistake: Forgetting input() returns a string even for numbers — Fix: always cast: int(input(...)).
  • Mistake: Using int(3.99) expecting rounding — Fix: use round(3.99) for rounding; int() truncates.

Professional Tips & Tricks

  • input() always returns a string — convert before doing math, or you will get a TypeError.
  • Use f-strings (f"...{var}...") instead of messy + concatenation (full power in Lesson 3).
  • Give variables meaningful names: user_age beats ua.
  • Use type() liberally while debugging — "what type is this, really?" solves most puzzles.

Key Takeaways

  • The five core data types are int, float, str, bool, and None.
  • Variables are name-tags pointing to objects in memory; Python uses dynamic typing.
  • input() reads text and always returns a string.
  • Cast values with int(), float(), and str().
  • type() is your debugging spyglass.
  • Follow snake_case naming and avoid Python keywords.

Next up: Strings — slicing, methods, and the modern f-string formatting.

Interactive Lesson Code Snippet
# The five core data types
age = 25            # int
price = 9.99        # float
name = "Amol"       # str
is_student = True   # bool
result = None       # NoneType

print("Core data types:")
print(type(age), type(price), type(name), type(is_student), type(result))
print("Float gotcha: 0.1 + 0.2 =", 0.1 + 0.2)
print("Booleans are ints: True + True =", True + True)

# Variables and casting demonstration
age_str = "24"  # String representation
print("Type before casting:", type(age_str))

# Cast string to integer to perform math addition
age_int = int(age_str)
next_year_age = age_int + 1
print("Type after casting:", type(age_int))
print(f"Age next year: {next_year_age}")

# Dynamic type swap
label = 100
print("Label type:", type(label))
label = "Dynamic Label Swapped"
print("Label new type:", type(label))

# Read user input (always returns a string)
name = input("What is your name? ")
print("Nice to meet you,", name)
Language: python

Lesson Code (Python)

# The five core data types
age = 25            # int
price = 9.99        # float
name = "Amol"       # str
is_student = True   # bool
result = None       # NoneType

print("Core data types:")
print(type(age), type(price), type(name), type(is_student), type(result))
print("Float gotcha: 0.1 + 0.2 =", 0.1 + 0.2)
print("Booleans are ints: True + True =", True + True)

# Variables and casting demonstration
age_str = "24"  # String representation
print("Type before casting:", type(age_str))

# Cast string to integer to perform math addition
age_int = int(age_str)
next_year_age = age_int + 1
print("Type after casting:", type(age_int))
print(f"Age next year: {next_year_age}")

# Dynamic type swap
label = 100
print("Label type:", type(label))
label = "Dynamic Label Swapped"
print("Label new type:", type(label))

# Read user input (always returns a string)
name = input("What is your name? ")
print("Nice to meet you,", name)

Console Output

Core data types:
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
Float gotcha: 0.1 + 0.2 = 0.30000000000000004
Booleans are ints: True + True = 2
Type before casting: <class 'str'>
Type after casting: <class 'int'>
Age next year: 25
Label type: <class 'int'>
Label new type: <class 'str'>
What is your name? Amol
Nice to meet you, Amol

Code Visualization Tips

  • 🧠Picture variables as name-tags tied to boxes in memory — reassigning points the tag at a different box.
  • 🧠Label each box in your memory diagram with its type (int, float, str, bool, None) — you will see the five core data types at a glance.
  • 🧠Use type() as a spyglass to check what kind of object a variable really holds.
  • 🧠Draw a small arrow diagram: age -> "24" (str), then age -> 24 (int).

Professional Tips & Tricks

  • ⚡input() always returns a string — convert before doing math, or you will get a TypeError.
  • ⚡Use f-strings (f"...{var}...") instead of messy + concatenation.
  • ⚡Give variables meaningful names: user_age beats ua.

Python Code Judge & Practice Arena

LeetCode Style

Run real Python 3.12 WebAssembly code directly in your browser against automated test suites.

Solved:0 / 6
0 / 110 XP
Challenges:
Problem 1 of 6

Core Data Types & Identity Inspector

Easy+10 XP
Create five variables — one int, one float, one str, one bool, and one None — then print the value, type, and memory id of each.
main.pyPython 3.12 (WASM)
1
2
3
4
5
6
7
8
9
10
11
12
Press Run Code to test or Submit to verify test cases

Test Your Knowledge

Instant feedback

Quick Check: Lesson 2: Variables & Basic I/O

1 / 20
What is the output of the following code? x = '5' y = 10 print(int(x) + y)

Up next · Continue learning

Strings — Slicing, Methods & f-Strings

String indexing and slicing, powerful string methods, and modern formatted strings.

8 mins read40 mins
Start next lesson
Previous: Hello, Python! Setup & Your First ProgramNext: Strings — Slicing, Methods & f-Strings
Made withbyAmol Shukla·amolshukla.online
ASAmol Shukla

AI Developer, Trainer & Agentic AI Expert building practical learning systems and real-world AI applications.

Explore

  • Projects
  • Courses
  • Prompts
  • Skills
  • Contact
  • Experience
  • Blogs

Connect

  • Resume
  • Contact
© 2026 Amol Shukla·Created withbyamolshukla.online
Back to top