Basics of python

Python syntax is designed to be readable and straightforward, making it an excellent language for beginners and experienced programmers alike. Here’s an overview of some basic syntax in Python:

1. Indentation

Python uses indentation to define blocks of code. Unlike other languages that use braces {} to indicate a block of code, Python uses indentation (a tab or four spaces). It is crucial for defining what code is inside loops, conditionals, functions, etc.

if 5 > 2:
    print("Five is greater than two!")
  1. Comments

Comments in Python start with a hash #. Anything following the hash in a line is ignored by the interpreter and is used to leave notes and explanations in the code.

# This is a comment
print("Hello, World!")  # This prints a message
  1. Variables

In Python, variables are created the moment you first assign a value to them, with no need to declare their type.

x = 5
y = "Hello, World!"
  1. Data Types

Python has various data types including integers, floats, strings, lists, tuples, dictionaries, etc. Python is dynamically-typed, meaning the type is inferred at runtime.

integer = 10
floating_point = 10.5
string = "Hello!"
list = [1, 2, 3]
tuple = (1, 2, 3)
dictionary = {"key": "value"}
  1. Operators

Python supports the usual arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators.


# Arithmetic operators
sum = 10 + 5

# Comparison operators
if sum > 10:
    print("Greater than ten")

# Logical operators
if sum > 10 and sum < 20:
    print("Between ten and twenty")
  1. Control Structures

Python uses standard control structures such as if, for, and while loops.

# if statement
if sum > 10:
    print("Greater than ten")

# for loop
for i in range(5):
    print(i)

# while loop
while sum < 20:
    sum += 1
  1. Functions

Functions in Python are defined using the def keyword. You can pass arguments and return values from functions.

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

print(greet("Alice"))
  1. Importing Modules

Python code can be organized into modules and packages. You can import a module to use its functions, classes, and variables within your program.

import math
print(math.sqrt(16))  # prints 4.0
  1. Exceptions Handling

Python handles exceptions using try, except, else, and finally blocks.

try:
    # Try to convert a string to an integer
    val = int("five")
except ValueError:
    print("That was not a number!")

This brief overview provides the fundamentals of Python syntax, but Python is rich with features, in the next chapters we will dive into more details which you need to understand before you can use it for testautomation like selenium