Unit 1: Python Fundamentals

1. Introduction to Python

What is Python?

  • Python is a high-level, interpreted programming language
  • Created by Guido van Rossum in 1991
  • Known for simple and readable syntax
  • Supports multiple programming paradigms (procedural, OOP, functional)
  • Named after the comedy group "Monty Python"
📖
Easy to Learn

Simple syntax similar to English

📚
Rich Libraries

Extensive standard library

🌐
Cross-Platform

Runs on Windows, Mac, Linux

Interpreted

No compilation required

Applications of Python:

  • Web Development (Django, Flask)
  • Data Science & Machine Learning (NumPy, Pandas, TensorFlow)
  • Automation & Scripting
  • Game Development (Pygame)
  • Desktop Applications (Tkinter, PyQt)

2. Python Setup and Installation

Installation Steps:

  1. Download Python from www.python.org
  2. Run the installer
  3. Check "Add Python to PATH" (Very Important!)
  4. Verify installation: python --version
💡 Tip: Always download the latest stable version of Python 3.x. Python 2.x is deprecated.

IDEs and Editors:

  • IDLE - Included with Python (great for beginners)
  • PyCharm - Professional IDE
  • VS Code - Lightweight and versatile
  • Jupyter Notebook - Interactive, great for data science

3. Variables and Data Types (Detailed)

3.1 What are Variables?

Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

# Creating variables
name = "Python"      # String variable
age = 30             # Integer variable
height = 5.9         # Float variable
is_active = True     # Boolean variable
📝 Note: Python is dynamically typed, meaning you don't need to declare the type of a variable. The type is determined automatically based on the value assigned.

3.2 Variable Naming Rules

  • Must start with a letter (a-z, A-Z) or underscore (_)
  • Cannot start with a number
  • Can only contain alphanumeric characters and underscores (A-z, 0-9, _)
  • Variable names are case-sensitive (age, Age, AGE are different)
  • Cannot use Python keywords (if, else, for, while, etc.)
# Valid variable names
my_name = "John"
_private = 100
userName2 = "Alice"
CONSTANT_VALUE = 3.14

# Invalid variable names (will cause error)
# 2name = "Invalid"    # Cannot start with number
# my-name = "Invalid"  # Cannot use hyphen
# class = "Invalid"    # Cannot use keyword

3.3 Python Data Types in Detail

Python has the following built-in data types:

🔢 Numeric Types

1. Integer (int) - Whole numbers without decimal points

# Integer examples
x = 10
y = -50
z = 0
big_number = 1234567890123456789  # Python handles large integers automatically

print(type(x))  # Output: <class 'int'>

2. Float (float) - Numbers with decimal points

# Float examples
pi = 3.14159
temperature = -40.5
scientific = 2.5e4  # Scientific notation (25000.0)

print(type(pi))  # Output: <class 'float'>

3. Complex (complex) - Numbers with real and imaginary parts

# Complex examples
c1 = 3 + 4j
c2 = complex(2, 5)  # 2 + 5j

print(c1.real)  # Output: 3.0
print(c1.imag)  # Output: 4.0

📝 String Type (str)

Strings are sequences of characters enclosed in quotes.

# String creation methods
single_quote = 'Hello'
double_quote = "World"
multi_line = '''This is a
multi-line string'''

# String with quotes inside
quote1 = "He said 'Hello'"
quote2 = 'She said "Hi"'

# Escape characters
escaped = "Hello\nWorld"  # \n = new line
tab_string = "Hello\tWorld"  # \t = tab

String Operations:

text = "Python Programming"

# Indexing (starts from 0)
print(text[0])     # Output: P
print(text[-1])    # Output: g (negative index from end)

# Slicing
print(text[0:6])   # Output: Python
print(text[7:])    # Output: Programming
print(text[:6])    # Output: Python

