Post

02. Python Basics - Syntax and Data Types

🐍 Dive into the foundational elements of Python! Learn about syntax rules, data types like numbers and booleans, and how to work with variables to build robust and readable code. 🚀

02. Python Basics - Syntax and Data Types

What we will learn in this post?

  • 👉 Python Basic Syntax
  • 👉 Python Comments
  • 👉 Python Variables and Naming Conventions
  • 👉 Python Data Types Overview
  • 👉 Numeric Types - int, float, complex
  • 👉 Boolean Type and Logical Operations
  • 👉 Type Conversion and Casting
  • 👉 Conclusion!

Python’s Simple Syntax 🐍

Python is super easy to read because of its clean syntax! Let’s break down the key parts:

Indentation: The Key to Blocks🔑

Instead of curly braces {}, Python uses indentation (spaces or tabs) to define code blocks. This makes code neat and readable.

1
2
if 5 > 2:
  print("Five is greater than two!") # This line is part of the 'if' block

Statements & Line Continuation 📜

Each line usually represents a statement. For long lines, use a backslash \ for continuation:

1
2
3
4
long_string = "This is a very " \
              "long string that spans " \
              "multiple lines."
print(long_string)

Code Structure 🧱

  • A Python program is made of statements.
  • Statements are grouped into blocks using indentation.
  • Comments start with # and are ignored by Python.
1
2
3
4
5
6
# This is a comment
def my_function():
    """This is a docstring explaining the function."""
    print("Hello from a function!")

my_function() # Calling the function
  • Readability is key! Clear indentation and comments make your code easier to understand.
  • For a deeper understanding, check out the official Python documentation on control flow tools.
graph TD
    A[Start] --> B{Condition};
    B -- True --> C[Action 1];
    B -- False --> D[Action 2];
    C --> E[End];
    D --> E;

Comments: Your Code’s Best Friend 💬

Comments are notes you add to your code that the computer ignores. They explain what your code does.

Types of Comments 📝

  • Single-line comments: Use # at the start of a line. Great for quick explanations.

    1
    2
    
    # This line calculates the total price
    total = price * quantity
    
  • Multi-line comments (Docstrings): Use triple quotes ("""Docstring""" or '''Docstring''') to explain functions, classes, or modules.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    def add(x, y):
        """Adds two numbers together.
    
        Args:
            x: The first number.
            y: The second number.
    
        Returns:
            The sum of x and y.
        """
        return x + y
    

Why Use Comments? 🤔

Comments make your code:

  • Easier to understand: Especially for others (or your future self!).
  • Maintainable: Easier to update and fix.
  • Documented: Docstrings can be automatically used to create documentation.
  • Professional : Demonstrates good coding practices.

Best Practices

  • Be clear and concise.
  • Explain the why, not just the what.
  • Keep comments updated with code changes.
  • Use docstrings for public functions/classes/modules.

Good documentation helps us understand the code better 🧑‍💻 and makes it easy to maintain for the future 👨‍🔧.

For more information, check out the PEP 8 Style Guide for Python Code for some guidelines on how to write good comments.

Variables in Python 🐍

Python uses variables to store data. You don’t need to declare a variable’s type; Python figures it out! This is called dynamic typing.

Declaring and Using Variables

Just assign a value to a name:

1
2
3
4
5
6
7
name = "Alice" # Assigning a string
age = 30      # Assigning an integer
pi = 3.14159  # Assigning a float

print(name)   # Output: Alice
print(age)    # Output: 30
print(pi)     # Output: 3.14159

Variable Naming Rules

  • Must start with a letter or underscore (_).
  • Can contain letters, numbers, and underscores.
  • Case-sensitive (age and Age are different).
  • Cannot be a Python keyword (like if, for, while).

PEP 8 Naming Conventions

PEP 8 is the style guide for Python code.

  • snake_case: Use for variable and function names (e.g., my_variable, calculate_sum).
  • CONSTANT_CASE: Use for constants (values that shouldn’t change, e.g., MAX_SIZE = 100).
1
2
3
4
5
my_variable = 10
MAX_SIZE = 200

print(my_variable) # Output: 10
print(MAX_SIZE)  # Output: 200

Resources

Python Data Types 🐍

