Python is one of the most popular programming languages in the world, and for very good reason. It reads almost like plain English. The syntax is clean and simple. You can do real, useful things with it in just a few lines of code.
Whether you want to build websites, analyse data, train machine learning models, automate tasks or just learn to think like a programmer — Python is an excellent first language. Big companies like Google, Netflix, Instagram and NASA use Python every single day.
This guide covers everything you need to start writing real Python code from scratch. Every concept is explained simply, every example is clear, and by the end you will have a solid foundation to build on.
Why Python Is Great for Beginners
Most programming languages make you write a lot of boilerplate — setup code that has nothing to do with what you are actually trying to accomplish. Python is different. It gets out of your way and lets you focus on the problem.
Compare printing "Hello World" in different languages. In Java you need a class, a main method and a print statement. In Python you just write one line:
That is the whole program. One line. No boilerplate, no semicolons, no curly braces. Python uses indentation (spaces at the start of a line) to organise code instead of brackets. This makes code visually clean and easy to read.
Your First Line of Code
To follow along, you can run Python in your browser at python.org/shell or install Python from python.org and use the built-in IDLE editor. VS Code with the Python extension is excellent for longer projects.
# This is a comment — Python ignores everything after the hash sign
# Comments are notes for humans, not instructions for Python
# Print text to the screen
print("Hello, World!")
print("My name is Shashank")
print(42)
print("I am", 25, "years old") # prints: I am 25 years old
# Ask the user to type something
name = input("What is your name? ")
print("Hello,", name, "!")
ℹ️
Python is case-sensitive. print works. Print does not. myName and myname are two completely different things. Always check your capitalisation when you get an error.
Variables — Storing Information
A variable is a named container that holds a value. Think of it like a labelled box. You put something in the box, give the box a name, and then you can find what is in it by using that name later.
In Python, creating a variable is as simple as writing its name, an equals sign, and the value you want to store. You do not need to declare the type — Python figures it out automatically.
# Create variables by assigning a value with =
name = "Shashank"
age = 25
height = 5.9
is_student = True
# Use them anywhere
print(name) # Shashank
print(age) # 25
print(age + 5) # 30
# Variables can be updated at any time
age = age + 1 # now age is 26
age += 1 # shortcut for the same thing
# Good variable names are lowercase with underscores
user_name = "shashank" # good
total_price = 149.99 # good
max_retry_count = 3 # good
Data Types — Different Kinds of Values
Every value in Python has a type. The type tells Python what kind of data it is and what operations it can perform. The four most important types for beginners are strings, integers, floats and booleans.
Strings — Text
A string is any text wrapped in quotes. You can use single quotes or double quotes — both work the same way.
greeting = "Hello, World!"
name = 'Shashank'
# Joining strings together (concatenation)
print("Hello, " + name) # Hello, Shashank
# f-strings — the easiest way to put variables inside text
age = 25
print(f"My name is {name} and I am {age} years old.")
# Useful string methods
text = " Hello World "
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.strip()) # "Hello World" — removes spaces from both ends
print(text.replace("World", "Python")) # Hello Python
print(len("Hello")) # 5 — length of the string
print("World" in text) # True — checks if a word is inside
Numbers — Integers and Floats
An integer (int) is a whole number with no decimal point. A float is a number with a decimal point. Python handles all the maths automatically.
whole_number = 42 # integer
decimal = 3.14 # float
# Basic maths
print(10 + 3) # 13 — addition
print(10 - 3) # 7 — subtraction
print(10 * 3) # 30 — multiplication
print(10 / 3) # 3.33 — division (always gives a float)
print(10 // 3) # 3 — floor division (drops the decimal)
print(10 % 3) # 1 — remainder after division
print(2 ** 10) # 1024 — power (2 to the power of 10)
# Convert between types
print(int(3.9)) # 3 — converts float to int (truncates, does not round)
print(float(5)) # 5.0 — converts int to float
print(str(42)) # "42" — converts number to string
Booleans — True or False
A boolean has exactly two possible values: True or False. They are the result of comparisons and are the backbone of all decision-making in code.
print(5 > 3) # True
print(5 < 3) # False
print(5 == 5) # True — two equals signs means "is equal to"
print(5 != 3) # True — not equal to
print(5 >= 5) # True — greater than or equal to
# Combining conditions with and, or, not
age = 20
print(age >= 18 and age < 65) # True — both conditions must be true
print(age < 10 or age > 18) # True — at least one must be true
print(not True) # False — flips the value
if, elif and else — Making Decisions
Conditionals let your program make decisions. If a condition is true, run this code. Otherwise, run that code instead. This is how programs respond differently to different inputs.
score = 75
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B") # this runs — score is 75
elif score >= 60:
print("Grade: C")
else:
print("Grade: F")
# Important: indentation (4 spaces) tells Python what is inside the block
# Python will throw an error if indentation is wrong
# Checking user input
password = input("Enter password: ")
if password == "secret123":
print("Access granted!")
else:
print("Wrong password.")
⚠️
One equals vs two equals: = assigns a value (it puts something in a variable). == compares two values (it asks "are these equal?"). This is one of the most common beginner mistakes. Use == inside conditions, never =.
Loops — Repeating Code
A loop lets you run the same block of code over and over, either for each item in a collection or as long as a condition stays true. Without loops, you would have to copy and paste code hundreds of times.
for loops — Loop Through a Collection
A for loop goes through every item in a list, string or range and runs your code once for each one.
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# prints: apple, banana, cherry (one per line)
# Loop a specific number of times using range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
# Loop through a string — goes character by character
for letter in "hello":
print(letter) # h, e, l, l, o
# break — exit the loop early
# continue — skip the current iteration and move to the next
for n in range(10):
if n == 3:
continue # skip 3
if n == 7:
break # stop at 7
print(n) # prints: 0, 1, 2, 4, 5, 6
while loops — Keep Going Until a Condition Changes
A while loop keeps running as long as a condition is true. It is useful when you do not know in advance how many times you need to loop.
# Keep counting until we reach 5
count = 0
while count < 5:
print(count) # 0, 1, 2, 3, 4
count += 1
# Ask for input until the user types the right thing
answer = ""
while answer != "quit":
answer = input("Type something (or 'quit' to stop): ")
print(f"You typed: {answer}")
⚠️
Infinite loops: if your while condition never becomes False the loop runs forever and your program hangs. Always make sure something inside the loop will eventually make the condition false. When in doubt, add a maximum iteration counter.
Lists — Ordered Collections
A list is an ordered collection of items stored in one variable. It can hold anything — numbers, strings, other lists, even a mix of types. Lists use square brackets and items are separated by commas.
# Create a list
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30, 40, 50]
mixed = ["hello", 42, True]
# Access items by index — counting starts at 0
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry — -1 means the last item
# Change an item
fruits[1] = "mango" # replaces banana with mango
# Add and remove items
fruits.append("grape") # add to end
fruits.insert(0, "kiwi") # insert at position 0 (start)
fruits.remove("apple") # remove by value
fruits.pop() # remove and return the last item
# Useful list functions
print(len(fruits)) # number of items
print(sum(numbers)) # 150
print(max(numbers)) # 50
print(min(numbers)) # 10
print(sorted(fruits)) # returns a sorted copy
print("apple" in fruits) # True or False — check if item exists
Dictionaries — Key and Value Pairs
A dictionary stores data as key and value pairs. Instead of accessing items by position (like a list), you access them by their key. Think of it like a real dictionary — you look up a word (the key) to find its definition (the value).
# Create a dictionary
person = {
"name": "Shashank",
"age": 25,
"city": "Mumbai",
"hobbies": ["coding", "reading"]
}
# Access values by key
print(person["name"]) # Shashank
print(person["age"]) # 25
# Use .get() — returns None instead of error if key is missing
print(person.get("email")) # None
print(person.get("email", "not set")) # not set
# Add or update a key
person["email"] = "shashank@example.com"
person["age"] = 26 # updates the existing value
# Remove a key
del person["city"]
# Loop through a dictionary
for key, value in person.items():
print(f"{key}: {value}")
# Useful dictionary methods
print(person.keys()) # all keys
print(person.values()) # all values
print("name" in person) # True — check if key exists
Functions — Reusable Blocks of Code
A function is a named block of code that does one specific job. You write it once and can use it as many times as you want. Good functions make your code shorter, more organised and much easier to understand.
Think of a function like a recipe. You write the recipe once. Every time you want to cook that dish, you just follow the recipe instead of figuring it out from scratch every time.
Parameters and Return Values
# Define a function with def
def greet():
print("Hello! Welcome to Hoopsiper.")
# Call the function
greet() # Hello! Welcome to Hoopsiper.
# A function with a parameter
def greet_user(name):
print(f"Hello, {name}! Welcome to Hoopsiper.")
greet_user("Shashank")
greet_user("Priya")
# A function that RETURNS a value you can use
def add(a, b):
return a + b
result = add(3, 7)
print(result) # 10
# A more realistic function
def calculate_discount(price, discount_percent):
discount_amount = price * (discount_percent / 100)
final_price = price - discount_amount
return final_price
sale_price = calculate_discount(1000, 20)
print(f"After 20% discount: ₹{sale_price}") # ₹800.0
Default Arguments
You can give a parameter a default value. If the caller does not pass that argument, the default value is used. This makes functions more flexible.
def create_profile(name, role="Student", active=True):
print(f"Name: {name}, Role: {role}, Active: {active}")
# Call with only the required argument
create_profile("Shashank")
# Name: Shashank, Role: Student, Active: True
# Override specific defaults using keyword arguments
create_profile("Priya", role="Developer")
# Name: Priya, Role: Developer, Active: True
create_profile("Raj", active=False)
# Name: Raj, Role: Student, Active: False
Error Handling — When Things Go Wrong
Errors happen. A user types a word when you expected a number. A file you are trying to read does not exist. Instead of your program crashing with an ugly error message, you can catch the error and handle it gracefully.
# Without error handling — this crashes if user types "abc"
number = int(input("Enter a number: "))
# With error handling — catches the problem and responds nicely
try:
number = int(input("Enter a number: "))
print(f"You entered: {number}")
except ValueError:
print("That is not a valid number. Please try again.")
except ZeroDivisionError:
print("You cannot divide by zero.")
except Exception as e:
print(f"Something unexpected happened: {e}")
finally:
# This ALWAYS runs, success or failure
print("Thanks for using this program!")
✅
Catch specific errors first. Order your except blocks from most specific to most general. ValueError before Exception. This way specific problems get specific responses and only truly unexpected errors fall through to the general handler.
Importing Modules — Using Python's Built-in Tools
Python comes with hundreds of built-in modules — collections of pre-written code that you can use in your own programs. Instead of writing code for common tasks from scratch, you just import a module that already does it.
# math — mathematical functions
import math
print(math.sqrt(16)) # 4.0
print(math.ceil(4.2)) # 5 — round up
print(math.floor(4.9)) # 4 — round down
print(math.pi) # 3.14159...
# random — generating random numbers
import random
print(random.randint(1, 10)) # random int between 1 and 10
print(random.choice(["a", "b", "c"])) # pick randomly from a list
# datetime — working with dates and times
from datetime import datetime
now = datetime.now()
print(now.strftime("%d %B %Y")) # e.g. 15 January 2025
# os — file system operations
import os
print(os.getcwd()) # current working directory
print(os.listdir('.')) # list files in current folder
os.makedirs('my_folder', exist_ok=True) # create a folder
ℹ️
Third-party packages: beyond the standard library, Python has a huge ecosystem of packages you can install with pip. pip install numpy, pip install pandas, pip install flask — these are the commands that unlock data science, web development and much more.
⚡ Key Takeaways
- Python uses indentation (4 spaces) to define code blocks. Everything inside an if, loop or function must be indented correctly or Python will throw an error.
- Create variables with a name and an equals sign. Python figures out the type automatically. Use lowercase names with underscores like user_name or total_price.
- The four basic data types are strings (text in quotes), integers (whole numbers), floats (decimal numbers) and booleans (True or False).
- Use == to compare values (is it equal?) and = to assign values (put this in the box). These are two completely different operations.
- Use if, elif and else to make decisions. Use for loops to go through collections. Use while loops to repeat until a condition changes.
- Lists are ordered collections accessed by index starting at 0. Dictionaries store data as key-value pairs accessed by key name.
- Use f-strings to put variables inside text: f"Hello, {name}!" — the variable goes inside curly braces.
- Write functions to avoid repeating code. Use def to define, return to send a value back, and parameters to pass information in.
- Wrap risky code in try and except blocks so your program handles errors gracefully instead of crashing.
- Use import to bring in Python's built-in modules like math, random, datetime and os. Use pip install to add third-party packages.
Tags:
Python
Beginner
Variables
Functions
Lists
Fundamentals
Shashank Shekhar
Founder & Creator — Hoopsiper.com
Full stack developer and educator. Building Hoopsiper to help developers learn faster through practical, no-fluff coding guides on JavaScript, AI/ML, Python and modern web development.