# String methods
print(text.upper())        # PYTHON PROGRAMMING
print(text.lower())        # python programming
print(text.split())        # ['Python', 'Programming']
print(len(text))           # 18 (length)
print(text.replace("Python", "Java"))  # Java Programming

String Formatting:

name = "Alice"
age = 25

# Method 1: f-strings (Python 3.6+) - Recommended
print(f"My name is {name} and I am {age} years old")

# Method 2: format() method
print("My name is {} and I am {} years old".format(name, age))

# Method 3: % operator (old style)
print("My name is %s and I am %d years old" % (name, age))

✅ Boolean Type (bool)

Boolean represents one of two values: True or False

# Boolean examples
is_student = True
is_adult = False

# Boolean from comparisons
print(10 > 5)     # True
print(10 == 5)    # False
print(10 != 5)    # True

# Truthy and Falsy values
print(bool(1))     # True
print(bool(0))     # False
print(bool(""))    # False (empty string)
print(bool("Hi"))  # True (non-empty string)
print(bool([]))    # False (empty list)
print(bool([1,2])) # True (non-empty list)
⚠️ Important: In Python, True and False must start with capital letters!

❌ None Type (NoneType)

None represents the absence of a value or null value.

# None examples
result = None
print(result)       # None
print(type(result)) # <class 'NoneType'>

# Common use: Function that doesn't return anything
def greet(name):
    print(f"Hello, {name}")

x = greet("Alice")  # Prints: Hello, Alice
print(x)            # None (function returned nothing)

3.4 Checking Data Types

# Using type() function
x = 10
y = 3.14
z = "Hello"
w = True

print(type(x))  # <class 'int'>
print(type(y))  # <class 'float'>
print(type(z))  # <class 'str'>
print(type(w))  # <class 'bool'>

# Using isinstance() function
print(isinstance(x, int))    # True
print(isinstance(y, float))  # True
print(isinstance(z, str))    # True

3.5 Multiple Assignment

# Assign same value to multiple variables
x = y = z = 100
print(x, y, z)  # 100 100 100

# Assign different values to multiple variables
a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3

# Swap variables
x, y = 10, 20
x, y = y, x  # Swap!
print(x, y)  # 20 10

4. Operators (Complete Guide)

4.1 Arithmetic Operators

Used for mathematical operations.

Operator Name Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 3 3.333...
// Floor Division 10 // 3 3
% Modulus (Remainder) 10 % 3 1
** Exponentiation 2 ** 3 8
# Arithmetic operators in action
a, b = 17, 5

print(f"Addition: {a} + {b} = {a + b}")        # 22
print(f"Subtraction: {a} - {b} = {a - b}")     # 12
print(f"Multiplication: {a} * {b} = {a * b}")  # 85
print(f"Division: {a} / {b} = {a / b}")        # 3.4
print(f"Floor Division: {a} // {b} = {a // b}")# 3
print(f"Modulus: {a} % {b} = {a % b}")         # 2
print(f"Power: {a} ** 2 = {a ** 2}")           # 289

4.2 Comparison (Relational) Operators

Used to compare two values. Returns True or False.

Operator Name Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 5 < 3 False
>= Greater than or equal 5 >= 5 True
<= Less than or equal 5 <= 3 False
# Comparison operators
x, y = 10, 20

print(x == y)   # False
print(x != y)   # True
print(x > y)    # False
print(x < y)    # True
print(x >= 10)  # True
print(y <= 20)  # True

# Chained comparisons (Python special feature!)
age = 25
print(18 <= age <= 65)  # True (age is between 18 and 65)

4.3 Logical Operators

Used to combine conditional statements.

Operator Description Example
and Returns True if both statements are true (5 > 3) and (10 > 5) → True
or Returns True if one statement is true (5 > 3) or (10 < 5) → True
not Reverses the result not(5 > 3) → False
# Logical operators
a, b = True, False

print(a and b)  # False (both must be True)
print(a or b)   # True (at least one is True)
print(not a)    # False (reverses True)
print(not b)    # True (reverses False)

