Semantics (Meaning and Logic) Flashcards
Semantics in Python
Semantics
Semantics focuses on the intended meaning of the code.
Semantic errors occur when the code runs without syntax errors but produces incorrect results due to faulty logic or misuse of concepts.
Types of Semantic
- Type Compatibility
- Undefined Variables
- Logical Errors
- Control Flow Errors
Type Compatibility
Python is dynamically typed, but operations on incompatible types lead to runtime errors.
x = “10”
y = 5
print(x + y) # TypeError: can only concatenate str (not “int”) to str
Fix
print(int(x) + y) # Correct: Outputs 15
Undefined Variables
A variable must be initialized before it is used, even if the syntax is correct.
print(x) # NameError: name ‘x’ is not defined
Logical Errors
These are errors in the logic of the code that lead to unintended outcomes.
def is_even(num):
return num % 2 == 1 # Incorrect logic for checking even numbers
def is_even(num):
return num % 2 == 0
Control Flow Errors
These occur when the intended flow of the program is not achieved.
for i in range(5):
if i == 3:
continue
print(i) # This print statement is unreachable
for i in range(5):
if i == 3:
continue
print(i)
Why Syntax and Semantics Matter in Python
For Readability: Python’s strict syntax (e.g., indentation) ensures clean, readable code.
For Debugging: Semantic errors are harder to detect because the code runs without errors but produces the wrong results.
For Robust Programs: Understanding both aspects helps write error-free and maintainable programs.