Python Basic Syntax

Python syntax is designed for readability and uses indentation to define code blocks. Here's a breakdown of the basics:

1. Indentation:

Unlike many other languages that use braces {}, Python uses indentation to define blocks of code. Consistent indentation (typically 4 spaces) is crucial.

if x > 5:
print("x is greater than 5") # Correct indentation

if x > 5:
print("x is greater than 5") # Incorrect indentation - will cause an error

2. Comments:

Comments explain your code. Use # for single-line comments and triple quotes ''' ''' or """ """ for multi-line comments.

# This is a single-line comment
'''
This is a
multi-line comment
'''
x = 10 # Comment at the end of a line

3. Variables:

Variables store data. Assignment is done using =. Variable names are case-sensitive. No explicit type declaration is needed (Python infers type).

name = "Tausif Khan"
age = 19
price = 99.99

4. Print Statement

The most common way to display information when programming is by printing the data directly onto your computer's output. In Python, this output capability is delivered with the print() function which is prebuilt within all native installs of Python on your computer. To utilize this, you need only use parentheses alongside the word print.

print("Hello, AIT!")

5. Data Types:

Python supports several data types including:

  • Integers (int): Whole numbers (e.g., 10, -5, 0).
  • Floats (float): Numbers with decimal points (e.g., 3.14, -2.5).
  • Strings (str): Sequences of characters enclosed in single or double quotes (e.g., "hello", 'Python').
  • Booleans (bool): True or False values.
  • Lists (list): Ordered, mutable sequences of items (e.g., [1, 2, "three"]).
  • Tuples (tuple): Ordered, immutable sequences of items (e.g., (1, 2, "three")).
  • Sets (set): Unordered collections of unique items (e.g., {1, 2, 3}).
  • Dictionaries (dict): Collections of key-value pairs (e.g., {"name": "Maaz", "age": 21}).