# Practical example
age = 25
has_license = True

can_drive = (age >= 18) and has_license
print(f"Can drive: {can_drive}")  # True
📝 Truth Table:
True and True = True
True and False = False
False and True = False
False and False = False

True or True = True
True or False = True
False or True = True
False or False = False

4.4 Assignment Operators

Used to assign values to variables.

Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
//= x //= 3 x = x // 3
%= x %= 3 x = x % 3
**= x **= 3 x = x ** 3
# Assignment operators
x = 10

x += 5   # x = 15
x -= 3   # x = 12
x *= 2   # x = 24
x /= 4   # x = 6.0
x //= 2  # x = 3.0
x **= 2  # x = 9.0

print(x)  # 9.0

4.5 Bitwise Operators

Used to perform bit-level operations.

Operator Name Description
& AND Sets bit to 1 if both bits are 1
| OR Sets bit to 1 if one of bits is 1
^ XOR Sets bit to 1 if only one bit is 1
~ NOT Inverts all the bits
<< Left Shift Shift left by pushing zeros from right
>> Right Shift Shift right by pushing copies of leftmost bit
# Bitwise operators
a = 5   # Binary: 0101
b = 3   # Binary: 0011

print(a & b)   # 1  (0001)
print(a | b)   # 7  (0111)
print(a ^ b)   # 6  (0110)
print(~a)      # -6 (inverts bits)
print(a << 1)  # 10 (1010) - shift left
print(a >> 1)  # 2  (0010) - shift right

4.6 Identity Operators

Used to compare if two objects are the same object (same memory location).

Operator Description
is Returns True if both variables are the same object
is not Returns True if both variables are not the same object
# Identity operators
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)      # True (same values)
print(a is b)      # False (different objects)
print(a is c)      # True (same object)
print(a is not b)  # True

4.7 Membership Operators

Used to test if a value is present in a sequence.

Operator Description
in Returns True if value is present in sequence
not in Returns True if value is not present in sequence
# Membership operators
fruits = ["apple", "banana", "cherry"]
text = "Hello World"

print("apple" in fruits)      # True
print("grape" in fruits)      # False
print("grape" not in fruits)  # True

print("Hello" in text)        # True
print("hello" in text)        # False (case-sensitive)

4.8 Operator Precedence

Order in which operators are evaluated (highest to lowest):

  1. () - Parentheses
  2. ** - Exponentiation
  3. ~, +, - - Unary operators
  4. *, /, //, % - Multiplication, Division
  5. +, - - Addition, Subtraction
  6. >>, << - Bitwise shifts
  7. & - Bitwise AND
  8. ^ - Bitwise XOR
  9. | - Bitwise OR
  10. ==, !=, >, <, >=, <= - Comparisons
  11. not - Logical NOT
  12. and - Logical AND
  13. or - Logical OR
# Operator precedence examples
result = 2 + 3 * 4      # 14 (not 20)
result = (2 + 3) * 4    # 20 (parentheses first)
result = 2 ** 3 ** 2    # 512 (right to left: 3**2=9, 2**9=512)

5. Input/Output Operations (Detailed)

5.1 Output with print()

The print() function outputs data to the console.

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

# Print multiple values
print("Name:", "John", "Age:", 25)

# Print with separator
print("A", "B", "C", sep="-")  # A-B-C

# Print without newline
print("Hello", end=" ")
print("World")  # Hello World (on same line)

# Print with variables
name = "Alice"
age = 25
print("Name:", name, "Age:", age)

# Formatted output using f-strings
print(f"My name is {name} and I am {age} years old")

# Formatting numbers
pi = 3.14159265359
print(f"Pi = {pi:.2f}")      # Pi = 3.14 (2 decimal places)
print(f"Pi = {pi:.4f}")      # Pi = 3.1416 (4 decimal places)

