Skip to main content

Module 2 - Python Syntax & Data Types

This module covers Python's core syntax and fundamental data types. You'll learn how to write clean, Pythonic code and work with numbers, strings, booleans, and type conversions.


1. Python Syntax Basics

1.1 Indentation (Critical!)

Python uses indentation to define code blocks (not braces like C/Java).

# Good
if True:
print("This is indented")
print("Still in the if block")

# Bad - IndentationError
if True:
print("This will cause an error")
Indentation Rules
  • Use 4 spaces (not tabs)
  • Be consistent throughout your code
  • Mixing spaces and tabs causes errors

1.2 Comments

# This is a single-line comment

"""
This is a multi-line comment
Also called a docstring when used for documentation
"""

def greet(name):
"""
Function docstring - describes what the function does

Args:
name (str): Name of the person to greet

Returns:
str: Greeting message
"""
return f"Hello, {name}!"

1.3 Statements and Line Continuation

# Multiple statements on one line (avoid)
x = 5; y = 10; print(x + y)

# Line continuation with backslash
total = 1 + 2 + 3 + \
4 + 5 + 6

# Implicit line continuation (preferred)
total = (1 + 2 + 3 +
4 + 5 + 6)

# List spanning multiple lines
numbers = [
1, 2, 3,
4, 5, 6,
7, 8, 9
]

2. Variables and Assignment

2.1 Variable Naming Rules

# Valid variable names
name = "John"
age = 25
user_name = "john_doe"
_private = "internal"
MAX_SIZE = 100

# Invalid names (will cause errors)
2name = "Invalid" # Cannot start with digit
user-name = "Invalid" # No hyphens
class = "Invalid" # Reserved keyword

2.2 Multiple Assignment

# Multiple variables, same value
x = y = z = 0

# Multiple variables, different values
name, age, city = "John", 25, "NYC"

# Swapping values (Pythonic way)
a, b = 10, 20
a, b = b, a # a=20, b=10

2.3 Dynamic Typing

# Variable can change type
x = 5 # int
print(type(x)) # <class 'int'>

x = "Hello" # str
print(type(x)) # <class 'str'>

x = [1, 2, 3] # list
print(type(x)) # <class 'list'>

3. Numeric Data Types

3.1 Integers (int)

# Integer literals
x = 42
negative = -10
large = 1_000_000 # Underscores for readability

# Different bases
binary = 0b1010 # Binary (10 in decimal)
octal = 0o12 # Octal (10 in decimal)
hexadecimal = 0xFF # Hexadecimal (255 in decimal)

# Unlimited precision
huge = 123456789012345678901234567890
print(huge ** 2)

3.2 Floating Point (float)

# Float literals
x = 3.14
scientific = 3.14e-10 # Scientific notation
large_float = 2.5e6 # 2,500,000

# Float precision issues
print(0.1 + 0.2) # 0.30000000000000004

# Use Decimal for precision
from decimal import Decimal
x = Decimal('0.1') + Decimal('0.2')
print(x) # 0.3

3.3 Complex Numbers

# Complex number literals
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0

# Complex arithmetic
z1 = 2 + 3j
z2 = 1 - 1j
print(z1 + z2) # (3+2j)
print(z1 * z2) # (5+1j)

3.4 Arithmetic Operators

a, b = 10, 3

# Basic operators
print(a + b) # 13 Addition
print(a - b) # 7 Subtraction
print(a * b) # 30 Multiplication
print(a / b) # 3.33 Division (always float)
print(a // b) # 3 Floor division
print(a % b) # 1 Modulus (remainder)
print(a ** b) # 1000 Exponentiation

# Compound assignment
x = 10
x += 5 # x = x + 5
x -= 3 # x = x - 3
x *= 2 # x = x * 2
x //= 4 # x = x // 4

3.5 Math Module

import math

# Common functions
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.ceil(3.2)) # 4
print(math.floor(3.8)) # 3
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045

# Trigonometry
print(math.sin(math.pi/2)) # 1.0
print(math.cos(0)) # 1.0
print(math.tan(math.pi/4)) # 1.0

4. Strings (str)

4.1 String Creation

# Different quote styles
single = 'Hello'
double = "World"
triple = """Multi-line
string with
line breaks"""

# Raw strings (ignore escape sequences)
path = r"C:\new\folder"

# F-strings (formatted string literals) - Python 3.6+
name = "John"
age = 25
message = f"My name is {name} and I'm {age} years old"

4.2 String Indexing and Slicing

text = "Python Programming"

# Indexing (0-based)
print(text[0]) # 'P'
print(text[-1]) # 'g' (last character)
print(text[-2]) # 'n' (second to last)

# Slicing [start:end:step]
print(text[0:6]) # 'Python'
print(text[:6]) # 'Python' (start from beginning)
print(text[7:]) # 'Programming' (to the end)
print(text[::2]) # 'Pto rgamn' (every 2nd character)
print(text[::-1]) # 'gnimmargorP nohtyP' (reverse)

4.3 String Methods

text = "  Python Programming  "

# Case conversion
print(text.upper()) # ' PYTHON PROGRAMMING '
print(text.lower()) # ' python programming '
print(text.capitalize()) # ' python programming '
print(text.title()) # ' Python Programming '

