Chapter 1 of 14

Python Fundamentals

Learn the basics of Python — installation, variables, data types, input/output, comments, and your first programs.

Meritshot11 min read
PythonBasicsVariablesGetting Started
All Python Chapters

What is Python?

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasises code readability with its use of significant whitespace and clean syntax that reads almost like English.

Python is used across virtually every domain in technology:

  • Web Development — Django, Flask, FastAPI
  • Data Science & Analytics — pandas, NumPy, Matplotlib
  • Machine Learning & AI — TensorFlow, PyTorch, scikit-learn
  • Automation & Scripting — automating repetitive tasks, file processing
  • DevOps — infrastructure automation, CI/CD pipelines
  • Finance — algorithmic trading, risk modelling, quantitative analysis

Why Learn Python?

Python has consistently ranked as the #1 most popular programming language (TIOBE Index, Stack Overflow Survey, GitHub Octoverse). Here's why:

AdvantageDetails
Easy to learnClean syntax close to plain English — ideal first language
Huge ecosystem400,000+ packages on PyPI for every use case imaginable
High demandOne of the most in-demand skills for data, AI, and backend roles
VersatileOne language for web, data, ML, scripting, and automation
Strong communityMassive community support, tutorials, and Stack Overflow answers
Cross-platformRuns on Windows, macOS, Linux without modification

Installing Python

Check if Python is Already Installed

Open your terminal (or Command Prompt on Windows) and type:

python3 --version

If you see something like Python 3.12.x, you're good to go.

Installing Python

  1. Visit python.org/downloads
  2. Download the latest Python 3.x version for your OS
  3. During installation on Windows, check "Add Python to PATH"
  4. Verify installation: python3 --version

Using an IDE

While you can write Python in any text editor, we recommend:

  • VS Code — free, lightweight, excellent Python extension
  • PyCharm — full-featured Python IDE (Community Edition is free)
  • Jupyter Notebook — great for data science and experimentation
  • Google Colab — free cloud-based Jupyter notebooks (no setup needed)

Your First Python Program

Create a file called hello.py and add:

print("Hello, World!")

Run it from the terminal:

python3 hello.py

Output:

Hello, World!

Congratulations — you've written your first Python program! The print() function outputs text to the screen.

Printing Multiple Values

print("Hello", "World", "Python")    # Hello World Python
print("Hello", "World", sep=", ")    # Hello, World
print("Line 1")
print("Line 2")
print("Same", end=" ")
print("Line")                         # Same Line

The print() function accepts:

  • Multiple arguments — separated by spaces by default
  • sep — custom separator between arguments
  • end — what to print at the end (default is \n newline)

Variables and Assignment

A variable is a name that refers to a value stored in memory. In Python, you create a variable by assigning a value with =.

# Creating variables
name = "Meritshot"
age = 5
pi = 3.14159
is_active = True
nothing = None

Python is dynamically typed — you don't need to declare the type. Python infers it automatically.

x = 10          # x is an int
x = "hello"     # now x is a str — perfectly valid in Python
x = [1, 2, 3]   # now x is a list

Variable Naming Rules

RuleValidInvalid
Start with letter or _name, _count2name, -val
Contains letters, digits, _score_1, total2my-var, my var
Case-sensitiveNamename
Not a Python keywordmy_classclass, if, for

Naming Conventions

# Good naming
student_name = "Priya"       # snake_case for variables
MAX_RETRIES = 3              # UPPER_CASE for constants
total_score = 0              # descriptive names
is_valid = True              # boolean prefix: is_, has_, can_

# Bad naming
x = "Priya"                  # not descriptive
studentName = "Priya"        # camelCase (not Pythonic)
a = 3                        # meaningless

Convention: Python uses snake_case for variables and functions, PascalCase for classes, and UPPER_CASE for constants.

Multiple Assignment

# Assign same value to multiple variables
a = b = c = 0
print(a, b, c)  # 0 0 0

# Assign different values in one line
x, y, z = 10, 20, 30
print(x, y, z)  # 10 20 30

# Swap variables (no temp variable needed!)
a, b = 1, 2
a, b = b, a
print(a, b)  # 2 1

Python Keywords (Reserved Words)

These words have special meaning and cannot be used as variable names:

