Home Python Programming Language
Post
Cancel
Python Programming Language | SEG

Python Programming Language

This is part 3 of our Programming Languages series. This post focuses on Python Programming Language.

Getting Started with Python

Today, we’re diving into one of the most accessible and widely-used programming languages around, Python. Whether you’re automating everyday tasks, analyzing data, building web applications, or just curious about how code can shape the world, Python is a superb starting point.

What Makes Python Worth Learning?

Python’s popularity isn’t accidental, it thrives on a foundation of simplicity and power:

  • Beginner-friendly syntax: Clean, readable code that feels almost like writing English. Perfect for first-timers.
  • Cross-platform compatibility: Python runs seamlessly on Windows, macOS, Linux, and more, with minimal tweaks.
  • Vast ecosystem and community: With millions of developers and countless libraries, there’s a package for almost anything.
  • High demand across industries: From startups to big tech and finance to healthcare, Python skills are constantly in demand.
  • Rapid development: Write less, do more. Python allows for fast prototyping and agile workflows.

Python is also a multi-paradigm language, supporting:

  • Object-oriented programming
  • Functional programming
  • Procedural scripting
  • Asynchronous and concurrent programming

This flexibility allows developers to pick the right tool and style for the job.

Let’s Talk IDEs: Your Coding Cockpit

An IDE (Integrated Development Environment) is like mission control for developers. It brings together everything you need to write, run, debug, and test your code, all in one streamlined interface.

Popular choices for Python include:

  • PyCharm (our pick for today)
  • VS Code
  • Thonny
  • JupyterLab

Why bother with an IDE? For speed, structure, and sanity. A good IDE helps catch errors early, offers smart code suggestions, and keeps your projects neat and navigable.

Building Your First Python Project in PyCharm

  1. Create a New Project: Open PyCharm and click on New Project.
  2. Select Python Interpreter: Choose a Python interpreter. If you don’t have one installed, PyCharm will guide you through setting it up. We’re using Python 3.11.
  3. Name Your Project: Give it a name like simple_project. PyCharm sets up your working directory and initial structure.
  4. Create Your First Script: Right-click on the project folder, select New > Python File, and name it main.py.

Here’s the simplest Python program:

1
print("Hello, world")

Click the green Run button or right-click the file and select Run ‘main’.

Boom, your first Python output.

Under the Hood: Interpretation and Bytecode

Python is an interpreted language, but it still compiles your code, just a bit differently. When you run a Python script, it’s first converted into bytecode, which is executed by the Python Virtual Machine (PVM). This layer of abstraction makes Python both portable and flexible across platforms.

Python Syntax 101

Comments

Comments clarify what your code is doing—for you and anyone else reading it. Python supports single-line and multi-line comments using a simple syntax:

1
2
3
4
5
6
7
8
9
10
11
# This is a single-line comment

"""
This is a multi-line comment.
Useful for longer explanations or documentation.
"""

'''
This is also a multi-line comment.
Python accepts both triple double-quotes and triple single-quotes.
'''

Variables & Types

In Python, variables are names that store data. Unlike Java, Python is dynamically typed, which means you don’t need to declare a type up front, Python figures it out at runtime. This makes coding faster and more flexible, especially in early development.

Python has several built-in data types, often grouped into:

  • Primitive types – the basics like int, float, and bool.
  • Composite types – collections like str, list, tuple, dict, and set.

There’s no need to explicitly specify types:

1
2
3
age = 25        # int
price = 19.99   # float
is_valid = True # bool

Python’s simplicity here means fewer declarations and more focus on logic, though you can use type hints for added clarity and tooling support.

Primitive Types

Primitive types in Python are the fundamental building blocks of data. While technically everything in Python is an object, these types behave like raw data and are used extensively.

TypeDescriptionExample
intStores whole numbersx = 5
floatStores decimal (floating point) numberspi = 3.14
boolStores true/false valuesis_python_fun = True

