DEV Community

Cover image for ๐Ÿš€ Day 1 โ€“ Python Syntax & Idioms
RexTora
RexTora

Posted on

๐Ÿš€ Day 1 โ€“ Python Syntax & Idioms

Welcome to Day 1! Python is famous for its clean, readable syntaxโ€”often described as "executable pseudocode." This guide covers the foundational idioms you need to write clean, Pythonic code from the start.

1. What is Python?

Python is a high-level, interpreted, dynamically typed programming language.

  • High-level: You don't have to manage memory or worry about hardware details. ๐Ÿง 

  • Interpreted: Code is executed line-by-line by the Python interpreter at runtime, meaning there is no separate compilation step. โšก

  • Dynamically typed: You donโ€™t need to state whether a variable is a number, text, or a list when you create it. Python figures it out automatically. โš™๏ธ

Code Example: Dynamic Typing

Because Python is dynamically typed, the same variable name can point to entirely different types of data over time.

Python

current_status = "Learning"  # Starts as a string (str)
print(type(current_status))  # Output: <class 'str'>

current_status = 100         # Changes to an integer (int)
print(type(current_status))  # Output: <class 'int'>
Enter fullscreen mode Exit fullscreen mode

2. Variables & Naming Conventions ๐Ÿท๏ธ

In Python, a variable is not a physical "box" that holds data; it is a label or pointer attached to an object in memory. Following the standard Python style guide (PEP 8) keeps your code clean and readable for other developers. ๐Ÿค

Naming Rules (PEP 8):

  • snake_case: Lowercase letters with underscores for variables and functions.

  • PascalCase: Capitalize the first letter of each word for class names.

  • UPPERCASE: All caps for constants (variables meant to remain unchanged).

  • Variables cannot start with a number and are strictly case-sensitive (age and Age are distinct).

Code Example: Pythonic Naming

Python

# ๐Ÿ‘ GOOD (Pythonic style)
user_growth_rate = 12.5      # snake_case for variables
def calculate_roi(): pass    # snake_case for functions
MAX_TIMEOUT_SECONDS = 30     # UPPERCASE for constants

# ๐Ÿ‘Ž BAD (Unpythonic syntax or errors)
userGrowthRate = 12.5        # Avoid camelCase in standard Python
UserGrowthRate = 12.5        # Avoid PascalCase for normal variables (save for Classes)
3_strikes_rule = "Out"       # SyntaxError: Cannot start with a number
Enter fullscreen mode Exit fullscreen mode

3. Data Types ๐Ÿ“Š

Python handles several built-in data types out of the box. They are broadly split into single scalar values and multi-item collections. ๐Ÿ—‚๏ธ

Category Type Description Example
Numeric int, float Integers and decimal numbers 42, 3.14
Text str Text string literals "Hello, Python!"
Boolean bool True or False states True, False
Sequence list Ordered, editable (mutable) collection ["python", "coding"]
Sequence tuple Ordered, unchangeable (immutable) array (1920, 1080)
Mapping dict Key-value pairs (dictionaries) {"id": 101, "name": "Alice"}
Set set Unordered collection of unique items {1, 2, 3}

Code Example: Declaring Types

Python

# Scalar Types
age = 28                         
price = 49.99                    
is_active = True                 

# Collection Types
tags = ["python", "coding"]      # list
dimensions = (1920, 1080)        # tuple (great for structural data like coordinates)
user_profile = {"id": 101}       # dict
unique_ids = {101, 102, 101}     # set (automatically drops duplicates, leaving {101, 102})
Enter fullscreen mode Exit fullscreen mode

4. Truthy & Falsy Values ๐Ÿค”

In Python, every single value evaluates to a boolean context when used inside a conditional statement (like an if block). A value is either Truthy (behaves like True) or Falsy (behaves like False).

Instead of writing clunky checks like if len(my_list) == 0:, the idiomatic Python approach is simply if not my_list:. ๐ŸŽฏ

The Falsy Hall of Fame:

  • None

  • False

  • Zero of any numeric type: 0, 0.0

  • Empty sequences and collections: "", [], (), {}, set()

  • Everything else is considered Truthy. โœจ

Code Example: Clean Boolean Checks

Python

# Checking for an empty string input
submitted_username = "" # Empty string is Falsy

if not submitted_username:
    print("Error: Username cannot be blank.")

# Checking a populated list
active_notifications = ["Alert: Low Battery", "Update Available"] # Populated list is Truthy

if active_notifications:
    print(f"You have {len(active_notifications)} unread notifications.")
Enter fullscreen mode Exit fullscreen mode

5. f-Strings (Formatted String Literals) โšก

f-strings are the gold standard for embedding variables or running expressions directly inside strings. Just prefix your string with an f or F and use curly braces {}. ๐Ÿ› ๏ธ

Code Example: Evaluation and Formatting

Python

# Math expressions and variables inside a string
item = "Coffee"
price = 4.50
quantity = 3
print(f"Total for {quantity} {item}s: ${price * quantity}") 
# Output: Total for 3 Coffees: $13.5

# Formatting floats (limiting decimal places)
pi_value = 3.14159265
print(f"Pi to two decimal places: {pi_value:.2f}") 
# Output: Pi to two decimal places: 3.14
Enter fullscreen mode Exit fullscreen mode

6. Multiple Assignment & Unpacking ๐ŸŽ

Python allows you to assign values to multiple variables simultaneously or pull elements out of sequences cleanly in a single line. This lets you write incredibly elegant, line-saving code. ๐Ÿช„

Code Example: The Variable Swap & Target Unpacking

Python

# The classic variable swap (No temporary third variable required!)
a = "Water"
b = "Wine"

a, b = b, a 
print(f"a: {a}, b: {b}") # Output: a: Wine, b: Water

# Unpacking elements from structural tuples
coordinates = (40.7128, -74.0060)
lat, lon = coordinates  # lat = 40.7128, lon = -74.0060

# Ignoring specific values during unpacking using an underscore (_)
api_response = (200, "Success", {"user_id": 42})
status_code, _, data = api_response # We choose to ignore the middle message string

# Advanced unpacking using the * (star) operator
numbers = [1, 2, 3, 4, 5]
first, second, *rest = numbers
print(rest)   # Output: [3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

7. Type Hints ๐Ÿ’ก

Because Python is dynamically typed, scripts can become confusing as they scale. Type hints allow you to explicitly document what kind of data variables and functions expect. ๐Ÿ“

Note: Python does not enforce these types at runtime. They exist for readability, auto-complete help in your IDE, and static analysis checkers like mypy. ๐Ÿ”

Code Example: Hinting Functions and Collections

Python

# Hinting function inputs and return outputs
def calculate_tax(amount: float, tax_rate: float) -> float:
    return amount * tax_rate

# Hinting standalone variables and built-in collections
score: int = 100
is_game_over: bool = False

# Native collection hinting (Python 3.9+)
guest_list: list[str] = ["Alice", "Bob", "Charlie"]
inventory_count: dict[str, int] = {"Apples": 50, "Oranges": 20}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)