# Alignment
print(f"{'Left':<10}")    # Left aligned, width 10
print(f"{'Right':>10}")   # Right aligned, width 10
print(f"{'Center':^10}")  # Center aligned, width 10

5.2 Input with input()

The input() function reads user input from keyboard.

# Basic input
name = input("Enter your name: ")
print("Hello,", name)

# Input always returns a string!
age = input("Enter your age: ")
print(type(age))  # <class 'str'>

# Convert input to number
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))

# Multiple inputs on one line
x, y = input("Enter two numbers: ").split()
x, y = int(x), int(y)
print(f"Sum = {x + y}")

# Alternative: using map()
a, b = map(int, input("Enter two numbers: ").split())
print(f"Sum = {a + b}")
⚠️ Important: The input() function always returns a string. You must convert it to the appropriate type (int, float) for mathematical operations!

5.3 Practical Examples

# Example 1: Simple Calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")

if operation == "+":
    result = num1 + num2
elif operation == "-":
    result = num1 - num2
elif operation == "*":
    result = num1 * num2
elif operation == "/":
    result = num1 / num2 if num2 != 0 else "Error: Division by zero"

print(f"Result: {result}")

# Example 2: Temperature Converter
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C = {fahrenheit}°F")

6. Type Conversion (Type Casting)

6.1 Implicit Type Conversion (Automatic)

Python automatically converts one data type to another.

# Implicit conversion
x = 10      # int
y = 3.14    # float
z = x + y   # Python converts x to float automatically

print(z)         # 13.14
print(type(z))   # <class 'float'>

6.2 Explicit Type Conversion (Manual)

Programmer manually converts data types using built-in functions.

Function Description Example
int() Converts to integer int("123") → 123
float() Converts to float float("3.14") → 3.14
str() Converts to string str(123) → "123"
bool() Converts to boolean bool(1) → True
list() Converts to list list("abc") → ['a','b','c']
tuple() Converts to tuple tuple([1,2]) → (1,2)
set() Converts to set set([1,1,2]) → {1,2}
dict() Converts to dictionary dict([('a',1)]) → {'a':1}
# Convert to integer
num = int("123")      # String to int: 123
num = int(45.67)      # Float to int: 45 (truncates decimal)
num = int(True)       # Bool to int: 1

# Convert to float
num = float("3.14")   # String to float: 3.14
num = float(10)       # Int to float: 10.0

# Convert to string
text = str(123)       # Int to string: "123"
text = str(3.14)      # Float to string: "3.14"
text = str(True)      # Bool to string: "True"

# Convert to boolean
bool_val = bool(1)    # True (non-zero is True)
bool_val = bool(0)    # False
bool_val = bool("")   # False (empty string)
bool_val = bool("Hi") # True (non-empty string)

# Convert between collections
my_list = list("Hello")         # ['H', 'e', 'l', 'l', 'o']
my_tuple = tuple([1, 2, 3])     # (1, 2, 3)
my_set = set([1, 2, 2, 3, 3])   # {1, 2, 3}
💡 Tip: Always validate user input before type conversion to avoid errors!
user_input = input("Enter a number: ")
if user_input.isdigit():
    number = int(user_input)
else:
    print("Invalid input!")

7. Data Structures (List, Tuple, Set, Dictionary)

📝 Overview: Python has four built-in data structures to store collections of data:
  • List - Ordered, mutable, allows duplicates
  • Tuple - Ordered, immutable, allows duplicates
  • Set - Unordered, mutable, no duplicates
  • Dictionary - Key-value pairs, unordered*, mutable

📋 List Ordered Mutable Duplicates Allowed

Lists are used to store multiple items in a single variable. Lists are created using square brackets [].

# Creating Lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "Hello", 3.14, True]  # Can store different types

# List with list() constructor
my_list = list((1, 2, 3))  # From tuple

print(fruits)       # ['apple', 'banana', 'cherry']
print(len(fruits))  # 3