Python abstracts away low-level memory management, so you can focus on writing logic rather than optimizing for space, though these types remain efficient under the hood.

Composite Types

Composite types in Python are more complex data structures built from classes. They can store multiple values, represent structured data, and come with built-in methods for manipulation.

1. String
1
greeting = "Hello"

A str in Python is a sequence of characters and supports a wide range of methods like .upper(), .lower(), .replace(), and .split().

2. Lists
1
numbers = [10, 20, 30, 40]

A list can hold multiple values, even of different types. Lists are dynamic in size and allow operations like appending, slicing, and iterating.

3. Objects and Custom Classes
1
2
3
4
5
6
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 28)

In Python, you can define your own classes and create objects from them. These structures help encapsulate data and behavior, making code more reusable and maintainable.

Type Casting: Converting Between Types

In Python, type casting lets you convert values from one data type to another, like turning a number into a string, or a float into an integer. This is especially useful when you’re mixing input types or preparing data for output or storage.

Python doesn’t differentiate between widening or narrowing conversions in the same way Java does. Instead, you explicitly call built-in functions to perform type casting.

1. Casting to float or int

1
2
3
4
5
num = 10
d = float(num)  # Converts int to float: 10.0

pi = 3.14
truncated = int(pi)  # Converts float to int: 3

Note: When casting a float to an int, the decimal portion is truncated, not rounded.

2. Casting to str

1
2
age = 25
text = str(age)  # "25"

This is handy for string concatenation or output formatting.

3. Casting to bool

1
2
flag = bool(0)    # False
flag = bool(123)  # True

Any non-zero number or non-empty object evaluates to True; zero and empty values evaluate to False.

When to Use Casting

  • Cast to float or int when working with mixed numeric data.
  • Cast to str when preparing user-facing output or logging.
  • Cast to bool for conditional logic and filtering.

Python’s casting is straightforward, readable, and puts the control in your hands, ideal for flexible, data-driven programming.

Operators: Arithmetic & Logic

In Python, operators are symbols that let you perform operations on variables and values. Whether you’re crunching numbers or making decisions, operators are essential for everyday coding.

Let’s focus on arithmetic and logical operators, your go-to tools for calculations and conditionals.

Arithmetic Operators

These perform basic math:

1
2
3
4
5
6
7
8
a = 10
b = 3

print(a + b)  # 13
print(a - b)  # 7
print(a * b)  # 30
print(a / b)  # 3.333...
print(a % b)  # 1
  • + adds two numbers
  • - subtracts one number from another
  • * multiplies
  • / divides and always returns a float
  • % (modulus) gives the remainder

Note on Division: In Python, even if both operands are integers, / will return a floating-point result. Use // for integer division (e.g., 10 // 3 gives 3).

Logical and Comparison Operators

These return True or False based on how values relate, essential for control structures like if, while, and for.

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b
andLogical AND (both true)a > 5 and b < 5
orLogical OR (at least one true)a > 5 or b < 5
notLogical NOT (inverts boolean)not (a == b)

Example:

1
2
3
4
print(a > b)             # True
print(a == 10)           # True
print(a > 5 and b < 5)   # False
print(not (a == b))      # True

These operators form the backbone of logic in your code, crucial for decision-making, branching, and loops.

Strings

In Python, a str is one of the most commonly used data types, representing a sequence of characters. Strings are actually objects in Python, packed with methods for processing and transforming text.

You can create a string by enclosing characters in either single or double quotes:

1
text = "Python"

Once defined, you have access to a rich set of methods for working with that string.

Common String Methods

1
2
3
4
5
6
text = "Python"

print(len(text))               # 6
print(text.upper())            # PYTHON
print(text.index('t'))         # 2
print(text + " is cool")       # Python is cool

Explanation:

  • len(text) — Returns the number of characters in the string (6 here).
  • .upper() — Converts all characters to uppercase. The original string stays unchanged.
  • .index('t') — Returns the index of the first 't'. Indexing starts at 0.
  • + — Concatenates strings. Python doesn’t use .concat()—just use +.

