Python Syntax

Python has a straightforward and clean syntax, making it easy to read and write code. Here are some key syntax rules in Python:

  • Indentation: Python uses indentation to define code blocks instead of braces or keywords like other languages.
  • Statements: Python statements are executed line by line, and each statement is terminated by a newline character.
  • Comments: Single-line comments start with a hash symbol (#), and multi-line comments are enclosed between triple quotes (""" or ''').

Indentation

Indentation is crucial in Python, as it defines the scope and structure of the code. Incorrect indentation can lead to syntax errors. Here's an example:

if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")

 

Comments

Comments are used to explain the code or add notes for better understanding. They are ignored by the Python interpreter.

# This is a single-line comment
"""
This is a
multi-line comment
"""

Variables

In Python, variables are used to store data. They don't need explicit declaration of data types; the interpreter automatically determines the type based on the assigned value.

x = 5       # int
y = 3.14    # float
z = "Hello" # str

Data Types

Python supports various data types, including:

  • Integers (e.g., 1, -5, 0)
  • Floating-point numbers (e.g., 3.14, -0.5, 2.0)
  • Strings (e.g., "Hello", 'World')
  • Booleans (e.g., True, False)
  • Lists (e.g., [1, 2, 3], ["apple", "banana"])
  • Tuples (e.g., (1, 2, 3), ("apple", "banana"))
  • Dictionaries (e.g., {"name": "Alice", "age": 25})
  • Sets (e.g., {1, 2, 3}, {"apple", "banana"})

Type Conversion

Python allows you to convert data types using built-in functions like int(), float(), str(), and more.

x = int(3.14)   # x = 3
y = float("3.14") # y = 3.14
z = str(42)     # z = "42"

In the next chapter, we'll explore Operators and Expressions, which are essential for creating dynamic and interactive programs.