Python Syntax

Python Syntax

1. Python File & Execution

  • Python files use the .py extension.
  • Run a file:

    python file_name.py
    
  • Indentation is required in Python — no {} for code blocks.

2. Indentation

  • Use spaces (recommended: 4 spaces) or tabs — be consistent.
  • Example:

    if True:
        print("Indented code runs")
    

3. Comments

  • Single-line:

    # This is a comment
    
  • Multi-line (technically multi-line strings used as comments):

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

4. Variables

  • No need to declare type — Python is dynamically typed.
  • Example:

    name = "Alice"    # string
    age = 25          # integer
    height = 5.6      # float
    is_student = True # boolean
    

5. Data Types

  • Basic: int, float, str, bool
  • Collections:

    • List – ordered, changeable: fruits = ["apple", "banana"]
    • Tuple – ordered, unchangeable: point = (4, 5)
    • Set – unordered, unique: unique_nums = {1, 2, 3}
    • Dictionary – key-value: person = {"name": "Alice", "age": 25}

6. Printing Output

print("Hello, World!")
print("Name:", name)
print(f"Name: {name}, Age: {age}")

7. Taking Input

name = input("Enter your name: ")
print("Hello", name)

8. Conditional Statements

x = 10
if x > 5:
    print("Greater than 5")
elif x == 5:
    print("Equal to 5")
else:
    print("Less than 5")

9. Loops

  • For loop:

    for i in range(5):
        print(i)
    
  • While loop:

    count = 0
    while count < 5:
        print(count)
        count += 1
    

10. Functions

def greet(name):
    return f"Hello, {name}"

print(greet("Alice"))

11. Importing Modules

import math
print(math.sqrt(16))

from datetime import date
print(date.today())


Previous Post Next Post