Python Syntax

Python syntax is simple and easy to read, making it one of the most beginner-friendly programming languages. Let’s explore the basics of Python syntax! ๐Ÿš€

1. Writing Python Code

โœ” Python uses indentation instead of curly braces {}.
โœ” No need to declare variable types.
โœ” Code is executed line by line (interpreted language).

Example:

print("Hello, World!")  # Output: Hello, World!

Try It Now

2. Python Indentation

Python uses indentation to define blocks of code. Incorrect indentation will cause an error.

โœ… Correct Example:

if True:
    print("This is indented correctly.")  # Indentation is required

Try It Now

โŒ Incorrect Example (will cause an error):

if True:
print("This will cause an error.")  # No indentation

Try It Now

3. Python Comments

Comments are ignored by Python and are used for explanations.

โœ” Single-line Comment:

# This is a comment
print("Hello, Python!")  # This prints a message

Try It Now

โœ” Multi-line Comment:

"""
This is a multi-line comment.
It spans multiple lines.
"""
print("Python is awesome!")

Try It Now

4. Python Variables

โœ” Variables do not need explicit declaration.
โœ” The type is assigned automatically.

Example:

name = "Alice"  # String
age = 25        # Integer
height = 5.6    # Float
is_student = True  # Boolean

print(name, age, height, is_student)

Try It Now

5. Python Data Types

Data Type Example
String "Hello"
Integer 10
Float 3.14
Boolean True / False
List [1, 2, 3]
Tuple (1, 2, 3)
Dictionary {"name": "Alice", "age": 25}

6. Python Input & Output

โœ” Taking User Input:

name = input("Enter your name: ")
print("Welcome, " + name + "!")

Try It Now

โœ” Printing Multiple Values:

print("Python", "is", "fun", sep=" - ")  # Output: Python - is - fun

Try It Now

7. Python Case Sensitivity

Python is case-sensitive, meaning Name and name are different variables.

name = "Alice"
Name = "Bob"
print(name)  # Output: Alice
print(Name)  # Output: Bob

Try It Now

8. Python Line Breaks & Multiple Statements

โœ” Writing multiple statements on one line:

x = 10; y = 20; print(x + y)

Try It Now

โœ” Breaking long lines using \ (backslash):

total = 10 + 20 + \
        30 + 40
print(total)  # Output: 100

Try It Now

9. Python Code Execution

Python code can be executed in:

  • Python Shell (REPL) โ†’ python
  • Python Script (.py files) โ†’ python filename.py
  • IDEs (VS Code, PyCharm, etc.)