Algo Infinity Verse

Start Your Journey With Python Programming Beginner-Friendly Concepts, Code & Practice

|
0 Topics
0 Examples
0 Exercises

🐍 Learn Python

Master the fundamentals of Python with clear explanations and hands-on examples

0 / 8 topics completed
01

Introduction to Python

Python is a high-level, interpreted programming language known for its simple, readable syntax. It was created by Guido van Rossum and first released in 1991. Today it powers everything from web apps to AI research.

Why Learn Python?

  • Easy to learn – clean, English-like syntax
  • Versatile – web dev, data science, automation, AI/ML
  • Massive community – tons of libraries and resources
  • In-demand – one of the most sought-after languages in jobs

Your very first Python program is the classic "Hello, World!" — just one line:

Python
print('Hello, World!')
Output
Hello, World!
💡

Python uses indentation (whitespace) to define code blocks instead of curly braces {}. This enforces clean, readable code.

02

Installation & Setup

Follow the steps below to install Python on your machine. Most systems come with Python pre-installed, but it's best to verify you have a recent version (3.9+).

macOS

Install via Homebrew (recommended):

Bash
brew install python3

Windows

Download the installer from python.org/downloads and check "Add Python to PATH" during installation.

Linux

Most distributions include Python. Install or update via your package manager:

Bash
sudo apt update && sudo apt install python3

Verify your installation by running python3 --version in your terminal.

Bash
python3 --version
# Expected: Python 3.11.x (or newer)

You can also use the Python REPL (Read-Eval-Print Loop) by simply typing python3 in your terminal to start writing code interactively.

03

Variables & Data Types

Variables are named containers that store data. In Python, you don't need to declare a type — the interpreter figures it out automatically.

Python
name = "Alice"       # str
age = 25              # int
height = 5.7          # float
is_student = True     # bool

print(type(name))
print(type(age))
Output
<class 'str'>
<class 'int'>
Type Example Description
int42Whole numbers
float3.14Decimal numbers
str"hello"Text (strings)
boolTrue / FalseBoolean values
list[1, 2, 3]Ordered, mutable collection
dict{"key": "val"}Key-value pairs
💡

Use type() to check a variable's type, and len() to get the length of a string, list, or dictionary.

Practice: Variables & Data Types

Create variables of each basic type (int, float, str, bool), then print their values and types.

  1. Create an integer variable score with value 95
  2. Create a float variable gpa with value 3.85
  3. Create a string variable city with value "New York"
  4. Create a boolean passed set to True
  5. Print each variable and its type()
Python
score = 95
gpa = 3.85
city = "New York"
passed = True

print(f"Score: {score} ({type(score).__name__})")
print(f"GPA: {gpa} ({type(gpa).__name__})")
print(f"City: {city} ({type(city).__name__})")
print(f"Passed: {passed} ({type(passed).__name__})")
04

Input & Output

Every interactive program needs to read input and display output. Python provides input() and print() for this.

print() — Displaying Output

The print() function outputs text to the console. You can separate values with sep and end with end.

Python
name = "Alice"
age = 25

# f-strings (formatted string literals)
print(f"My name is {name} and I am {age} years old.")

# Multiple values
print("Name:", name, "| Age:", age)
Output
My name is Alice and I am 25 years old.
Name: Alice | Age: 25

input() — Reading User Input

The input() function pauses the program and waits for the user to type something. It always returns a string.

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

# Convert input to integer
age = int(input("How old are you? "))
print(f"In 10 years you will be {age + 10}.")
⚠️

input() always returns a str. Wrap it with int() or float() to use it as a number.

Practice: Input & Output

Build a simple greeting program:

  1. Ask the user for their name using input()
  2. Ask for their favorite color
  3. Print a message: "Hello {name}, your favorite color is {color}!"
Python
name = input("Enter your name: ")
color = input("Enter your favorite color: ")
print(f"Hello {name}, your favorite color is {color}!")
05

Conditional Statements

Conditionals let your program make decisions. Python uses if, elif, and else to branch execution based on conditions.

Python
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Score: {score} → Grade: {grade}")
Output
Score: 85 → Grade: B

Comparison Operators

  • == equal to
  • != not equal to
  • >, <, >=, <= — greater/less than
  • and, or, not — logical operators
Python
age = 20
has_id = True

if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")
Practice: Conditionals

Write a program that:

  1. Reads a number from the user
  2. Prints "Positive" if it's greater than 0
  3. Prints "Negative" if it's less than 0
  4. Prints "Zero" if it's exactly 0
Python
num = float(input("Enter a number: "))