Let’s explore Python’s basic building blocks! These are the data types that Python uses to understand and work with different kinds of information.

Core Data Types

  • Numbers:
    • int: Whole numbers (e.g., 10, -5).

      1
      2
      
      x = 10
      print(type(x)) # <class 'int'>
      
    • float: Numbers with decimal points (e.g., 3.14, -2.5).

      1
      2
      
      y = 3.14
      print(type(y)) # <class 'float'>
      
    • complex: Numbers with a real and imaginary part (e.g., 2 + 3j).

      1
      2
      
      z = 2 + 3j
      print(type(z)) # <class 'complex'>
      
  • Text:
    • str: Sequences of characters (e.g., "Hello", 'Python').

      1
      2
      
      message = "Hello, World!"
      print(type(message)) # <class 'str'>
      
  • Boolean:
    • bool: Represents True or False values.

      1
      2
      
      is_true = True
      print(type(is_true)) # <class 'bool'>
      
  • Sequences:
    • list: Ordered, mutable collections of items (e.g., [1, 2, 3], ['a', 'b', 'c']).

      1
      2
      
      my_list = [1, "hello", True]
      print(type(my_list)) # <class 'list'>
      
    • tuple: Ordered, immutable collections of items (e.g., (1, 2, 3)).

      1
      2
      
      my_tuple = (1, 2, "world")
      print(type(my_tuple)) # <class 'tuple'>
      
  • Sets:
    • set: Unordered collections of unique items (e.g., {1, 2, 3}).

      1
      2
      3
      
      my_set = {1, 2, 2, 3} # Duplicates are removed automatically
      print(type(my_set)) # <class 'set'>
      print(my_set) # {1, 2, 3}
      
  • Mappings:
    • dict: Key-value pairs (e.g., {'name': 'Alice', 'age': 30}).

      1
      2
      
      my_dict = {"name": "Bob", "age": 25}
      print(type(my_dict)) # <class 'dict'>
      
  • None:
    • None: Represents the absence of a value.

      1
      2
      
      nothing = None
      print(type(nothing)) # <class 'NoneType'>
      

Type Checking with type()

The type() function tells you the data type of a variable. It’s like asking Python, “What kind of thing is this?”.

1
2
3
4
5
x = 5
print(type(x)) # <class 'int'>

name = "Charlie"
print(type(name)) # <class 'str'>

Type checking is important for avoiding errors in your code!

More resources

Here are a few resources where you can learn more about python’s data types:

Python Numeric Types 🔢

Python handles numbers in a few main ways:

Integers, Floats, and Complex Numbers 🧮

  • Integers (int): Whole numbers, like 10, -5, or 0.
  • Floating-point numbers (float): Numbers with decimal points, like 3.14 or -2.5.
  • Complex numbers (complex): Numbers with a real and imaginary part, like 2 + 3j.

Arithmetic Operations ➕

Python does all the usual math stuff:

  • + (addition), - (subtraction), * (multiplication), / (division), // (floor division - integer result), % (modulus - remainder), ** (exponentiation).
