Python – a Quick Tutorial

This tutorial is designed to get you up and running with the essentials of Python very quickly. Python is a high-level, readable language that uses indentation (spaces) instead of curly braces {} to define code blocks.

On Linux, Python is already installed in most cases. On Windows, you may install it from Python Releases for Windows | Python.org or Download Anaconda Distribution | Anaconda. On Windows 11, you may also directly install it from Windows Store.

After you’ve got it installed on your system, start Python shell either by clicking on its shortcut in the menu or by running command python3 at a command prompt. A Python shell presents a bare minimum environment to execute Python code. So, enter following command and hit Enter:

print("Hello World!")

Congrats! you’ve written first Python program using print() output function.

Next, write following lines and see how programming is essentially mathematics packaged around some linguistic wrappers (known as syntax):

a = 3
b = 4
c = a + b
print(c)

We’ve used print() output function, let’s introduce an input() function. For this, we’ll up the ante and start using source files instead of Python shell. So, close Python shell by entering exit() command.

Now, let’s fire up a text editor, write following code, and save it as first.py:

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

Assuming you’re on the command prompt and first.py is in your current location, enter following command:

python3 first.py

Ok, we’ve handshaked with Python. Now, let’s move on topic-wise:

1. Variables and Data Types

Variables are data holders as you saw above (a, b, c). In programming variables can be of many types like integer, float, alphanumeric (string), boolean (true / false) and other advance types like date.

# Numbers
age = 30          # Integer (int)
pi = 3.14         # Floating-point (float)

# Text & Boolean
name = "Alice"    # String (str)
is_active = True  # Boolean (bool)


In Python, you don’t need to declare variable types explicitly; Python infers them automatically. Copy following into another file named second.py and then run as explained above:

a = 30
b = 3.14
c = a * b
print(c)

As you can see the Python Interpreter automatically assigns a as integer, then b and c as float.

You can explicitly convert types too (type casting), like:

# Type conversion
count = int("42") # converting string to integer
count = count + 3
print(count)

2. Data Structures

Python has built-in collections to store multiple items in a single variable.

Lists (Ordered, mutable, allows duplicates)

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[0]) # Output: apple
print(fruits[3]) # Output: orange

Dictionaries (Key-Value pairs, mutable)

user = {
    "name": "Bob",
    "age": 25
}
print(user["name"]) # Output: Bob

Tuples

Tuples are used to store multiple items in a single variable, but unlike lists, they cannot be changed (immutable) after they are created. They are perfect for data that should never change, like GPS coordinates or RGB color codes.

coordinates = (10, 20)
# coordinates[0] = 15  # This would throw a TypeError!

colors = ("red", "green", "blue", "red")  # Allows duplicate values
print(colors[1])  # Output: green
print(len(colors))  # Output: 4

Sets

Sets are used to store multiple items where duplicates are strictly not allowed, and the order of items does not matter. If you try to add a duplicate item, Python will simply ignore it.

unique_ids = {1, 2, 3, 3}  # The duplicate '3' is automatically removed
print(unique_ids)  # Output: {1, 2, 3}

3. Control Flow

Python relies heavily on indentation (usually 4 spaces) to structure logic.

Conditionals (if-elif-else)

Decision making is done through if-else structure:

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
else:
    print("Grade: C")

We could assign value using if-else condition:

num = int(input("Enter a number:"))
res = "Even" if num % 2 == 0 else "Odd"
print(res)

(Hint: % is remainder operator (not divide); obviously, if remainder is 0 after a number is divided by 2, then it’s ‘even’ number.)

Loops

For loop is used for iterating over a range or collection:

# For loop (iterating over a range or collection)
for i in range(3):
    print(i)

fruits = ["apple", "banana", "cherry"]
for f in fruits:
    print(f)

While is used when exact number of iterations is not known beforehand. The loop keeps going until a condition is met:

# While loop (runs while a condition is True)
count = 0
while count < 3:
    print(count)
    count += 1

4. Functions

Use the def keyword to create reusable blocks of code.

def greet(username="Guest"):
    return f"Hello, {username}!"

# Calling the function
message = greet("Alex")
print(message) # Output: Hello, Alex!

5. List Comprehensions

A concise, “Pythonic” way to create lists from existing lists.

numbers = [1, 2, 3, 4]
# Squares of even numbers
squares = [x**2 for x in numbers if x % 2 == 0]
print(squares) # Output: [4, 16]

6. Error Handling

Prevent your program from crashing when exceptions occur using try-except.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero!")
finally:
    print("This always runs.")

7. Object-Oriented Programming (OOP)

Python supports object-oriented programming using classes and objects.

class Dog:
    # Constructor method
    def __init__(self, name):
        self.name = name # Instance variable

    def bark(self):
        return f"{self.name} says woof!"

# Creating instances (objects) of class Dog
my_dog = Dog("Buddy")
print(my_dog.bark()) # Output: Buddy says woof!
my_second_dog = Dog("Tommy")
print(my_second_dog.bark()) # Output: Tommy says woof!

8. Modules and Packages

To use code written by others (or your own in separate files), use import.

import math
from datetime import datetime

print(math.sqrt(16))      # Output: 4.0
print(datetime.now().year) # Output: 2026

Modules and packages are what make your life easy as programmer. You don’t have to reinvent the wheel; just import a package and start solving your business problem. In next tutorial, we’ll use Tkinter GUI and SQLite3 modules to quickly build a GUI app which talks to a database; there you’ll see the magic of using different modules and packages.

Leave a Comment