if num > 0:
    print("Positive")
elif num < 0:
    print("Negative")
else:
    print("Zero")
06

Loops

Loops let you repeat a block of code multiple times. Python has two main loop types: for and while.

for Loop — Iterating Over a Sequence

Use for when you know how many times to loop or are iterating over a collection.

Python
# Iterate over a range
for i in range(5):
    print(f"Count: {i}")

# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
apple
banana
cherry

while Loop — Repeating Until a Condition is False

Use while when you don't know the exact number of iterations.

Python
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1
⚠️

Be careful with while loops — always make sure the condition eventually becomes False to avoid infinite loops.

Python
# Break and Continue
for i in range(10):
    if i == 3:
        continue    # skip 3
    if i == 7:
        break       # stop at 7
    print(i)
Output
0
1
2
4
5
6
Practice: Loops

Write two programs:

  1. Use a for loop to print all even numbers from 1 to 20
  2. Use a while loop to find the sum of numbers from 1 to 100
Python
# Even numbers 1-20
for i in range(1, 21):
    if i % 2 == 0:
        print(i)

# Sum of 1 to 100
total = 0
num = 1
while num <= 100:
    total += num
    num += 1
print(f"Sum: {total}")
07

Functions

Functions are reusable blocks of code that perform a specific task. They help you avoid repetition and keep your code organized.

Python
def greet(name):
    """Greet a user by name."""
    return f"Hello, {name}!"

# Call the function
message = greet("Alice")
print(message)
Output
Hello, Alice!

Default Parameters & Multiple Returns

You can set default values for parameters and return multiple values using tuples.

Python
def calculate(a, b, operation="add"):
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b

print(calculate(10, 5))              # 15 (default: add)
print(calculate(10, 5, "multiply"))  # 50

def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([3, 1, 7, 2, 9])
print(f"Min: {lo}, Max: {hi}")
Output
15
50
Min: 1, Max: 9
Practice: Functions
  1. Write a function is_even(n) that returns True if n is even, False otherwise
  2. Write a function factorial(n) that returns the factorial of n
  3. Write a function reverse_string(s) that returns the reversed string
Python
def is_even(n):
    return n % 2 == 0

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

def reverse_string(s):
    return s[::-1]

print(is_even(4))        # True
print(factorial(5))      # 120
print(reverse_string("hello"))  # olleh
08

Lists & Dictionaries

Lists and dictionaries are Python's most commonly used data structures. Lists hold ordered sequences; dictionaries store key-value pairs.

Lists — Ordered & Mutable

Lists can hold any data type and can be modified after creation.

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

# Access
print(fruits[0])       # apple
print(fruits[-1])      # cherry

# Modify
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.remove("banana")

print(fruits)
print(f"Length: {len(fruits)}")
Output
apple
cherry
['apple', 'blueberry', 'cherry', 'date']
Length: 4

List Slicing

Slice syntax: list[start:stop:step] — extract a portion of a list without modifying the original.

Python
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(nums[2:5])     # [2, 3, 4]
print(nums[:4])      # [0, 1, 2, 3]
print(nums[::2])     # [0, 2, 4, 6, 8]
print(nums[::-1])    # [9, 8, 7, ... 0] (reversed)

Dictionaries — Key-Value Pairs

Dictionaries store data as key: value pairs. Keys must be immutable (strings, numbers, tuples).

Python
person = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}

# Access values
print(person["name"])         # Alice
print(person.get("age", 0))   # 25

# Add / update
person["email"] = "alice@mail.com"
person["age"] = 26

# Iterate
for key, value in person.items():
    print(f"{key}: {value}")
Output
Alice
25
name: Alice
age: 26
city: New York
email: alice@mail.com
Practice: Lists & Dictionaries
  1. Create a list of 5 numbers and print their sum and average
  2. Create a dictionary representing a book (title, author, pages, genre) and print each field
  3. Write a function that takes a list and returns a dictionary with each element as a key and its count as the value
Python
# Sum and average
nums = [10, 20, 30, 40, 50]
total = sum(nums)
avg = total / len(nums)
print(f"Sum: {total}, Average: {avg}")

# Book dictionary
book = {
    "title": "1984",
    "author": "George Orwell",
    "pages": 328,
    "genre": "Dystopian"
}
for key, value in book.items():
    print(f"{key}: {value}")

# Count elements
def count_elements(lst):
    counts = {}
    for item in lst:
        counts[item] = counts.get(item, 0) + 1
    return counts

print(count_elements(["a", "b", "a", "c", "b", "a"]))