Important Note: Like Java, strings in Python are immutable. Methods like .upper() or concatenation create new strings, leaving the original untouched.

Strings are everywhere in Python, from output and file handling to web APIs and data analysis. Their immutability makes them reliable and safe for use in many contexts, especially when dealing with concurrent or multithreaded code.

Math

Python gives you access to math functions from two sources: built-in functions and the math module. Built-in functions are available out of the box. For more advanced operations, you’ll want to use math, a standard module that expands your toolbox.

Built-in Math Functions

These don’t require any import and handle common tasks:

1
2
3
4
print(max(10, 20))     # 20
print(min(5, 3))       # 3
print(abs(-7))         # 7
print(round(2.6))      # 3

Explanation:

  • max() and min() — Return the largest or smallest value.
  • abs() — Returns the absolute value.
  • round() — Rounds to the nearest integer.

The math Module

For more specialized calculations, import Python’s math module:

1
2
3
4
import math

print(math.sqrt(16))     # 4.0
print(math.pow(2, 3))    # 8.0

Explanation:

  • math.sqrt() — Returns the square root of a number.
  • math.pow() — Raises a number to a power (returns a float).

Pro Tip: Functions from the math module typically return float values, even if both inputs are integers. Cast with int() if you need whole numbers.

Whether you’re crunching numbers or writing simulations, these tools help you write precise and efficient mathematical logic.

Booleans

In Python, a boolean (bool) is a data type that can hold one of two values: True or False. Though simple, booleans are essential for decision-making, controlling everything from conditionals to loops.

Declaring and Using a Boolean

1
2
3
4
is_logged_in = True

if is_logged_in:
    print("Welcome back!")

Explanation:

  • is_logged_in stores a boolean value (True).
  • The if statement evaluates this value.
  • If the condition is True, the indented block runs, and it prints a message.

Tip: Boolean variable names often begin with is, has, or can; like is_active, has_access, or can_edit. This naming convention makes your code easier to read.

Common Boolean Expressions

Booleans often result from comparisons or logical expressions:

1
2
age = 20
is_adult = age >= 18  # True
1
is_eligible = age >= 18 and age <= 65  # True

These expressions evaluate to True or False and can be used directly in control statements like if, while, and list filters.

If … Else

In Python, if, elif, and else statements are used to control the flow of your program based on conditions. These conditional statements allow your code to make decisions, executing different blocks depending on whether a condition is True or False.

Basic Example

1
2
3
4
5
6
7
8
score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("Try harder")

Explanation:

  • Python checks score >= 90. Since it’s False, that block is skipped.
  • Next, it checks score >= 80, which is True, so it prints "B".
  • The final else acts as a fallback, only running if all previous conditions are False.

When to Use

Use if ... else when:

  • You want to take different actions for different scenarios.
  • Each condition is exclusive, and only one block should run.

More Realistic Example

1
2
3
4
5
6
7
8
temperature = 30

if temperature > 35:
    print("It's very hot!")
elif temperature >= 20:
    print("Nice weather.")
else:
    print("It's cold outside.")

This mirrors real-life decision-making, showing how elif allows you to branch into multiple logic paths.

Tip: Use logical operators (and, or, not) or nested if statements to build more complex conditions.

Here’s the Python version of that section, tailored for how Python handles similar scenarios:


Match (Switch Equivalent)

Python doesn’t have a traditional switch statement like Java, but starting with Python 3.10, it introduced the match statement, a modern, powerful alternative that allows you to handle multiple specific values of a variable cleanly and readably.

Example

1
2
3
4
5
6
7
8
9
10
11
day = 3

match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case _:
        print("Other day")

Explanation:

  • The variable day is matched against the listed cases.
  • When a match is found (case 3), the corresponding block runs, printing "Wednesday".
  • The _ case is the default fallback, similar to Java’s default.