Accessing List Elements:

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Positive indexing (starts from 0)
print(fruits[0])    # apple
print(fruits[2])    # cherry

# Negative indexing (starts from -1)
print(fruits[-1])   # elderberry (last item)
print(fruits[-2])   # date (second last)

# Slicing
print(fruits[1:4])    # ['banana', 'cherry', 'date']
print(fruits[:3])     # ['apple', 'banana', 'cherry']
print(fruits[2:])     # ['cherry', 'date', 'elderberry']
print(fruits[::2])    # ['apple', 'cherry', 'elderberry'] (step 2)
print(fruits[::-1])   # Reverse the list

Modifying Lists:

fruits = ["apple", "banana", "cherry"]

# Change item
fruits[1] = "blueberry"
print(fruits)  # ['apple', 'blueberry', 'cherry']

# Add items
fruits.append("date")        # Add at end
fruits.insert(1, "apricot")  # Add at specific position
fruits.extend(["fig", "grape"])  # Add multiple items

# Remove items
fruits.remove("apple")   # Remove by value
del fruits[0]            # Remove by index
popped = fruits.pop()    # Remove and return last item
popped = fruits.pop(1)   # Remove and return item at index
fruits.clear()           # Remove all items

List Methods:

append()
insert()
extend()
remove()
pop()
clear()
sort()
reverse()
copy()
count()
index()
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

# Sorting
numbers.sort()           # Sort ascending: [1, 1, 2, 3, 4, 5, 6, 9]
numbers.sort(reverse=True)  # Sort descending

# Other operations
numbers.reverse()        # Reverse the list
count = numbers.count(1) # Count occurrences of 1
idx = numbers.index(5)   # Find index of 5

# List comprehension
squares = [x**2 for x in range(1, 6)]  # [1, 4, 9, 16, 25]
evens = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]

📦 Tuple Ordered Immutable Duplicates Allowed

Tuples are used to store multiple items that cannot be changed. Tuples are created using parentheses ().

# Creating Tuples
empty_tuple = ()
single_item = (1,)  # Note the comma! Without it, it's just (1)
numbers = (1, 2, 3, 4, 5)
fruits = ("apple", "banana", "cherry")
mixed = (1, "Hello", 3.14, True)

# Tuple with tuple() constructor
my_tuple = tuple([1, 2, 3])  # From list

print(fruits)       # ('apple', 'banana', 'cherry')
print(len(fruits))  # 3

Accessing Tuple Elements:

fruits = ("apple", "banana", "cherry", "date")

# Same as list indexing
print(fruits[0])    # apple
print(fruits[-1])   # date
print(fruits[1:3])  # ('banana', 'cherry')

# Tuple unpacking
a, b, c, d = fruits
print(a)  # apple
print(b)  # banana

# Using * for remaining items
first, *middle, last = (1, 2, 3, 4, 5)
print(first)   # 1
print(middle)  # [2, 3, 4]
print(last)    # 5
⚠️ Important: Tuples are immutable - you cannot change, add, or remove items after creation!
fruits = ("apple", "banana")
# fruits[0] = "cherry"  # This will cause an error!

Why Use Tuples?

  • Faster than lists
  • Protect data from modification
  • Can be used as dictionary keys (lists cannot)
  • Used for returning multiple values from functions
# Tuple methods (only 2 methods!)
numbers = (1, 2, 3, 2, 4, 2)
print(numbers.count(2))  # 3 (count occurrences)
print(numbers.index(3))  # 2 (find index)

# Convert tuple to list to modify
fruits = ("apple", "banana")
temp_list = list(fruits)
temp_list.append("cherry")
fruits = tuple(temp_list)
print(fruits)  # ('apple', 'banana', 'cherry')

🎯 Set Unordered Mutable No Duplicates

Sets are used to store unique items only. Sets are created using curly braces {}.

# Creating Sets
empty_set = set()  # Note: {} creates an empty dictionary!
numbers = {1, 2, 3, 4, 5}
fruits = {"apple", "banana", "cherry"}

