Chapter 2

Python Basics

FREE Variables and Data Types
Article Β· 25 min
πŸ“ Homework 8

2.1.1 What is a Variable?

Think of a variable as a labeled box where you store a piece of data. You give the box a name (the label), and Python remembers what's inside. Whenever you need that data, you just refer to the label.

πŸ’‘ Memory Hook: A variable is like a locker at a train station. You put your luggage inside (the data), label it with a name (the variable name), and when you come back and say the name, the locker opens and your luggage is still there.

In Python, creating a variable is as simple as picking a name and using the assignment operator =:

name = "Alice"        # String variable
age = 15              # Integer variable
height = 1.68         # Float variable
is_student = True     # Boolean variable

The = sign doesn't mean "equals" like in math. It means "assign the value on the right to the name on the left". Read it as: "name gets the value 'Alice'".

1
Practice 1
✏️ Try it yourself!
1 Code
Create a variable called favourite_game and assign it a string value of your favourite computer game. Then create a variable hours_played and assign it an integer (how many hours you've played it).
2 Code
Create a variable price and assign it the float value 29.99. Then create a variable is_on_sale and assign it False.

2.1.2 Python's Basic Data Types

Every value in Python has a type. Python has four fundamental data types that you'll use all the time:

Type Name Examples Analogy 🧠
str String (text) "Hello", 'Python' πŸ“ A sentence you write on a sticky note
int Integer (whole number) 42, -7, 0, 1000000 πŸ”’ Counting apples β€” no halves allowed
float Float (decimal number) 3.14, -0.5, 99.99 πŸ“ A ruler measurement with precision
bool Boolean (True/False) True, False πŸ’‘ A light switch β€” only ON or OFF

πŸ”€ Strings (str)

Strings hold text. They're created by wrapping characters in quotes β€” either single ' ' or double " ".

greeting = "Hello, World!"
name = 'Alice'
empty_string = ""
πŸ’‘ Key Point: Python doesn't care if you use single or double quotes β€” just be consistent. If your text contains an apostrophe (like "it's"), using double quotes on the outside avoids errors.

πŸ”’ Integers (int)

Integers are whole numbers β€” positive, negative, or zero. No decimal point allowed!

score = 95
temperature = -3
population = 8_000_000_000  # Underscores make large numbers readable!
πŸ’‘ Pro Tip: You can use underscores _ to separate groups of digits in large numbers. Python ignores them: 1_000_000 is the same as 1000000.

πŸ“ Floats (float)

Floats represent decimal numbers. Use them when you need precision, like measurements or money.

pi = 3.14159
gpa = 3.75
price = 19.99
temperature = 36.6

βœ… Booleans (bool)

Booleans have only two possible values: True or False. They're perfect for yes/no questions.

is_raining = True
has_passed = False
is_enrolled = True

Note: In Python, True and False must be capitalized!

2
Practice 2
✏️ Try it yourself!
1 Code
Create four variables β€” one of each type: str, int, float, bool. Use meaningful names and values related to a school subject you enjoy.
2 Code
What happens if you write true (lowercase) instead of True? Try it mentally β€” would Python understand it?

2.1.3 Checking Types with type()

Python provides a built-in function called type() that tells you the data type of any value. This is extremely useful when you're debugging or unsure what type a variable holds:

name = "Alice"
age = 15
gpa = 3.8
passed = True

print(type(name))    # 
print(type(age))     # 
print(type(gpa))     # 
print(type(passed))  # 
πŸ’‘ Memory Hook: Think of type() as a scanner β€” hold it up to any value and it prints a label saying what kind of data it is, like scanning a barcode at the supermarket.
3
Practice 3
✏️ Try it yourself!
1 Code
What would type("42") return? (Think carefully β€” the quotes make a difference!)
2 Code
What would type(3.0) return? Is 3.0 an integer or a float?

2.1.4 Variable Naming Rules

Python has strict rules about what makes a valid variable name. Follow these to avoid errors:

Rule Example Valid?
Start with letter or underscore my_var, _count βœ…
Cannot start with a digit 1st_place ❌
Letters, numbers, underscores only my-var, my$var ❌
Case-sensitive score β‰  Score β‰  SCORE ⚠️ Different!
Cannot use Python keywords if, for, while, class ❌

Python Keywords to Avoid

These words have special meanings in Python and can't be used as variable names:

and     as      assert  break   class   continue  def
del     elif    else    except  finally  for      from
global  if      import  in      is      lambda    not
or      pass    raise   return  try     while     with
yield

Best Practice: Snake Case

Python programmers follow a naming convention called snake_case β€” all lowercase letters with underscores between words:

student_name       # βœ… Good: clear and readable
age_of_student     # βœ… Good: descriptive
total_score        # βœ… Good: follows convention
a                  # ❌ Too vague β€” what does it mean?
x1y2               # ❌ Meaningless β€” no context
studentName        # ⚠️ camelCase β€” JavaScript style, not Python!
πŸ’‘ Rule of Thumb: A good variable name tells you what the data represents without reading a comment. temperature_in_celsius is better than t or temp.
4
Practice 4
✏️ Try it yourself!
1 Code
Which of these variable names are valid in Python? For invalid ones, explain why: 2fast, fast_2, my-name, my_name, class, Class, _private, total$
2 Code
Rewrite these bad variable names using proper snake_case: m, StudentGrade, numberofstudentsinclass

2.1.5 Dynamic Typing β€” The Python Superpower

Unlike many other programming languages, Python is dynamically typed. This means:

  • βœ… You don't need to declare the type β€” just assign a value
  • βœ… A variable can change its type if you assign a new value of a different type
x = 10           # x is an integer
print(type(x))   # 

x = "Hello"      # Now x is a string!
print(type(x))   # 

x = 3.14         # Now x is a float!
print(type(x))   # 
πŸ’‘ Memory Hook: Think of a variable as a chameleon β€” it changes its "colour" (type) based on what you put into it. In statically-typed languages like Java, a box can only hold one type forever. In Python, the box adapts!
Feature Static Typing (Java, C++) Dynamic Typing (Python)
Declaration Must specify type: int x = 5; Just assign: x = 5
Flexibility Strict β€” can't reassign different type Flexible β€” type changes on reassignment
Learning curve More code, more concepts upfront Less code, easier to get started
Error catching Catches type errors at compile time Catches type errors at runtime
🦎
Dynamic Typing
"The Chameleon"

🧱 Analogy: Python variables are like a chameleon that changes colour depending on what it sits on. Put an integer on it β†’ it looks like an integer. Put a string on it β†’ it becomes a string!

πŸ“Œ Definition: Dynamic typing means the type of a variable is determined at runtime based on the value assigned, and the same variable can hold values of different types during its lifetime.

5
Practice 5
✏️ Try it yourself!
1 Code
What will Python display when you run this code?
value = 100
print(type(value))
value = "one hundred"
print(type(value))
value = 100.0
print(type(value))
Explain what happens at each step.
2 Code
True or False: In Python, once a variable is declared as an integer, it can never hold a string value.

2.1.6 Type Conversion (Casting)

Sometimes you need to convert a value from one type to another. Python provides built-in functions for this:

# Convert to string
age = 15
message = "You are " + str(age) + " years old"
print(message)  # You are 15 years old

# Convert to integer
price_str = "29"
price_int = int(price_str)
print(price_int + 1)  # 30

# Convert to float
whole = 10
decimal = float(whole)
print(decimal)  # 10.0

# Boolean conversion
print(bool(1))    # True (any non-zero number is True)
print(bool(0))    # False (zero is False)
print(bool(""))   # False (empty string is False)
print(bool("Hi")) # True (non-empty string is True)
⚠️ Watch Out! Not all conversions are valid. int("hello") will cause an error β€” Python can't turn the word "hello" into a number!
6
Practice 6
✏️ Try it yourself!
1 Code
Write code that converts the string "3.14159" to a float, then multiplies it by 2, and prints the result.
2 Code
What happens when you run int("3.9")? Will it round up to 4, cause an error, or truncate to 3?
3 Code
Convert the integer 99 to a string, then concatenate it with " percent" and print the result.

πŸ“‹ Section 2.1 Summary Checklist

☐ I can explain what a variable is using the locker analogy
☐ I know the 4 basic data types: str, int, float, bool
☐ I can use type() to check any value's type
☐ I know Python's variable naming rules and snake_case
☐ I understand dynamic typing (the "chameleon")
☐ I can convert between types using str(), int(), float(), bool()
☐ I know which Python keywords cannot be used as variable names
FREE Strings and Print Statements
Article Β· 25 min
πŸ“ Homework

2.2.1 Creating Strings

In Python, a string is a sequence of characters enclosed in quotes. Strings are everywhere in programming β€” names, messages, passwords, file paths, and even the HTML code of websites.

πŸ’‘ Memory Hook: A string is like a string of beads β€” each character is a bead, and the quotes are the knot at each end holding them all together. "Hello" = H-e-l-l-o beads on a string!
Method Example When to Use
Single quotes 'Hello' When the string contains double quotes like 'He said "hi"'
Double quotes "Hello" When the string contains apostrophes like "It's great!"
Triple quotes '''Multi-line''' Long text that spans multiple lines, or docstrings

Single vs Double Quotes

Python treats both identically. The key is consistency β€” pick one style and stick with it!

# Single quotes
name = 'Alice'
greeting = 'Hello, World!'

# Double quotes
name = "Alice"
greeting = "Hello, World!"

# Choosing quotes to avoid escaping:
sentence1 = "It's a beautiful day"     # βœ… Double quotes = no escape needed for '
sentence2 = 'He said "Python is fun"'  # βœ… Single quotes = no escape needed for "

Multi-line Strings with Triple Quotes

For strings that span multiple lines, use triple quotes (''' or """):

poem = '''Roses are red,
Violets are blue,
Python is awesome,
And so are you!'''

print(poem)
# Output:
# Roses are red,
# Violets are blue,
# Python is awesome,
# And so are you!
1
Practice 1
✏️ Try it yourself!
1 Code
Create a string variable called favourite_quote that holds a famous quote containing an apostrophe (like "Python's readability is its strength"). Choose your quotes wisely to avoid escaping!
2 Code
Write a multi-line string that contains your name, age, and favourite hobby β€” each on a separate line β€” and print it.

2.2.2 String Concatenation & Repetition

πŸ”— Concatenation with +

The + operator joins strings together. This is called concatenation:

first = "Python"
second = "Rocks"
result = first + " " + second
print(result)  # Python Rocks

# Concatenating multiple strings
full_name = "Alice" + " " + "Smith"
print(full_name)  # Alice Smith
⚠️ Common Mistake: You cannot concatenate a string with a number directly! "Age: " + 15 causes an error. Use str(15) to convert first: "Age: " + str(15).

πŸ” Repetition with *

The * operator repeats a string a given number of times:

print("Ha" * 3)       # HaHaHa
print("-" * 20)        # --------------------
print("🐍" * 5)        # 🐍🐍🐍🐍🐍

# Great for creating visual separators!
separator = "=" * 30
print(separator)
print("WELCOME TO PYTHON")
print(separator)
πŸ’‘ Pro Tip: String repetition is perfect for drawing lines, borders, and simple ASCII art in the console.
2
Practice 2
✏️ Try it yourself!
1 Code
Create an email variable by concatenating "alice", "@", "example", ".", and "com". Print the result.
2 Code
Use string repetition to print a pattern like this (use * and " " creatively):
*
**
***
****
*****
Hint: You'll need a separate print for each line.

2.2.3 Essential String Methods

Python strings come with many built-in methods that let you manipulate text. Here are the most important ones for beginners:

Method What It Does Example Result
.upper() Convert to UPPERCASE "hello".upper() HELLO
.lower() Convert to lowercase "HELLO".lower() hello
.strip() Remove leading/trailing spaces " hi ".strip() hi
len() Get string length (it's a function!) len("Hello") 5
.replace() Replace part of a string "Hi there".replace("Hi","Bye") Bye there
.find() Find position of a substring "Python".find("th") 1
.count() Count occurrences "banana".count("a") 3
.capitalize() Capitalize first letter "python".capitalize() Python

Seeing Them in Action

text = "  Hello, Python!  "

print(text.upper())                    # "  HELLO, PYTHON!  "
print(text.lower())                    # "  hello, python!  "
print(text.strip())                    # "Hello, Python!"
print(len(text))                       # 19 (counts ALL characters including spaces)
print(text.replace("Python", "World")) # "  Hello, World!  "
print(text.find("Python"))             # 8 (starts at index 8)
print(text.count("o"))                 # 3 ('o' appears 3 times)
print("python".capitalize())           # "Python"

Method Chaining

You can chain multiple methods together β€” each operates on the result of the previous one:

message = "  Hello, World!  "
print(message.strip().upper())                           # "HELLO, WORLD!"
print(message.strip().replace("World", "Python").upper()) # "HELLO, PYTHON!"
3
Practice 3
✏️ Try it yourself!
1 Code
Start with username = " Captain Python ". Use method chaining to produce "CAPTAIN PYTHON" (all caps, no spaces).
2 Code
Given sentence = "The quick brown fox jumps over the lazy dog", find:
a) The position of the word "fox" using .find()
b) How many times the letter "o" appears using .count()
c) The total length of the string using len()
3 Code
Replace the word "dog" with "cat" in the sentence above and print the result in uppercase.

2.2.4 f-Strings β€” The Modern Way to Format Text

f-strings (formatted string literals) are the cleanest way to insert variables into text. Just put an f before the opening quote and use {} as placeholders:

name = "Bob"
age = 16
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Bob and I am 16 years old.
πŸ’‘ Memory Hook: Think of an f-string as a fill-in-the-blank worksheet. The {} are the blank spaces, and Python fills them in with the variable values. The f prefix says "this string has blanks to fill!"

Expressions Inside {}

You can put any Python expression inside the curly braces, not just variable names:

a = 10
b = 20
print(f"{a} + {b} = {a + b}")
# Output: 10 + 20 = 30

print(f"Temperature: {36.6}Β°C")
# Output: Temperature: 36.6Β°C

score = 85
print(f"You scored {score}% β€” {'Pass' if score >= 50 else 'Fail'}")
# Output: You scored 85% β€” Pass

Formatting Numbers

You can control how numbers are displayed:

pi = 3.1415926535
print(f"Pi to 2 decimals: {pi:.2f}")    # Pi to 2 decimals: 3.14
print(f"Pi to 4 decimals: {pi:.4f}")    # Pi to 4 decimals: 3.1416

big_number = 1000000
print(f"Formatted: {big_number:,}")     # Formatted: 1,000,000

percentage = 0.875
print(f"Percentage: {percentage:.1%}")  # Percentage: 87.5%

f-Strings vs Older Methods

Method Example Readability
Concatenation "Hi " + name + ", you are " + str(age) πŸ˜• Messy with many variables
f-string βœ… f"Hi {name}, you are {age}" 😊 Clean and readable
4
Practice 4
✏️ Try it yourself!
1 Code
Create variables subject = "Computer Science" and grade = "A". Use an f-string to print: "I got an A in Computer Science!"
2 Code
Using f-strings, print a receipt that shows:
Item: Laptop, Price: $999.99, Tax (8%): $79.99, Total: $1,079.98
Hint: Calculate tax and total inside the f-string!

2.2.5 The print() Function β€” Beyond the Basics

The print() function is your window to the outside world β€” it sends text to the console. Let's explore its hidden powers:

Multiple Arguments

You can pass multiple values separated by commas. print() automatically adds a space between them:

print("Apple", "Banana", "Cherry")
# Output: Apple Banana Cherry

print(1, 2, 3, "Go!")
# Output: 1 2 3 Go!

Customizing the Separator (sep)

The sep parameter changes what goes between items:

print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry

print("10", "20", "30", sep=" | ")
# Output: 10 | 20 | 30

print("hello", "world", sep="")
# Output: helloworld (no space at all!)

Customizing the End Character (end)

By default, print() ends with a newline (\n). You can change this with end:

print("Hello", end=" ")
print("World")
# Output: Hello World (both on the same line!)

print("Loading", end="")
print(".", end="")
print(".", end="")
print(".")
# Output: Loading....

Combining sep and end

print("a", "b", "c", sep=" - ", end="!!!\n")
# Output: a - b - c!!!
πŸ’‘ Pro Tip: Use sep="" and end="" together to build output piece by piece β€” perfect for progress indicators, ASCII art, and formatting tables.
5
Practice 5
✏️ Try it yourself!
1 Code
Use print() with custom sep to display a CSV-like row: Alice,15,Computer Science,A
2 Code
Use print() with end to print the numbers 1 through 5 all on the same line, separated by spaces. Output should look like: 1 2 3 4 5

2.2.6 Escape Characters

Escape sequences let you include special characters inside strings. They start with a backslash \ followed by a character code:

Escape Sequence Meaning Analogy
\n New line (like pressing Enter) πŸ“‹ "Start a fresh page"
\t Tab (moves to next column) ➑️ "Jump to the next cell"
\\ Backslash character πŸ” "I'm the real backslash"
\" Double quote inside double-quoted string πŸ—£οΈ "Escaping the quote"
\' Single quote inside single-quoted string πŸ—£οΈ "Escaping the apostrophe"

Escape Characters in Action

# New line
print("Line 1\nLine 2\nLine 3")
# Output:
# Line 1
# Line 2
# Line 3

# Tab for alignment
print("Name\tAge\tGrade")
print("Alice\t15\tA")
print("Bob\t16\tB")
# Output:
# Name    Age    Grade
# Alice   15     A
# Bob     16     B

# Including quotes inside strings
print("She said, \"Python is amazing!\"")
# Output: She said, "Python is amazing!"

# Backslash in file paths
path = "C:\\Users\\Student\\Documents"
print(path)
# Output: C:\Users\Student\Documents
πŸ’‘ Memory Hook: Think of the backslash \ as a "magic switch" β€” it tells Python: "The next character doesn't mean what it normally means!" \n isn't a backslash and an 'n' β€” it's the "newline magic spell."
6
Practice 6
✏️ Try it yourself!
1 Code
Write a single print statement that displays:
  *
 ***
*****
Use escape characters (\n and maybe \t) to create the pattern β€” all in ONE print statement.
2 Code
Print a table with headers Name, Score, Result and two rows of data (Alice: 85/Pass, Bob: 42/Fail). Use tabs (\t) to align the columns neatly.
3 Code
Write a print statement that shows the sentence:
He said, "Python's \n escape creates a new line."
Hint: You need to escape both the quotes AND the backslash.

πŸ“
String
"A string of characters"

🧱 Analogy: A string is like beads on a necklace β€” each character is a bead, and the quotes are the clasp holding them together.

πŸ“Œ Definition: A string (str) is an immutable sequence of characters enclosed in single, double, or triple quotes, used to represent text data in Python.

πŸ› οΈ Key Methods: .upper(), .lower(), .strip(), .replace(), .find(), .count(), and the function len().

πŸ”—
Concatenation
"Joining strings"

🧱 Analogy: Concatenation is like linking train carriages together β€” each carriage is a string, and the + operator is the coupling mechanism.

πŸ“Œ Definition: Concatenation is the operation of joining two or more strings end-to-end using the + operator to create a single new string.

⚑
f-String
"Fill in the blanks"

🧱 Analogy: An f-string is like a Mad Libs worksheet β€” you have a template with {blanks}, and Python fills them in with your variables to create the final sentence.

πŸ“Œ Definition: An f-string (formatted string literal) is a string prefixed with f that can contain Python expressions inside {} which are evaluated and replaced at runtime.

βœ… Best Practice: Use f-strings over concatenation for cleaner, more readable code!

πŸ”€
Escape Sequence
"Special characters"

🧱 Analogy: The backslash \ is like a "Do Not Read Literally" sign β€” when Python sees \n, it doesn't print a backslash followed by 'n'. Instead, it interprets the combination as a single special character: a newline.

πŸ“Œ Definition: An escape sequence is a combination of a backslash \ followed by a character that represents a special character (like newline \n, tab \t, or a literal quote).


πŸ“‹ Section 2.2 Summary Checklist

☐ I can create strings with single, double, and triple quotes
☐ I know how to concatenate (+) and repeat (*) strings
☐ I can use string methods: .upper(), .lower(), .strip(), .replace(), .find(), .count()
☐ I understand method chaining
☐ I can use f-strings with expressions and number formatting
☐ I can customize print() with sep and end parameters
☐ I understand escape sequences: \n, \t, \\, \", \'
☐ I prefer f-strings over concatenation for formatting

πŸ“‹ Chapter 2: Python Basics β€” Complete Checklist

πŸ”’ Variables and Data Types
☐ I can create variables using the assignment operator =
☐ I can name the 4 basic data types: str, int, float, bool
☐ I can use type() to check a value's type
☐ I follow snake_case naming conventions
☐ I understand dynamic typing and can cast types
πŸ“ Strings and Print Statements
☐ I can create strings with quotes and triple quotes
☐ I can concatenate (+) and repeat (*) strings
☐ I can use .upper(), .lower(), .strip(), .replace(), .find(), .count()
☐ I prefer f-strings over concatenation
☐ I can customize print() with sep and end
☐ I understand escape sequences: \n, \t, \\, \", \'