Syntax (Rules and Structure) Flashcards
syntax in python
What is Syntax in python
Syntax is a fixed set of rules that defines the correct structure, order, and format of Python code.
So that Python interpreter can parse and execute code without errors.
Types of Syntax
- Indentation
- Variable Names and Assignment
- Operators and Expressions
- Function Definition and Calls
Indentation
Unlike many other programming languages, Python uses indentation to define code blocks (loops, conditionals, functions, etc.), not braces {}.
def example_function():
for i in range(5):
print(i) # Indented to show it’s part of the loop
def example_function():
for i in range(5): # Missing indentation
print(i)
# Results in: IndentationError: expected an indented block
Variable Names and Assignment
Variable names must follow specific rules (e.g., cannot start with numbers or use special characters like @, $).
my_variable = 10
1st_variable = 10 # SyntaxError: invalid syntax
Operators and Expressions
Python has strict rules for how operators and expressions should be written.
result = 5 + 3
result = 5 + # SyntaxError: invalid syntax
Function Definition and Calls
Functions must have parentheses and colons in their definitions.
def greet(name):
return f”Hello, {name}!”
def greet name: # SyntaxError: invalid syntax (missing parentheses)
return f”Hello, {name}!”