# Duplicates are automatically removed
numbers = {1, 2, 2, 3, 3, 3}
print(numbers)  # {1, 2, 3}

# Set with set() constructor
my_set = set([1, 2, 2, 3, 3])  # {1, 2, 3}

print(fruits)       # {'apple', 'banana', 'cherry'}
print(len(fruits))  # 3
📝 Note: Sets are unordered, so you cannot access items by index. The order may change each time you print!

Adding and Removing Items:

fruits = {"apple", "banana", "cherry"}

# Add items
fruits.add("date")           # Add single item
fruits.update(["fig", "grape"])  # Add multiple items

# Remove items
fruits.remove("apple")    # Remove (error if not found)
fruits.discard("mango")   # Remove (no error if not found)
popped = fruits.pop()     # Remove and return random item
fruits.clear()            # Remove all items

Set Operations:

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# Union (all elements from both sets)
print(A | B)           # {1, 2, 3, 4, 5, 6, 7, 8}
print(A.union(B))      # Same result

# Intersection (common elements)
print(A & B)              # {4, 5}
print(A.intersection(B))  # Same result

# Difference (in A but not in B)
print(A - B)           # {1, 2, 3}
print(A.difference(B)) # Same result

# Symmetric Difference (in A or B, but not both)
print(A ^ B)                     # {1, 2, 3, 6, 7, 8}
print(A.symmetric_difference(B)) # Same result

# Subset and Superset
print({1, 2}.issubset(A))     # True
print(A.issuperset({1, 2}))   # True

Set Methods:

add()
update()
remove()
discard()
pop()
clear()
union()
intersection()
difference()
issubset()
issuperset()

📖 Dictionary Key-Value Pairs Mutable No Duplicate Keys

Dictionaries store data in key-value pairs. Keys must be unique and immutable. Created using curly braces {} with key:value pairs.

# Creating Dictionaries
empty_dict = {}
student = {
    "name": "John",
    "age": 20,
    "grade": "A",
    "courses": ["Math", "Science"]
}

# Dictionary with dict() constructor
person = dict(name="Alice", age=25, city="Mumbai")

print(student)
print(len(student))  # 4 (number of key-value pairs)

Accessing Dictionary Items:

student = {"name": "John", "age": 20, "grade": "A"}

# Access by key
print(student["name"])      # John
print(student.get("age"))   # 20
print(student.get("gpa", "N/A"))  # N/A (default if not found)

# Get all keys, values, items
print(student.keys())    # dict_keys(['name', 'age', 'grade'])
print(student.values())  # dict_values(['John', 20, 'A'])
print(student.items())   # dict_items([('name', 'John'), ...])

# Check if key exists
if "name" in student:
    print("Name exists!")

# Loop through dictionary
for key in student:
    print(f"{key}: {student[key]}")

for key, value in student.items():
    print(f"{key}: {value}")

Modifying Dictionaries:

student = {"name": "John", "age": 20}

# Add or update items
student["grade"] = "A"         # Add new key-value
student["age"] = 21            # Update existing
student.update({"city": "NYC", "age": 22})  # Update multiple

# Remove items
del student["city"]            # Delete by key
grade = student.pop("grade")   # Remove and return value
last = student.popitem()       # Remove last inserted item
student.clear()                # Remove all items

Dictionary Methods:

get()
keys()
values()
items()
update()
pop()
popitem()
clear()
copy()
setdefault()
fromkeys()

Nested Dictionaries:

students = {
    "student1": {"name": "John", "age": 20},
    "student2": {"name": "Alice", "age": 22},
    "student3": {"name": "Bob", "age": 21}
}

# Access nested items
print(students["student1"]["name"])  # John

# Dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

📊 Comparison of Data Structures

