Basic Python Syntax
Python is built from five small ideas. Once you can read these, you can read 90% of automation scripts.
1. Variables
A variable is a label on a value. No type declaration needed:
name = "Ravi" # string
age = 28 # integer
salary = 850000.50 # float
is_active = True # boolean
2. Printing
print() shows anything you give it. The f"..." prefix lets you insert variables:
print(f"{name} earns Rs {salary} per year")
# Ravi earns Rs 850000.5 per year
3. Indentation matters
Python uses indentation (4 spaces) instead of curly braces to mark blocks. This is the single biggest gotcha for people coming from Java or JavaScript:
if age >= 18:
print("Adult") # indented = inside the if
print("Can vote") # still inside
print("Always runs") # back at the left edge, outside
Mix tabs and spaces and Python will throw IndentationError. Pick one (spaces) and use the same width everywhere.
4. Conditionals
score = 75
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
else:
grade = "C"
elif is "else if". The chain stops at the first true condition.
5. Comments
# starts a single-line comment. Everything after # on that line is ignored:
# This is a comment
age = 28 # so is this
Quick check
Q1. What does this print?
city = "Bangalore"
if city == "bangalore":
print("South")
else:
print("Other")
Hint: String comparison in Python is case-sensitive.
Answer: Other. "Bangalore" (capital B) is not equal to "bangalore" (lowercase b). Common bug, especially when reading data from user input or a database. Use .lower() to normalise: if city.lower() == "bangalore":.
Q2. Will this run?
score = 80
if score >= 75:
print("Pass")
Hint: Look at the indentation of the
Answer: No. Python expects the body of the if to be indented. You get IndentationError: expected an indented block. Add 4 spaces before print.
Try this
Type the snippet at the top into a file called intro.py and run python intro.py. Change age = 28 to age = 16 and re-run. The output should switch from "Adult" to "Minor".