When to Use match

  • When checking a single variable against specific constant values.
  • When you want more structured and readable logic than multiple if-elif-else statements.

Real-World Example

1
2
3
4
5
6
7
8
9
10
11
role = "admin"

match role:
    case "admin":
        print("Access to all features")
    case "editor":
        print("Can edit content")
    case "viewer":
        print("Read-only access")
    case _:
        print("Unknown role")

Tip: The match statement is available in Python 3.10 and later. If you’re using an earlier version, stick with if-elif-else.

While Loop

In Python, the while loop is a control structure that repeats a block of code as long as a condition is True. It’s especially useful when you don’t know in advance how many times the loop should run.

Basic Example

1
2
3
4
i = 0
while i < 3:
    print(f"Count: {i}")
    i += 1

Explanation:

  • Python checks the condition i < 3.
  • If True, it enters the loop, prints the count, and increments i.
  • Once i reaches 3, the condition becomes False and the loop exits.

Key point: If the condition is False from the start, the loop body won’t execute at all.

Use Cases

Use a while loop when:

  • You don’t know beforehand how many times you’ll need to repeat.
  • You’re waiting on something external, like user input, network responses, or file availability.

Real-World Example

1
2
3
4
input_text = ""

while input_text != "exit":
    input_text = input("Type 'exit' to quit: ")

Explanation: This loop keeps asking the user for input until they type "exit". A classic pattern for command loops, menus, and background polling.

Watch out for infinite loops. If the condition never becomes False, the loop will keep running until forcibly stopped.

For Loop

In Python, the for loop is one of the most versatile and widely used control structures. It’s ideal when you know how many times you want to repeat something, especially when working with sequences like lists, strings, or ranges.

Basic Example

1
2
for i in range(3):
    print(f"For count: {i}")

Explanation:

  • range(3) generates the sequence 0, 1, 2.
  • The loop runs once for each value in that sequence.
  • Prints: For count: 0, 1, and 2.

When the sequence is exhausted, the loop exits automatically.

Structure Breakdown

1
2
for variable in iterable:
    # Loop body

This format is clean, readable, and flexible. Perfect for iteration over collections or generated sequences.

Use Cases

Use a for loop when:

  • You want to loop a fixed number of times.
  • You’re iterating through items in a list, string, or other iterable.
  • You want clear, structured iteration.

Real-World Example

1
2
for year in range(2020, 2026):
    print(f"Year: {year}")

This prints years from 2020 through 2025, showing how range(start, stop) lets you control the bounds of your loop.

Pro Tip: range() excludes the stop value. So range(2020, 2026) goes up to, but doesn’t include—2026.

For-Each Loop

In Python, the standard for loop already behaves like a for-each loop. It lets you iterate directly over elements of any iterable, like lists, strings, or sets, without needing to manage indexes manually.

Basic Example

1
2
3
4
fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits:
    print(fruit)

Explanation:

  • fruit is a temporary variable that holds each item from the list fruits.
  • On each loop iteration, Python assigns the next value from the list to fruit.
  • This prints each fruit in order:
1
2
3
Apple  
Banana  
Cherry

Syntax Structure

1
2
for item in iterable:
    # Code to execute
  • item is a placeholder for each element in the iterable.
  • iterable can be a list, tuple, string, dictionary, or any object that supports iteration.

When to Use

Use this style of for loop when:

  • You want to process each item in a sequence.
  • You don’t need the item’s index.
  • You’re focused on readability and simplicity.

Real-World Example

1
2
3
4
5
scores = [95, 87, 74, 66]

for score in scores:
    if score >= 90:
        print(f"Excellent: {score}")

This loops through the list of scores and prints only the high-performing ones.

Limitation: You can’t change the elements of the list directly during iteration. If you need to modify items in place, use a traditional loop with range() and indexing.

Break & Continue