Feature List Tuple Set Dictionary
Syntax [ ] ( ) { } {k:v}
Ordered ✅ Yes ✅ Yes ❌ No ✅ Yes*
Mutable ✅ Yes ❌ No ✅ Yes ✅ Yes
Duplicates ✅ Yes ✅ Yes ❌ No Keys: No
Indexing ✅ Yes ✅ Yes ❌ No By Key
Use Case General storage Fixed data Unique items Key-value pairs

*Dictionaries maintain insertion order since Python 3.7

8. Understanding the Syntax Transition: From C to Python

📝 Why Learn This? If you're coming from C programming, Python will feel very different. Understanding these differences will help you transition smoothly and write better Python code.

8.1 Key Differences Overview

Feature C Language Python
Type System Statically typed (must declare types) Dynamically typed (no declaration needed)
Compilation Compiled language Interpreted language
Syntax Style Uses braces { } and semicolons ; Uses indentation and colons :
Memory Manual memory management Automatic garbage collection
Execution Faster execution Slower but easier development

8.2 Variable Declaration

C Language

// Must declare type
int age = 25;
float height = 5.9;
char name[20] = "John";
int x, y, z;

// Constants
const int MAX = 100;

Python

# No type declaration needed
age = 25
height = 5.9
name = "John"
x = y = z = 0

# Constants (by convention, all caps)
MAX = 100

8.3 Input/Output

C Language

#include <stdio.h>

int main() {
    int age;
    char name[50];
    
    // Output
    printf("Hello World\n");
    printf("Age: %d\n", 25);
    
    // Input
    printf("Enter name: ");
    scanf("%s", name);
    printf("Enter age: ");
    scanf("%d", &age);
    
    return 0;
}

Python

# No imports needed for basic I/O

# Output
print("Hello World")
print("Age:", 25)
print(f"Age: {25}")

# Input (always returns string)
name = input("Enter name: ")
age = int(input("Enter age: "))

# No main function required
# No return statement needed

8.4 Conditional Statements (if-else)

C Language

int age = 20;

if (age >= 18) {
    printf("Adult\n");
} else if (age >= 13) {
    printf("Teenager\n");
} else {
    printf("Child\n");
}

// Switch statement
switch (grade) {
    case 'A':
        printf("Excellent");
        break;
    case 'B':
        printf("Good");
        break;
    default:
        printf("Invalid");
}

Python

age = 20

if age >= 18:
    print("Adult")
elif age >= 13:
    print("Teenager")
else:
    print("Child")

# No switch, use match (Python 3.10+)
match grade:
    case 'A':
        print("Excellent")
    case 'B':
        print("Good")
    case _:
        print("Invalid")

# Or use if-elif-else / dictionary
💡 Key Differences:
  • Python uses elif instead of else if
  • No parentheses around conditions
  • No braces - uses colon and indentation
  • No semicolons at end of lines

8.5 Loops

C Language - For Loop

// Print 0 to 4
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}

// Iterate array
int arr[] = {10, 20, 30};
int size = sizeof(arr)/sizeof(arr[0]);
for (int i = 0; i < size; i++) {
    printf("%d\n", arr[i]);
}

Python - For Loop

# Print 0 to 4
for i in range(5):
    print(i)

# Iterate list (directly!)
arr = [10, 20, 30]
for item in arr:
    print(item)

# With index
for i, item in enumerate(arr):
    print(i, item)

C Language - While Loop

int i = 0;
while (i < 5) {
    printf("%d\n", i);
    i++;
}

// Do-while loop
do {
    printf("%d\n", i);
    i++;
} while (i < 5);

Python - While Loop

i = 0
while i < 5:
    print(i)
    i += 1  # No ++ operator!

# No do-while in Python
# Use while True with break
while True:
    print(i)
    i += 1
    if i >= 5:
        break
⚠️ Important: Python does NOT have ++ or -- operators! Use i += 1 or i -= 1 instead.

8.6 Functions

C Language

// Function declaration
int add(int a, int b);

// Function definition
int add(int a, int b) {
    return a + b;
}

