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
๐Ÿš€ Try this Live โ†’ Click to open interactive PYTHON playground

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)
๐Ÿš€ Try this Live โ†’ Click to open interactive PYTHON playground

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'>
    
๐Ÿš€ Try this Live โ†’ Click to open interactive PYTHON playground

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
๐Ÿš€ Try this Live โ†’ Click to open interactive PYTHON playground

๐ŸŽฏ Practice Project Assignment

๐Ÿ’ก Project: Simple Calculator with Type Conversion (Click to expand)

Your Challenge:

Create a calculator program that takes two numbers as input (simulated as strings) and performs all arithmetic operations we learned!

Implementation Hints:

  • Start with two string variables: num1_str = "15", num2_str = "4"
  • Convert them to int or float using int() or float()
  • Perform all 7 operations: +, -, *, /, //, %, **
  • Display results with f-strings and show data types
  • Bonus: Handle division by zero, try both int and float inputs

Example Output:

Calculator Results
==================
15 + 4 = 19
15 - 4 = 11
15 * 4 = 60
15 / 4 = 3.75

Share Your Solution! ๐Ÿ’ฌ

Once you've completed this project, share your code in the comments below! We'd love to see your creative solutions. Don't be shy - every coder started as a beginner! ๐Ÿš€


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! ๐Ÿ‘‡๐Ÿ’ฌ

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