import keyword
print(keyword.kwlist)

Common keywords: if, else, elif, for, while, def, class, return, import, from, True, False, None, and, or, not, in, is, try, except, finally, with, as, lambda, yield, global, nonlocal, break, continue, pass, raise, del.

Data Types Overview

Every value in Python has a type. Here's a quick overview (each type is covered in depth in later chapters):

TypeCategoryExampleDescription
intNumeric42, -7Whole numbers (no size limit)
floatNumeric3.14, -0.5Decimal numbers
complexNumeric3+4jComplex numbers
strText"hello"Text strings
boolBooleanTrue, FalseLogical values
listSequence[1, 2, 3]Ordered, mutable collection
tupleSequence(1, 2, 3)Ordered, immutable collection
dictMapping{"a": 1}Key-value pairs
setSet{1, 2, 3}Unordered, unique elements
NoneTypeNoneNoneRepresents "no value"
# Check the type of any value
print(type(42))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("hello"))     # <class 'str'>
print(type(True))        # <class 'bool'>
print(type([1, 2]))      # <class 'list'>
print(type(None))        # <class 'NoneType'>

Input and Output

Output with print()

# Basic output
print("Welcome to Meritshot!")

# Printing variables
name = "Priya"
age = 22
print("Name:", name)
print("Age:", age)

# f-string formatting (recommended)
print(f"Name: {name}, Age: {age}")

# Number formatting
price = 1299.5
print(f"Price: ₹{price:,.2f}")     # Price: ₹1,299.50
print(f"Percentage: {0.856:.1%}")   # Percentage: 85.6%

# Padding and alignment
print(f"{'left':<20}")    # left-aligned, 20 chars wide
print(f"{'right':>20}")   # right-aligned
print(f"{'center':^20}")  # center-aligned

Input from the User

The input() function reads a line of text from the user. It always returns a string.

name = input("What is your name? ")
print(f"Hello, {name}!")

# input() always returns a string, so convert for numbers
age_str = input("Enter your age: ")
age = int(age_str)                   # convert string to int
print(f"Next year you'll be {age + 1}")

# One-liner conversion
height = float(input("Enter your height in metres: "))
print(f"Your height is {height}m")

Practical Example: Simple Calculator

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

print(f"\n--- Results ---")
print(f"{num1} + {num2} = {num1 + num2}")
print(f"{num1} - {num2} = {num1 - num2}")
print(f"{num1} × {num2} = {num1 * num2}")

if num2 != 0:
    print(f"{num1} ÷ {num2} = {num1 / num2:.2f}")
else:
    print("Cannot divide by zero!")

Comments

Comments help explain your code. Python ignores them during execution.

Single-Line Comments

# This is a single-line comment
name = "Priya"  # This is an inline comment

# You can use comments to temporarily disable code:
# print("This line won't execute")

Multi-Line Comments (Docstrings)

Python doesn't have a dedicated multi-line comment syntax, but you can use triple-quoted strings:

"""
This is a multi-line comment.
It can span as many lines as you need.
Often used as docstrings for functions and classes.
"""

def calculate_area(radius):
    """
    Calculate the area of a circle.

    Args:
        radius: The radius of the circle

    Returns:
        The area as a float
    """
    return 3.14159 * radius ** 2

When to Comment

# Good comments explain WHY, not WHAT
# Calculate discount for loyalty members (business rule: 15% after 2 years)
discount = 0.15 if years_active > 2 else 0

# Bad comment — just restates the code
# Set x to 5
x = 5

Indentation

Python uses indentation (whitespace) to define code blocks — there are no curly braces {} like in C or JavaScript. This is one of Python's most distinctive features.

# Correct — consistent 4-space indentation
if True:
    print("This is inside the if block")
    print("So is this")
print("This is outside")

# WRONG — inconsistent indentation causes IndentationError
# if True:
#     print("4 spaces")
#       print("6 spaces")  # IndentationError!

Standard: Use 4 spaces per indentation level. Never mix tabs and spaces. Most editors can be configured to insert 4 spaces when you press Tab.

Type Conversion

Since input() returns strings and you often need numbers, type conversion is essential:

# String to int
age = int("25")

# String to float
price = float("19.99")