In Python, break and continue are essential tools for managing control flow inside loops. They let you exit a loop early or skip specific iterations based on conditions, adding flexibility to your logic.

Example

1
2
3
4
5
6
for i in range(5):
    if i == 2:
        continue  # Skip this iteration
    if i == 4:
        break     # Exit the loop completely
    print(i)

Explanation:

  • When i == 2, continue skips the print statement and moves to the next iteration.
  • When i == 4, break exits the loop, even though more values are left in the range.
  • Output:
1
2
3
0  
1  
3

How They Work

  • continue — Skips the rest of the current iteration and moves to the next cycle of the loop.
  • break — Immediately exits the loop, no matter the condition.

When to Use

  • Use continue when:

    • You want to ignore certain items but keep looping.
    • You’re filtering or validating and need to skip specific cases.
  • Use break when:

    • A condition tells you to stop looping early.
    • You’ve found what you need and want to exit right away.

Real-World Analogy

Think of people in a line:

  • If someone doesn’t meet the entry criteria (continue), they’re skipped, but the line moves on.
  • If a “closed” sign goes up (break), the whole line is dismissed immediately.

Tip: Use break and continue thoughtfully. They’re powerful but can hurt readability if overused. Make your intent clear with good naming and comments.

Lists (Array Equivalent)

In Python, the closest equivalent to a Java array is a list, a flexible, built-in data structure that lets you store multiple values in a single variable. Unlike Java arrays, Python lists can grow or shrink in size and hold different types (though typically you’ll use consistent types for clarity).

Basic Example

1
2
3
4
5
6
7
numbers = [1, 2, 3]
print(numbers[1])  # 2

numbers[1] = 10

for n in numbers:
    print(n)

Explanation:

  • numbers = [1, 2, 3] creates a list of three elements.
  • numbers[1] accesses the second element (2), since indexing starts at 0.
  • numbers[1] = 10 updates the second element to 10.
  • The for loop iterates through the list and prints: 1, 10, 3.

List Characteristics

  • Dynamic size: Lists can grow or shrink, no fixed size required.
  • Zero-based indexing: First element is at index 0.
  • Flexible typing: Lists can hold mixed data types, but consistent types are recommended for simplicity.

Accessing and Modifying Lists

1
2
3
4
scores = [0] * 4  # creates a list with 4 elements, all set to 0
scores[0] = 95
scores[1] = 88
print(scores[0])  # prints 95

You can initialize a list with a fixed size and update values later, handy when preparing space for incoming data.

Looping Through Lists

  • Using range() with indexes (if you need the position):
1
2
for i in range(len(numbers)):
    print(f"Index {i}: {numbers[i]}")
  • Simple iteration (for readability):
1
2
for value in numbers:
    print(value)

Note: Unlike Java, you can modify list elements during a for-each style loop, just use their index if needed.

When to Use Lists

Lists are ideal when:

  • You need a collection of items (e.g., numbers, strings, objects).
  • The number of elements may change over time.
  • You’re performing looped or indexed operations like filtering, sorting, or aggregating data.

The IDE Advantage

A great IDE like PyCharm can seriously level up your Python workflow. From intelligent auto-completion and real-time error detection to built-in terminal access and integrated debugging, PyCharm turns writing Python code into a faster, more focused experience.

Syntax highlighting, linting, code navigation, and version control support aren’t just conveniences. They’re your allies in writing clean, correct, and maintainable code.

Conclusion

Python may be simple to start with, but it’s incredibly powerful and widely used across industries, from web development and automation to data science and AI. Its clear syntax, dynamic features, and massive ecosystem make it a perfect choice for both beginners and experienced developers.

By learning Python’s core syntax, data structures, and tools like PyCharm, you’re building a solid foundation for countless projects and careers.

Whether you’re starting out or sharpening your skills, keep experimenting, stay curious, and above all, keep coding.

This post is licensed under CC BY 4.0 by the author.