Python short tutorial


0:00
0:00

Python Tutorial (Easy & Modern Features)

Python is known for its readability and simplicity. It's great for web development, data science, automation, and more.

1. "Hello, World!"

# This is a comment - Python ignores it
print("Hello, Python World!")

Explanation:

  • #: Lines starting with # are comments, used for explaining code.
  • print(): A built-in Python function to display output to the console.
  • "Hello, Python World!": A string literal (text enclosed in quotes).

2. F-Strings (Formatted String Literals) (Python 3.6+):

A fantastic way to embed variables directly into strings. Much cleaner than older methods.

name = "Bob"
age = 25

# Use an f-string to embed variables
message = f"Hello, my name is {name} and I am {age} years old."
print(message)

# You can also include expressions
pi = 3.14159
print(f"The value of pi is approximately {pi:.2f}") # Format to 2 decimal places

Explanation:

  • f"...": The f or F before the quotes indicates it's an f-string.
  • {variable_name}: Place variable names or expressions inside curly braces {} to insert their values.
  • {pi:.2f}: .2f specifies formatting as a floating-point number (f) with 2 decimal places.

3. Type Hinting (Python 3.5+):

Specifies the expected types for variables, function arguments, and return values. It doesn't enforce types strictly at runtime but improves code readability and helps static analysis tools catch errors early.

def add(a: int, b: int) -> int:
    """This function takes two integers and returns their sum."""
    return a + b

result = add(5, 3)
print(f"The sum is: {result}")

def greet(name: str) -> None:
    """This function prints a greeting and doesn't return anything."""
    print(f"Hello, {name}!")

greet("Alice")

Explanation:

  • a: int: Specifies that variable a is expected to be an integer.
  • -> int: Specifies that the add function is expected to return an integer.
  • -> None: Specifies that the greet function doesn't explicitly return anything (it implicitly returns None).

4. Structural Pattern Matching (Python 3.10+):

A powerful way to match values against patterns, similar to switch statements but much more flexible.


def process_point(point):
    match point:
        case (0, 0):
            print("Point at the origin")
        case (x, 0):
            print(f"Point on the x-axis at x={x}")
        case (0, y):
            print(f"Point on the y-axis at y={y}")
        case (x, y):
            print(f"Point at ({x}, {y})")
        case _: # Wildcard pattern - matches anything else
            print("Unknown point format")

process_point((0, 0))
process_point((5, 0))
process_point((0, -2))
process_point((3, 4))
process_point("hello")

Explanation:

  • match point:: Starts the pattern matching block.
  • case (0, 0):: Matches if point is exactly the tuple (0, 0).
  • case (x, 0):: Matches if point is a tuple with two elements, where the second is 0. The first element is assigned to the variable x.
  • case (x, y):: Matches if point is a tuple with two elements, assigning them to x and y.
  • case _:: The wildcard case, matches if none of the previous patterns match.

5. Walrus Operator (:=) (Python 3.8+):

Allows assigning values to variables within an expression. It can sometimes make code cleaner, especially when you need to re-use the result of an operation immediately.

data = [1, 2, 3, 4, 5]

# Without walrus operator
# n = len(data)
# if n > 3:
#     print(f"List has {n} elements, which is more than 3.")

# With walrus operator
if (n := len(data)) > 3:
    print(f"List has {n} elements, which is more than 3.")

Explanation:

  • (n := len(data)): Assigns the result of len(data) to n and returns that result, which is then used in the if condition.

Running Python Code:

Save the code in a .py file (e.g., my_script.py). Open your terminal or command prompt, navigate to the directory where you saved it, and run:

python my_script.py  # Or python3 my_script.py


Last updated on August 15, 2025

🔍 Explore More Topics

Discover related content that might interest you

TwoAnswers Logo

Providing innovative solutions and exceptional experiences. Building the future.

© 2025 TwoAnswers.com. All rights reserved.

Made with by the TwoAnswers.com team