Introduction to Python Programming
Variables · Loops · Functions · Code Examples · Learning Resources
What is Python?
Python is a high-level, general-purpose programming language created by Guido van Rossum and
first released in 1991. Its design philosophy emphasises code readability and simplicity, making it
one of the easiest languages for beginners to learn. Python consistently ranks as the world's most
popular programming language (TIOBE Index, Stack Overflow Developer Survey). It powers web
applications (Instagram, Pinterest), data science (NumPy, Pandas), artificial intelligence
(TensorFlow, PyTorch), automation, game development, and much more.
1. Setting Up Python
Install Python from [Link] (choose version 3.10 or newer). During installation on Windows,
tick "Add Python to PATH." Verify your installation by opening a terminal and typing: python
--version We recommend VS Code or PyCharm as your editor. Alternatively, try Google Colab — a
free browser-based environment that requires no installation.
python --version
# Output: Python 3.11.4
print("Hello, World!")
2. Variables and Data Types
Variables are named containers for data. Python is dynamically typed — you do not need to
declare a type; Python infers it automatically. The main built-in types are: int (integers), float
(decimal numbers), str (text strings), bool (True/False), list, tuple, dict, and set.
# Integer
age = 25
# Float
height = 5.9
# String
name = "Alice"
# Boolean
is_student = True
# Check the type
print(type(age)) #
print(type(name)) #
3. Operators
Python supports arithmetic (+, -, *, /, //, %, **), comparison (==, !=, <, >, <=, >=), logical (and, or,
not), and assignment operators (=, +=, -=, etc.).
# Arithmetic
print(10 + 3) # 13
print(10 / 3) # 3.333...
print(10 // 3) # 3 (floor division)
print(10 % 3) # 1 (remainder)
print(2 ** 8) # 256 (exponent)
# Comparison
print(5 > 3) # True
print(5 == 5) # True
print(5 != 4) # True
4. Strings
Strings are sequences of characters enclosed in single or double quotes. Python provides rich
string operations: concatenation, slicing, formatting, and many built-in methods.
greeting = "Hello, World!"
print(len(greeting)) # 13
print([Link]()) # HELLO, WORLD!
print(greeting[0:5]) # Hello
print([Link]("World", "Python")) # Hello, Python!
# f-strings (Python 3.6+)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
5. Lists
A list is an ordered, mutable collection of items. Lists can hold mixed data types and are one of the
most versatile data structures in Python.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
[Link]("mango") # add to end
[Link]("banana") # remove item
print(len(fruits)) # 3
# List slicing
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # [2, 3, 4]
print(numbers[::-1]) # [5, 4, 3, 2, 1]
6. Dictionaries
Dictionaries store key-value pairs. They are unordered (Python 3.7+ preserves insertion order),
mutable, and do not allow duplicate keys.
person = {
"name": "Alice",
"age": 25,
"city": "Mumbai"
}
print(person["name"]) # Alice
person["email"] = "alice@[Link]" # add key
print([Link]()) # dict_keys([...])
print([Link]()) # dict_values([...])
7. Conditional Statements
Conditionals allow your program to make decisions. Python uses if, elif, and else keywords.
Indentation (4 spaces) defines code blocks — there are no curly braces.
score = 78
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(f"Your grade is: {grade}") # Your grade is: B
8. Loops
Loops repeat a block of code. Python has two loop types: for loops (iterate over a sequence) and
while loops (repeat while a condition is True). Use break to exit early, continue to skip an iteration.
# for loop
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
# Loop over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# while loop
count = 0
while count < 5:
count += 1
print(count) # 5
# List comprehension (Pythonic shorthand)
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
9. Functions
Functions are reusable blocks of code defined with the def keyword. They can accept parameters,
have default values, return values, and even return multiple values at once.
def greet(name, greeting="Hello"):
"""Return a greeting string."""
return f"{greeting}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Good morning")) # Good morning, Bob!
# Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
lo, hi = min_max([3, 1, 7, 2, 9])
print(lo, hi) # 1 9
10. File I/O
Python makes reading and writing files straightforward. Always use the with statement — it
automatically closes the file even if an error occurs.
# Write to a file
with open("[Link]", "w") as f:
[Link]("Line 1\nLine 2\nLine 3")
# Read from a file
with open("[Link]", "r") as f:
content = [Link]()
print(content)
# Read line by line
with open("[Link]", "r") as f:
for line in f:
print([Link]())
11. Error Handling
Runtime errors (exceptions) can crash your program. Use try/except to catch and handle them
gracefully. The finally block always runs, making it ideal for cleanup code.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("Please enter a valid integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Program finished.")
12. Modules and Libraries
Python's standard library is enormous, and thousands of third-party packages extend it further.
Import modules with the import statement. Install third-party packages with pip.
# Standard library
import math
import random
import datetime
print([Link](144)) # 12.0
print([Link](1, 100)) # random number
print([Link]()) # today's date
# Install a package
# pip install requests
import requests
response = [Link]("[Link]
print(response.status_code) # 200
Learning Resources
Official Documentation: [Link] — comprehensive and kept up to date
Interactive Practice: [Link], [Link], [Link]
Free Courses: CS50P (Harvard), freeCodeCamp Python, Automate the Boring Stuff
([Link])
Books: Python Crash Course (Eric Matthes), Fluent Python (Luciano Ramalho)
Community: r/learnpython, Stack Overflow, Python Discord
— End of Document —