# Number to string
text = str(100)
label = str(3.14)

# Float to int (truncates — does NOT round)
whole = int(3.99)   # 3 (not 4)
whole = int(-3.99)  # -3

# Rounding
rounded = round(3.7)      # 4
rounded = round(3.14159, 2)  # 3.14

# Boolean conversion
print(bool(0))        # False
print(bool(42))       # True
print(bool(""))       # False
print(bool("hello"))  # True
print(bool([]))       # False
print(bool([1, 2]))   # True

String Basics (Preview)

Strings get their own full chapter later, but here are the essentials:

# Creating strings
single = 'Hello'
double = "Hello"
triple = """Multi
line string"""

# String concatenation
first = "Merit"
last = "shot"
full = first + last      # "Meritshot"
repeated = "Ha" * 3      # "HaHaHa"

# String length
print(len("Python"))     # 6

# Accessing characters (zero-indexed)
language = "Python"
print(language[0])       # P
print(language[-1])      # n
print(language[0:3])     # Pyt (slicing)

# Common methods
text = "  Hello, World!  "
print(text.strip())      # "Hello, World!" (removes whitespace)
print(text.strip().lower())   # "hello, world!"
print(text.strip().upper())   # "HELLO, WORLD!"
print("Python" in text)       # False

Practical Examples

Example 1: Temperature Converter

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32

print(f"\n{celsius}°C = {fahrenheit:.1f}°F")

if fahrenheit > 100:
    print("That's really hot!")
elif fahrenheit < 32:
    print("Below freezing!")
else:
    print("Comfortable temperature.")

Example 2: BMI Calculator

weight = float(input("Enter your weight (kg): "))
height = float(input("Enter your height (m): "))

bmi = weight / (height ** 2)
print(f"\nYour BMI: {bmi:.1f}")

if bmi < 18.5:
    print("Category: Underweight")
elif bmi < 25:
    print("Category: Normal weight")
elif bmi < 30:
    print("Category: Overweight")
else:
    print("Category: Obese")

Example 3: Simple Interest Calculator

principal = float(input("Enter principal amount (₹): "))
rate = float(input("Enter annual interest rate (%): "))
time = float(input("Enter time period (years): "))

interest = (principal * rate * time) / 100
total = principal + interest

print(f"\n--- Results ---")
print(f"Principal:  ₹{principal:,.2f}")
print(f"Interest:   ₹{interest:,.2f}")
print(f"Total:      ₹{total:,.2f}")

Common Beginner Mistakes

1. Forgetting to Convert Input

# Wrong — comparing string with number
age = input("Age: ")
if age > 18:      # TypeError!
    print("Adult")

# Correct
age = int(input("Age: "))
if age > 18:
    print("Adult")

2. Incorrect Indentation

# Wrong
if True:
print("Hello")    # IndentationError

# Correct
if True:
    print("Hello")

3. Using = Instead of ==

# Wrong — assignment, not comparison
if x = 5:        # SyntaxError

# Correct — comparison
if x == 5:
    print("x is 5")

4. Forgetting Quotes Around Strings

# Wrong
name = Priya      # NameError: name 'Priya' is not defined

# Correct
name = "Priya"

Practice Exercises

  1. Write a program that asks for the user's name and age, then prints: "Hello [name], you will be [age+1] next year!"
  2. Create a program that converts kilometres to miles (1 km = 0.621371 miles)
  3. Write a program that takes the radius of a circle and prints its area and circumference
  4. Create a tip calculator: take a bill amount and tip percentage, then print the tip and total
  5. Write a program that takes seconds as input and converts it to hours, minutes, and seconds

Summary

In this chapter, you learned:

  • What Python is and where it's used in the industry
  • How to install Python and set up your development environment
  • Writing and running your first Python program
  • Variables: creation, naming rules, conventions, and multiple assignment
  • Python's core data types at a glance
  • print() for output and input() for user input
  • f-strings for formatted output
  • Comments and docstrings
  • Indentation rules
  • Type conversion between strings, numbers, and booleans
  • Practical programs: temperature converter, BMI calculator, interest calculator
  • Common beginner mistakes and how to avoid them

Next up: Operators — learn how to perform calculations, comparisons, and logical operations in Python.