// Function with no return
void greet(char name[]) {
    printf("Hello %s\n", name);
}

int main() {
    int result = add(5, 3);
    greet("John");
    return 0;
}

Python

# Function definition (no declaration)
def add(a, b):
    return a + b

# Function with no return
def greet(name):
    print(f"Hello {name}")

# Default parameters
def greet(name="World"):
    print(f"Hello {name}")

# Multiple return values!
def get_stats(nums):
    return min(nums), max(nums)

result = add(5, 3)
greet("John")
low, high = get_stats([1,2,3])

8.7 Arrays vs Lists

C Language - Arrays

// Fixed size, same type
int numbers[5] = {1, 2, 3, 4, 5};
int matrix[3][3];

// Access elements
numbers[0] = 10;
int val = numbers[2];

// Size must be known
int size = sizeof(numbers)/sizeof(numbers[0]);

// Cannot resize once created

Python - Lists

# Dynamic size, any type
numbers = [1, 2, 3, 4, 5]
matrix = [[1,2], [3,4], [5,6]]

# Access elements
numbers[0] = 10
val = numbers[2]

# Get size easily
size = len(numbers)

# Can resize anytime!
numbers.append(6)
numbers.extend([7, 8])
numbers.pop()

8.8 Strings

C Language

#include <string.h>

char str1[20] = "Hello";
char str2[20] = "World";
char result[40];

// String length
int len = strlen(str1);

// String copy
strcpy(result, str1);

// String concatenation
strcat(result, str2);

// String comparison
if (strcmp(str1, str2) == 0) {
    printf("Equal");
}

Python

# No imports needed

str1 = "Hello"
str2 = "World"

# String length
length = len(str1)

# String copy (just assign)
result = str1

# String concatenation
result = str1 + " " + str2

# String comparison
if str1 == str2:
    print("Equal")

# Many built-in methods!
print(str1.upper())
print(str1.lower())
print(str1.replace("l", "L"))

8.9 Comments

C Language

// Single line comment

/* Multi-line
   comment in C */

int x = 5; // Inline comment

Python

# Single line comment

"""
Multi-line comment
(using docstring)
"""

'''
Also works with
single quotes
'''

x = 5  # Inline comment

8.10 Complete Program Comparison

Example: Find the largest of three numbers

C Language

#include <stdio.h>

int main() {
    int a, b, c, largest;
    
    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);
    
    if (a >= b && a >= c) {
        largest = a;
    } else if (b >= a && b >= c) {
        largest = b;
    } else {
        largest = c;
    }
    
    printf("Largest: %d\n", largest);
    return 0;
}

Python

# Much simpler!

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

# Method 1: Using if-elif-else
if a >= b and a >= c:
    largest = a
elif b >= a and b >= c:
    largest = b
else:
    largest = c

# Method 2: Using built-in max()
largest = max(a, b, c)

print(f"Largest: {largest}")

8.11 Quick Reference Cheat Sheet

Concept C Syntax Python Syntax
Print printf("Hello\n"); print("Hello")
Input scanf("%d", &x); x = int(input())
If if (x > 0) { } if x > 0:
Else If else if (x < 0) { } elif x < 0:
For Loop for(i=0; i for i in range(n):
While Loop while(x > 0) { } while x > 0:
Increment i++; i += 1
Function int func(int a) { } def func(a):
Array/List int arr[5]; arr = []
Length sizeof(arr)/sizeof(arr[0]) len(arr)
AND && and
OR || or
NOT ! not
True/False 1 / 0 True / False
NULL NULL None
💡 Tips for C Programmers Learning Python:
  1. Stop typing semicolons - Python doesn't need them!
  2. Use indentation carefully - it defines code blocks
  3. Forget about type declarations - Python handles it
  4. Embrace Python's built-in functions (len, max, min, sum, etc.)
  5. Lists are much more powerful than C arrays
  6. Use and, or, not instead of &&, ||, !