# Whitespace removal
print(text.strip()) # 'Python Programming'
print(text.lstrip()) # 'Python Programming '
print(text.rstrip()) # ' Python Programming'

# Searching
print(text.find('Python')) # 2
print(text.count('m')) # 2
print(text.startswith(' P')) # True
print(text.endswith('g ')) # True

# Replacement
print(text.replace('Python', 'Java'))

# Splitting and joining
words = "apple,banana,orange".split(',')
print(words) # ['apple', 'banana', 'orange']
print(' '.join(words)) # 'apple banana orange'

4.4 String Formatting

name = "John"
age = 25
salary = 50000.50

# F-strings (recommended)
print(f"Name: {name}, Age: {age}")
print(f"Salary: ${salary:,.2f}") # $50,000.50

# Format method
print("Name: {}, Age: {}".format(name, age))
print("Name: {n}, Age: {a}".format(n=name, a=age))

# Old-style (avoid in new code)
print("Name: %s, Age: %d" % (name, age))

4.5 String Immutability

text = "Python"

# Strings are immutable
# text[0] = 'J' # TypeError!

# Create new string instead
text = 'J' + text[1:]
print(text) # 'Jython'

5. Boolean (bool)

5.1 Boolean Values

# Two values: True and False (case-sensitive)
is_active = True
is_deleted = False

print(type(True)) # <class 'bool'>

# Boolean arithmetic (True=1, False=0)
print(True + True) # 2
print(True * 5) # 5
print(False + 10) # 10

5.2 Comparison Operators

x, y = 10, 5

print(x == y) # False (equal)
print(x != y) # True (not equal)
print(x > y) # True (greater than)
print(x < y) # False (less than)
print(x >= y) # True (greater or equal)
print(x <= y) # False (less or equal)

5.3 Logical Operators

x, y = True, False

# and - Both must be True
print(x and y) # False
print(True and True) # True

# or - At least one must be True
print(x or y) # True
print(False or False) # False

# not - Inverts boolean value
print(not x) # False
print(not y) # True

5.4 Truthy and Falsy Values

# Falsy values
print(bool(False)) # False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool('')) # False (empty string)
print(bool([])) # False (empty list)
print(bool({})) # False (empty dict)
print(bool(None)) # False

# Everything else is Truthy
print(bool(True)) # True
print(bool(42)) # True
print(bool("text")) # True
print(bool([1])) # True

6. None Type

# None represents absence of value
result = None
print(type(result)) # <class 'NoneType'>

# Common use cases
def function_without_return():
print("No return statement")

result = function_without_return()
print(result) # None

# Checking for None
if result is None:
print("Result is None")

# Don't use ==, use 'is'
if result is not None:
print("Result has a value")

7. Type Conversion (Casting)

# String to int
x = int("42")
print(x) # 42

# String to float
y = float("3.14")
print(y) # 3.14

# Number to string
s = str(100)
print(s) # '100'

# String to boolean
print(bool("")) # False
print(bool("text")) # True

# Explicit conversions
print(int(3.9)) # 3 (truncates)
print(float(5)) # 5.0
print(str(True)) # 'True'

# Error handling
try:
x = int("abc")
except ValueError as e:
print(f"Conversion error: {e}")

8. Input and Output

8.1 Input Function

# Basic input (always returns string)
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Converting input
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))

# Multiple inputs on one line
x, y = input("Enter two numbers: ").split()
x, y = int(x), int(y)

8.2 Print Function

# Basic printing
print("Hello, World!")

# Multiple arguments
print("Name:", "John", "Age:", 25)

# Custom separator
print("apple", "banana", "orange", sep=", ")

# Custom ending
print("Loading", end="...")
print("Done!")

# Formatting
name = "John"
print(f"Hello, {name}!")

9. Constants

# Python has no built-in constant type
# Convention: use UPPER_CASE names

MAX_SIZE = 100
PI = 3.14159
API_KEY = "abc123def456"

# You can still modify them (no enforcement)
# MAX_SIZE = 200 # Valid but violates convention

# Use typing module for hints (Python 3.8+)
from typing import Final

MAX_CONNECTIONS: Final = 10
# MAX_CONNECTIONS = 20 # Type checker will warn

Summary

✅ Python uses indentation for code blocks
✅ Variables are dynamically typed
✅ Three numeric types: int, float, complex
✅ Strings are immutable and have powerful methods
✅ Booleans evaluate truthy/falsy values
✅ Use None for absence of value
✅ Type conversion with int(), float(), str(), bool()


Next Steps

In Module 3, you'll learn:

  • Lists, tuples, and sets
  • Dictionaries
  • Collection operations
  • List comprehensions

Practice Exercises

  1. Write a program that converts temperature from Celsius to Fahrenheit
  2. Create a string manipulation program that reverses a user's name
  3. Build a simple calculator that takes two numbers and performs all arithmetic operations
  4. Write a program that checks if a number is even or odd
  5. Create a BMI calculator that takes height and weight as input
Challenge

Create a program that:

  • Takes a sentence as input
  • Counts the number of words, vowels, and consonants
  • Converts the sentence to title case
  • Displays all results formatted nicely