1
2
3
4
5
6
7
x = 10
y = 3
print(x + y) # 13
print(x / y) # 3.3333333333333335
print(x // y) # 3
print(x % y) # 1
print(x ** y) # 1000

Type Conversion 🔄

You can change numbers from one type to another:

  • int(): Converts to an integer.
  • float(): Converts to a float.
  • complex(): Creates a complex number.
1
2
3
4
5
num_int = 5
num_float = float(num_int)
print(num_float) # 5.0
num_complex = complex(num_int)
print(num_complex) # (5+0j)

Precision ⚙️

Floats have limited precision due to how they’re stored, so tiny errors can happen. Integers usually don’t have this problem and can represent very large numbers.

For more info on numeric types, check out the Python documentation.

Boolean Basics in Python 🐍

Let’s explore the world of Booleans, True and False values that are fundamental in Python! They are our on/off switches, influencing program flow based on conditions.

The bool Type and Truthiness 🧐

The bool type represents truth values. Everything in Python has a “truthiness” – it evaluates to either True or False in a boolean context. For instance, non-empty strings and non-zero numbers are generally True, while empty strings, zero, and None are False.

1
2
3
4
print(bool("Hello"))  # Output: True
print(bool(""))     # Output: False
print(bool(10))    # Output: True
print(bool(0))      # Output: False

Logical Operators ⚙️

These operators help us combine or negate boolean values:

  • and: Returns True if both operands are True.
  • or: Returns True if at least one operand is True.
  • not: Negates the operand (flips True to False and vice versa).
1
2
3
4
x = 5
print(x > 0 and x < 10) # Output: True
print(x < 0 or x > 2)   # Output: True
print(not(x > 10))    # Output: True

Comparison Operators ⚖️

Comparison operators (like ==, !=, >, <, >=, <=) compare values and always return a bool:

1
2
3
4
print(5 == 5)  # Output: True
print(5 != 6)  # Output: True
print(5 > 4)   # Output: True
print(5 < 6)   # Output: True

Here’s a simple if statement example using comparison and boolean:

1
2
3
age = 20
if age >= 18:
    print("You are an adult.") # Output: You are an adult.

Here is a resource for more info on Boolean values and conditions: Python Booleans

Type Conversion in Python 🐍

Hey there! Let’s explore how Python handles changing data types, also known as type conversion. There are two main types: implicit and explicit.

Implicit Conversion (Automatic)

Python sometimes converts types automatically. This usually happens when you’re doing math with different types, like an int and a float. Python will generally convert the int to a float to avoid losing information.

1
2
3
4
5
num_int = 10
num_float = 5.5
sum_nums = num_int + num_float # Implicit conversion int to float
print(sum_nums) # 15.5
print(type(sum_nums)) # <class 'float'>

Explicit Conversion (Manual)

Using int(), float(), str(), bool()

You can manually convert types using built-in functions:

  • int(): Converts to an integer.

    1
    2
    3
    4
    
    num_str = "123"
    num_int = int(num_str)
    print(num_int) # 123
    print(type(num_int)) # <class 'int'>
    
  • float(): Converts to a floating-point number.

    1
    2
    3
    4
    
    num_str = "3.14"
    num_float = float(num_str)
    print(num_float) # 3.14
    print(type(num_float)) # <class 'float'>
    
  • str(): Converts to a string.

    1
    2
    3
    4
    
    num_int = 42
    num_str = str(num_int)
    print(num_str) # 42
    print(type(num_str)) # <class 'str'>
    
  • bool(): Converts to a boolean (True or False).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    num_int = 0
    num_bool = bool(num_int) # Anything other than 0 is True
    print(num_bool) # False
    print(type(num_bool)) # <class 'bool'>
    
    num_int = 10
    num_bool = bool(num_int) # Anything other than 0 is True
    print(num_bool) # True
    print(type(num_bool)) # <class 'bool'>
    

Why is it Needed?

Type conversion is essential when:

  • You need to perform operations that require specific data types (like adding an integer to a float).
  • You’re receiving data from an external source (like a file or user input) that needs to be converted to the correct type for your program.
  • You want to present data in a specific format (e.g., converting a number to a string for display).

For example, if you’re taking input from a user via input(), it always returns a string. If you want to do math with that input, you must convert it to an int or float first!

1
2
3
age_str = input("Enter your age: ") # User inputs "25"
age = int(age_str)
print("Next year, you will be:", age + 1) # Next year, you will be: 26

Here are some resources for more info on the topic:

Okay, here are a few options for your conclusion statement, all formatted as requested and designed to be engaging and inviting:

Option 1:

Conclusion

So, what do you think? 🤔 Did you find this helpful? I’d love to hear your thoughts, suggestions, or even just a “hello” in the comments below! Let’s chat! 👇💬

Option 2:

Conclusion

That’s a wrap! 🎉 I’m super curious to know what resonated with you the most. Drop your comments, questions, or feedback below! Your input helps me create better content. Thanks! 💖

Option 3:

Conclusion

Alright, time to hear from you! 📣 What are your experiences with this topic? Any tips you’d like to share? Jump into the comments section – I’m eager to learn from you all! Let’s build a community! 🤝

Option 4:

Conclusion

Hope you enjoyed reading! 😄 Now it’s your turn! What are your thoughts? Any questions lingering? Share them in the comments! I’ll do my best to answer them. Happy commenting! ✍️

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