techmore.in

Python - Syntax

Python is a powerful and versatile programming language with simple and readable syntax, making it ideal for beginners and professionals alike. Below is an overview of Python's basic syntax:

1. Python Script Basics

Python scripts do not require explicit start or end tags, and the file extension is .py.

python
# Simple Python program print("Hello, World!")

2. Comments

Python uses the # symbol for single-line comments. Multi-line comments can be made using triple quotes (''' or """).

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

3. Variables and Data Types

Variables in Python are dynamically typed, meaning that you do not need to declare their type. Simply assign values to variables using the = operator.

python
x = 10 # Integer y = 3.14 # Float name = "Python" # String is_valid = True # Boolean

4. Data Structures

Python has several built-in data structures such as lists, tuples, sets, and dictionaries.

python
# List my_list = [1, 2, 3] # Tuple my_tuple = (1, 2, 3) # Set my_set = {1, 2, 3} # Dictionary my_dict = {"name": "Python", "version": 3.9}

5. Control Flow Statements

Python uses indentation (usually 4 spaces) to define blocks of code. The common control flow statements include if, for, while, etc.

python
# If-else statement if x > 5: print("x is greater than 5") else: print("x is less than or equal to 5") # For loop for i in range(5): print(i) # While loop i = 0 while i < 5: print(i) i += 1

6. Functions

Functions are defined using the def keyword.

python
def greet(name): return f"Hello, {name}!" print(greet("Alice")) # Outputs: Hello, Alice!

7. Classes

Python supports object-oriented programming, and classes can be defined using the class keyword.

python
class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Fido") print(my_dog.bark()) # Outputs: Fido says Woof!

8. Importing Modules

Python has a large standard library that can be imported into your program.

python
import math result = math.sqrt(16) print(result) # Outputs: 4.0

These are the fundamental elements of Python syntax, and the language's simplicity and readability make it popular for a wide range of applications, from web development to data science.