Python Syntax and Semantics

Loading

Introduction

Python is a high-level programming language known for its readability and simplicity. Understanding Python’s syntax and semantics is crucial for writing efficient and error-free code. This guide covers the fundamental syntax rules and semantic principles that govern Python programs.

1. Python Syntax Basics

1.1 Indentation

Python uses indentation instead of braces {} to define code blocks.

if True:
    print("This is inside the if block")

Note: Incorrect indentation will raise an IndentationError.

1.2 Variables and Data Types

Python is dynamically typed, meaning variables do not require explicit type declaration.

name = "Alice"  # String
iq = 120        # Integer
height = 5.9    # Float
is_student = True # Boolean

1.3 Comments

Python supports both single-line and multi-line comments.

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

1.4 Print Statement

The print() function is used to display output.

print("Hello, World!")

1.5 Taking User Input

Use input() to receive user input.

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

2. Python Semantics

2.1 Data Type Conversions

Python allows type conversion using built-in functions.

age = "25"
age = int(age)  # Convert string to integer

2.2 Control Flow Statements

Conditional Statements

x = 10
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is 5")
else:
    print("x is less than 5")

Loops

For Loop
for i in range(5):
    print(i)
While Loop
count = 0
while count < 5:
    print(count)
    count += 1

2.3 Functions

Functions allow code reuse and modular programming.

def greet(name):
    return "Hello, " + name

print(greet("Alice"))

2.4 Exception Handling

Use try-except to handle errors gracefully.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Leave a Reply

Your email address will not be published. Required fields are marked *